blob: b622e73a326ad7163cdf938425c75fb9c9e1cade [file] [log] [blame]
Paolo Valenteaee69d72017-04-19 08:29:02 -06001/*
2 * Budget Fair Queueing (BFQ) I/O scheduler.
3 *
4 * Based on ideas and code from CFQ:
5 * Copyright (C) 2003 Jens Axboe <axboe@kernel.dk>
6 *
7 * Copyright (C) 2008 Fabio Checconi <fabio@gandalf.sssup.it>
8 * Paolo Valente <paolo.valente@unimore.it>
9 *
10 * Copyright (C) 2010 Paolo Valente <paolo.valente@unimore.it>
11 * Arianna Avanzini <avanzini@google.com>
12 *
13 * Copyright (C) 2017 Paolo Valente <paolo.valente@linaro.org>
14 *
15 * This program is free software; you can redistribute it and/or
16 * modify it under the terms of the GNU General Public License as
17 * published by the Free Software Foundation; either version 2 of the
18 * License, or (at your option) any later version.
19 *
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 * General Public License for more details.
24 *
25 * BFQ is a proportional-share I/O scheduler, with some extra
26 * low-latency capabilities. BFQ also supports full hierarchical
27 * scheduling through cgroups. Next paragraphs provide an introduction
28 * on BFQ inner workings. Details on BFQ benefits, usage and
29 * limitations can be found in Documentation/block/bfq-iosched.txt.
30 *
31 * BFQ is a proportional-share storage-I/O scheduling algorithm based
32 * on the slice-by-slice service scheme of CFQ. But BFQ assigns
33 * budgets, measured in number of sectors, to processes instead of
34 * time slices. The device is not granted to the in-service process
35 * for a given time slice, but until it has exhausted its assigned
36 * budget. This change from the time to the service domain enables BFQ
37 * to distribute the device throughput among processes as desired,
38 * without any distortion due to throughput fluctuations, or to device
39 * internal queueing. BFQ uses an ad hoc internal scheduler, called
40 * B-WF2Q+, to schedule processes according to their budgets. More
41 * precisely, BFQ schedules queues associated with processes. Each
42 * process/queue is assigned a user-configurable weight, and B-WF2Q+
43 * guarantees that each queue receives a fraction of the throughput
44 * proportional to its weight. Thanks to the accurate policy of
45 * B-WF2Q+, BFQ can afford to assign high budgets to I/O-bound
46 * processes issuing sequential requests (to boost the throughput),
47 * and yet guarantee a low latency to interactive and soft real-time
48 * applications.
49 *
50 * In particular, to provide these low-latency guarantees, BFQ
51 * explicitly privileges the I/O of two classes of time-sensitive
52 * applications: interactive and soft real-time. This feature enables
53 * BFQ to provide applications in these classes with a very low
54 * latency. Finally, BFQ also features additional heuristics for
55 * preserving both a low latency and a high throughput on NCQ-capable,
56 * rotational or flash-based devices, and to get the job done quickly
57 * for applications consisting in many I/O-bound processes.
58 *
Paolo Valente43c1b3d2017-05-09 12:54:23 +020059 * NOTE: if the main or only goal, with a given device, is to achieve
60 * the maximum-possible throughput at all times, then do switch off
61 * all low-latency heuristics for that device, by setting low_latency
62 * to 0.
63 *
Paolo Valenteaee69d72017-04-19 08:29:02 -060064 * BFQ is described in [1], where also a reference to the initial, more
65 * theoretical paper on BFQ can be found. The interested reader can find
66 * in the latter paper full details on the main algorithm, as well as
67 * formulas of the guarantees and formal proofs of all the properties.
68 * With respect to the version of BFQ presented in these papers, this
69 * implementation adds a few more heuristics, such as the one that
70 * guarantees a low latency to soft real-time applications, and a
71 * hierarchical extension based on H-WF2Q+.
72 *
73 * B-WF2Q+ is based on WF2Q+, which is described in [2], together with
74 * H-WF2Q+, while the augmented tree used here to implement B-WF2Q+
75 * with O(log N) complexity derives from the one introduced with EEVDF
76 * in [3].
77 *
78 * [1] P. Valente, A. Avanzini, "Evolution of the BFQ Storage I/O
79 * Scheduler", Proceedings of the First Workshop on Mobile System
80 * Technologies (MST-2015), May 2015.
81 * http://algogroup.unimore.it/people/paolo/disk_sched/mst-2015.pdf
82 *
83 * [2] Jon C.R. Bennett and H. Zhang, "Hierarchical Packet Fair Queueing
84 * Algorithms", IEEE/ACM Transactions on Networking, 5(5):675-689,
85 * Oct 1997.
86 *
87 * http://www.cs.cmu.edu/~hzhang/papers/TON-97-Oct.ps.gz
88 *
89 * [3] I. Stoica and H. Abdel-Wahab, "Earliest Eligible Virtual Deadline
90 * First: A Flexible and Accurate Mechanism for Proportional Share
91 * Resource Allocation", technical report.
92 *
93 * http://www.cs.berkeley.edu/~istoica/papers/eevdf-tr-95.pdf
94 */
95#include <linux/module.h>
96#include <linux/slab.h>
97#include <linux/blkdev.h>
Arianna Avanzinie21b7a02017-04-12 18:23:08 +020098#include <linux/cgroup.h>
Paolo Valenteaee69d72017-04-19 08:29:02 -060099#include <linux/elevator.h>
100#include <linux/ktime.h>
101#include <linux/rbtree.h>
102#include <linux/ioprio.h>
103#include <linux/sbitmap.h>
104#include <linux/delay.h>
105
106#include "blk.h"
107#include "blk-mq.h"
108#include "blk-mq-tag.h"
109#include "blk-mq-sched.h"
Paolo Valenteea25da42017-04-19 08:48:24 -0600110#include "bfq-iosched.h"
Luca Micciob5dc5d42017-10-09 16:27:21 +0200111#include "blk-wbt.h"
Paolo Valenteaee69d72017-04-19 08:29:02 -0600112
113#define BFQ_BFQQ_FNS(name) \
Paolo Valenteea25da42017-04-19 08:48:24 -0600114void bfq_mark_bfqq_##name(struct bfq_queue *bfqq) \
Paolo Valenteaee69d72017-04-19 08:29:02 -0600115{ \
116 __set_bit(BFQQF_##name, &(bfqq)->flags); \
117} \
Paolo Valenteea25da42017-04-19 08:48:24 -0600118void bfq_clear_bfqq_##name(struct bfq_queue *bfqq) \
Paolo Valenteaee69d72017-04-19 08:29:02 -0600119{ \
120 __clear_bit(BFQQF_##name, &(bfqq)->flags); \
121} \
Paolo Valenteea25da42017-04-19 08:48:24 -0600122int bfq_bfqq_##name(const struct bfq_queue *bfqq) \
Paolo Valenteaee69d72017-04-19 08:29:02 -0600123{ \
124 return test_bit(BFQQF_##name, &(bfqq)->flags); \
125}
126
Arianna Avanzinie1b23242017-04-12 18:23:20 +0200127BFQ_BFQQ_FNS(just_created);
Paolo Valenteaee69d72017-04-19 08:29:02 -0600128BFQ_BFQQ_FNS(busy);
129BFQ_BFQQ_FNS(wait_request);
130BFQ_BFQQ_FNS(non_blocking_wait_rq);
131BFQ_BFQQ_FNS(fifo_expire);
Paolo Valented5be3fe2017-08-04 07:35:10 +0200132BFQ_BFQQ_FNS(has_short_ttime);
Paolo Valenteaee69d72017-04-19 08:29:02 -0600133BFQ_BFQQ_FNS(sync);
Paolo Valenteaee69d72017-04-19 08:29:02 -0600134BFQ_BFQQ_FNS(IO_bound);
Arianna Avanzinie1b23242017-04-12 18:23:20 +0200135BFQ_BFQQ_FNS(in_large_burst);
Arianna Avanzini36eca892017-04-12 18:23:16 +0200136BFQ_BFQQ_FNS(coop);
137BFQ_BFQQ_FNS(split_coop);
Paolo Valente77b7dce2017-04-12 18:23:13 +0200138BFQ_BFQQ_FNS(softrt_update);
Paolo Valenteea25da42017-04-19 08:48:24 -0600139#undef BFQ_BFQQ_FNS \
Paolo Valenteaee69d72017-04-19 08:29:02 -0600140
Paolo Valenteaee69d72017-04-19 08:29:02 -0600141/* Expiration time of sync (0) and async (1) requests, in ns. */
142static const u64 bfq_fifo_expire[2] = { NSEC_PER_SEC / 4, NSEC_PER_SEC / 8 };
143
144/* Maximum backwards seek (magic number lifted from CFQ), in KiB. */
145static const int bfq_back_max = 16 * 1024;
146
147/* Penalty of a backwards seek, in number of sectors. */
148static const int bfq_back_penalty = 2;
149
150/* Idling period duration, in ns. */
151static u64 bfq_slice_idle = NSEC_PER_SEC / 125;
152
153/* Minimum number of assigned budgets for which stats are safe to compute. */
154static const int bfq_stats_min_budgets = 194;
155
156/* Default maximum budget values, in sectors and number of requests. */
157static const int bfq_default_max_budget = 16 * 1024;
158
Paolo Valentec074170e2017-04-12 18:23:11 +0200159/*
160 * Async to sync throughput distribution is controlled as follows:
161 * when an async request is served, the entity is charged the number
162 * of sectors of the request, multiplied by the factor below
163 */
164static const int bfq_async_charge_factor = 10;
165
Paolo Valenteaee69d72017-04-19 08:29:02 -0600166/* Default timeout values, in jiffies, approximating CFQ defaults. */
Paolo Valenteea25da42017-04-19 08:48:24 -0600167const int bfq_timeout = HZ / 8;
Paolo Valenteaee69d72017-04-19 08:29:02 -0600168
Paolo Valente7b8fa3b2017-12-20 12:38:33 +0100169/*
170 * Time limit for merging (see comments in bfq_setup_cooperator). Set
171 * to the slowest value that, in our tests, proved to be effective in
172 * removing false positives, while not causing true positives to miss
173 * queue merging.
174 *
175 * As can be deduced from the low time limit below, queue merging, if
176 * successful, happens at the very beggining of the I/O of the involved
177 * cooperating processes, as a consequence of the arrival of the very
178 * first requests from each cooperator. After that, there is very
179 * little chance to find cooperators.
180 */
181static const unsigned long bfq_merge_time_limit = HZ/10;
182
Paolo Valenteaee69d72017-04-19 08:29:02 -0600183static struct kmem_cache *bfq_pool;
184
Paolo Valenteab0e43e2017-04-12 18:23:10 +0200185/* Below this threshold (in ns), we consider thinktime immediate. */
Paolo Valenteaee69d72017-04-19 08:29:02 -0600186#define BFQ_MIN_TT (2 * NSEC_PER_MSEC)
187
188/* hw_tag detection: parallel requests threshold and min samples needed. */
189#define BFQ_HW_QUEUE_THRESHOLD 4
190#define BFQ_HW_QUEUE_SAMPLES 32
191
192#define BFQQ_SEEK_THR (sector_t)(8 * 100)
193#define BFQQ_SECT_THR_NONROT (sector_t)(2 * 32)
194#define BFQQ_CLOSE_THR (sector_t)(8 * 1024)
Paolo Valentef0ba5ea2017-12-20 17:27:36 +0100195#define BFQQ_SEEKY(bfqq) (hweight32(bfqq->seek_history) > 19)
Paolo Valenteaee69d72017-04-19 08:29:02 -0600196
Paolo Valenteab0e43e2017-04-12 18:23:10 +0200197/* Min number of samples required to perform peak-rate update */
198#define BFQ_RATE_MIN_SAMPLES 32
199/* Min observation time interval required to perform a peak-rate update (ns) */
200#define BFQ_RATE_MIN_INTERVAL (300*NSEC_PER_MSEC)
201/* Target observation time interval for a peak-rate update (ns) */
202#define BFQ_RATE_REF_INTERVAL NSEC_PER_SEC
Paolo Valenteaee69d72017-04-19 08:29:02 -0600203
Paolo Valentebc56e2c2018-03-26 16:06:24 +0200204/*
205 * Shift used for peak-rate fixed precision calculations.
206 * With
207 * - the current shift: 16 positions
208 * - the current type used to store rate: u32
209 * - the current unit of measure for rate: [sectors/usec], or, more precisely,
210 * [(sectors/usec) / 2^BFQ_RATE_SHIFT] to take into account the shift,
211 * the range of rates that can be stored is
212 * [1 / 2^BFQ_RATE_SHIFT, 2^(32 - BFQ_RATE_SHIFT)] sectors/usec =
213 * [1 / 2^16, 2^16] sectors/usec = [15e-6, 65536] sectors/usec =
214 * [15, 65G] sectors/sec
215 * Which, assuming a sector size of 512B, corresponds to a range of
216 * [7.5K, 33T] B/sec
217 */
Paolo Valenteaee69d72017-04-19 08:29:02 -0600218#define BFQ_RATE_SHIFT 16
219
Paolo Valente44e44a12017-04-12 18:23:12 +0200220/*
221 * By default, BFQ computes the duration of the weight raising for
222 * interactive applications automatically, using the following formula:
223 * duration = (R / r) * T, where r is the peak rate of the device, and
224 * R and T are two reference parameters.
Paolo Valente8a8747d2018-01-13 12:05:18 +0100225 * In particular, R is the peak rate of the reference device (see
226 * below), and T is a reference time: given the systems that are
227 * likely to be installed on the reference device according to its
228 * speed class, T is about the maximum time needed, under BFQ and
229 * while reading two files in parallel, to load typical large
230 * applications on these systems (see the comments on
231 * max_service_from_wr below, for more details on how T is obtained).
232 * In practice, the slower/faster the device at hand is, the more/less
233 * it takes to load applications with respect to the reference device.
234 * Accordingly, the longer/shorter BFQ grants weight raising to
235 * interactive applications.
Paolo Valente44e44a12017-04-12 18:23:12 +0200236 *
237 * BFQ uses four different reference pairs (R, T), depending on:
238 * . whether the device is rotational or non-rotational;
239 * . whether the device is slow, such as old or portable HDDs, as well as
240 * SD cards, or fast, such as newer HDDs and SSDs.
241 *
242 * The device's speed class is dynamically (re)detected in
243 * bfq_update_peak_rate() every time the estimated peak rate is updated.
244 *
245 * In the following definitions, R_slow[0]/R_fast[0] and
246 * T_slow[0]/T_fast[0] are the reference values for a slow/fast
247 * rotational device, whereas R_slow[1]/R_fast[1] and
248 * T_slow[1]/T_fast[1] are the reference values for a slow/fast
249 * non-rotational device. Finally, device_speed_thresh are the
250 * thresholds used to switch between speed classes. The reference
251 * rates are not the actual peak rates of the devices used as a
252 * reference, but slightly lower values. The reason for using these
253 * slightly lower values is that the peak-rate estimator tends to
254 * yield slightly lower values than the actual peak rate (it can yield
255 * the actual peak rate only if there is only one process doing I/O,
256 * and the process does sequential I/O).
257 *
258 * Both the reference peak rates and the thresholds are measured in
259 * sectors/usec, left-shifted by BFQ_RATE_SHIFT.
260 */
261static int R_slow[2] = {1000, 10700};
262static int R_fast[2] = {14000, 33000};
263/*
264 * To improve readability, a conversion function is used to initialize the
265 * following arrays, which entails that they can be initialized only in a
266 * function.
267 */
268static int T_slow[2];
269static int T_fast[2];
270static int device_speed_thresh[2];
271
Paolo Valente8a8747d2018-01-13 12:05:18 +0100272/*
273 * BFQ uses the above-detailed, time-based weight-raising mechanism to
274 * privilege interactive tasks. This mechanism is vulnerable to the
275 * following false positives: I/O-bound applications that will go on
276 * doing I/O for much longer than the duration of weight
277 * raising. These applications have basically no benefit from being
278 * weight-raised at the beginning of their I/O. On the opposite end,
279 * while being weight-raised, these applications
280 * a) unjustly steal throughput to applications that may actually need
281 * low latency;
282 * b) make BFQ uselessly perform device idling; device idling results
283 * in loss of device throughput with most flash-based storage, and may
284 * increase latencies when used purposelessly.
285 *
286 * BFQ tries to reduce these problems, by adopting the following
287 * countermeasure. To introduce this countermeasure, we need first to
288 * finish explaining how the duration of weight-raising for
289 * interactive tasks is computed.
290 *
291 * For a bfq_queue deemed as interactive, the duration of weight
292 * raising is dynamically adjusted, as a function of the estimated
293 * peak rate of the device, so as to be equal to the time needed to
294 * execute the 'largest' interactive task we benchmarked so far. By
295 * largest task, we mean the task for which each involved process has
296 * to do more I/O than for any of the other tasks we benchmarked. This
297 * reference interactive task is the start-up of LibreOffice Writer,
298 * and in this task each process/bfq_queue needs to have at most ~110K
299 * sectors transferred.
300 *
301 * This last piece of information enables BFQ to reduce the actual
302 * duration of weight-raising for at least one class of I/O-bound
303 * applications: those doing sequential or quasi-sequential I/O. An
304 * example is file copy. In fact, once started, the main I/O-bound
305 * processes of these applications usually consume the above 110K
306 * sectors in much less time than the processes of an application that
307 * is starting, because these I/O-bound processes will greedily devote
308 * almost all their CPU cycles only to their target,
309 * throughput-friendly I/O operations. This is even more true if BFQ
310 * happens to be underestimating the device peak rate, and thus
311 * overestimating the duration of weight raising. But, according to
312 * our measurements, once transferred 110K sectors, these processes
313 * have no right to be weight-raised any longer.
314 *
315 * Basing on the last consideration, BFQ ends weight-raising for a
316 * bfq_queue if the latter happens to have received an amount of
317 * service at least equal to the following constant. The constant is
318 * set to slightly more than 110K, to have a minimum safety margin.
319 *
320 * This early ending of weight-raising reduces the amount of time
321 * during which interactive false positives cause the two problems
322 * described at the beginning of these comments.
323 */
324static const unsigned long max_service_from_wr = 120000;
325
Bart Van Assche12cd3a22017-08-30 11:42:11 -0700326#define RQ_BIC(rq) icq_to_bic((rq)->elv.priv[0])
Paolo Valenteaee69d72017-04-19 08:29:02 -0600327#define RQ_BFQQ(rq) ((rq)->elv.priv[1])
328
Paolo Valenteea25da42017-04-19 08:48:24 -0600329struct bfq_queue *bic_to_bfqq(struct bfq_io_cq *bic, bool is_sync)
330{
331 return bic->bfqq[is_sync];
332}
333
334void bic_set_bfqq(struct bfq_io_cq *bic, struct bfq_queue *bfqq, bool is_sync)
335{
336 bic->bfqq[is_sync] = bfqq;
337}
338
339struct bfq_data *bic_to_bfqd(struct bfq_io_cq *bic)
340{
341 return bic->icq.q->elevator->elevator_data;
342}
343
Paolo Valenteaee69d72017-04-19 08:29:02 -0600344/**
345 * icq_to_bic - convert iocontext queue structure to bfq_io_cq.
346 * @icq: the iocontext queue.
347 */
348static struct bfq_io_cq *icq_to_bic(struct io_cq *icq)
349{
350 /* bic->icq is the first member, %NULL will convert to %NULL */
351 return container_of(icq, struct bfq_io_cq, icq);
352}
353
354/**
355 * bfq_bic_lookup - search into @ioc a bic associated to @bfqd.
356 * @bfqd: the lookup key.
357 * @ioc: the io_context of the process doing I/O.
358 * @q: the request queue.
359 */
360static struct bfq_io_cq *bfq_bic_lookup(struct bfq_data *bfqd,
361 struct io_context *ioc,
362 struct request_queue *q)
363{
364 if (ioc) {
365 unsigned long flags;
366 struct bfq_io_cq *icq;
367
368 spin_lock_irqsave(q->queue_lock, flags);
369 icq = icq_to_bic(ioc_lookup_icq(ioc, q));
370 spin_unlock_irqrestore(q->queue_lock, flags);
371
372 return icq;
373 }
374
375 return NULL;
376}
377
378/*
Arianna Avanzinie21b7a02017-04-12 18:23:08 +0200379 * Scheduler run of queue, if there are requests pending and no one in the
380 * driver that will restart queueing.
Paolo Valenteaee69d72017-04-19 08:29:02 -0600381 */
Paolo Valenteea25da42017-04-19 08:48:24 -0600382void bfq_schedule_dispatch(struct bfq_data *bfqd)
Paolo Valenteaee69d72017-04-19 08:29:02 -0600383{
Arianna Avanzinie21b7a02017-04-12 18:23:08 +0200384 if (bfqd->queued != 0) {
385 bfq_log(bfqd, "schedule dispatch");
386 blk_mq_run_hw_queues(bfqd->queue, true);
387 }
Paolo Valenteaee69d72017-04-19 08:29:02 -0600388}
389
Paolo Valenteaee69d72017-04-19 08:29:02 -0600390#define bfq_class_idle(bfqq) ((bfqq)->ioprio_class == IOPRIO_CLASS_IDLE)
391#define bfq_class_rt(bfqq) ((bfqq)->ioprio_class == IOPRIO_CLASS_RT)
392
393#define bfq_sample_valid(samples) ((samples) > 80)
394
395/*
Paolo Valenteaee69d72017-04-19 08:29:02 -0600396 * Lifted from AS - choose which of rq1 and rq2 that is best served now.
397 * We choose the request that is closesr to the head right now. Distance
398 * behind the head is penalized and only allowed to a certain extent.
399 */
400static struct request *bfq_choose_req(struct bfq_data *bfqd,
401 struct request *rq1,
402 struct request *rq2,
403 sector_t last)
404{
405 sector_t s1, s2, d1 = 0, d2 = 0;
406 unsigned long back_max;
407#define BFQ_RQ1_WRAP 0x01 /* request 1 wraps */
408#define BFQ_RQ2_WRAP 0x02 /* request 2 wraps */
409 unsigned int wrap = 0; /* bit mask: requests behind the disk head? */
410
411 if (!rq1 || rq1 == rq2)
412 return rq2;
413 if (!rq2)
414 return rq1;
415
416 if (rq_is_sync(rq1) && !rq_is_sync(rq2))
417 return rq1;
418 else if (rq_is_sync(rq2) && !rq_is_sync(rq1))
419 return rq2;
420 if ((rq1->cmd_flags & REQ_META) && !(rq2->cmd_flags & REQ_META))
421 return rq1;
422 else if ((rq2->cmd_flags & REQ_META) && !(rq1->cmd_flags & REQ_META))
423 return rq2;
424
425 s1 = blk_rq_pos(rq1);
426 s2 = blk_rq_pos(rq2);
427
428 /*
429 * By definition, 1KiB is 2 sectors.
430 */
431 back_max = bfqd->bfq_back_max * 2;
432
433 /*
434 * Strict one way elevator _except_ in the case where we allow
435 * short backward seeks which are biased as twice the cost of a
436 * similar forward seek.
437 */
438 if (s1 >= last)
439 d1 = s1 - last;
440 else if (s1 + back_max >= last)
441 d1 = (last - s1) * bfqd->bfq_back_penalty;
442 else
443 wrap |= BFQ_RQ1_WRAP;
444
445 if (s2 >= last)
446 d2 = s2 - last;
447 else if (s2 + back_max >= last)
448 d2 = (last - s2) * bfqd->bfq_back_penalty;
449 else
450 wrap |= BFQ_RQ2_WRAP;
451
452 /* Found required data */
453
454 /*
455 * By doing switch() on the bit mask "wrap" we avoid having to
456 * check two variables for all permutations: --> faster!
457 */
458 switch (wrap) {
459 case 0: /* common case for CFQ: rq1 and rq2 not wrapped */
460 if (d1 < d2)
461 return rq1;
462 else if (d2 < d1)
463 return rq2;
464
465 if (s1 >= s2)
466 return rq1;
467 else
468 return rq2;
469
470 case BFQ_RQ2_WRAP:
471 return rq1;
472 case BFQ_RQ1_WRAP:
473 return rq2;
474 case BFQ_RQ1_WRAP|BFQ_RQ2_WRAP: /* both rqs wrapped */
475 default:
476 /*
477 * Since both rqs are wrapped,
478 * start with the one that's further behind head
479 * (--> only *one* back seek required),
480 * since back seek takes more time than forward.
481 */
482 if (s1 <= s2)
483 return rq1;
484 else
485 return rq2;
486 }
487}
488
Paolo Valentea52a69e2018-01-13 12:05:17 +0100489/*
Paolo Valentea52a69e2018-01-13 12:05:17 +0100490 * Async I/O can easily starve sync I/O (both sync reads and sync
491 * writes), by consuming all tags. Similarly, storms of sync writes,
492 * such as those that sync(2) may trigger, can starve sync reads.
493 * Limit depths of async I/O and sync writes so as to counter both
494 * problems.
495 */
496static void bfq_limit_depth(unsigned int op, struct blk_mq_alloc_data *data)
497{
Paolo Valentea52a69e2018-01-13 12:05:17 +0100498 struct bfq_data *bfqd = data->q->elevator->elevator_data;
Paolo Valentea52a69e2018-01-13 12:05:17 +0100499
500 if (op_is_sync(op) && !op_is_write(op))
501 return;
502
Paolo Valentea52a69e2018-01-13 12:05:17 +0100503 data->shallow_depth =
504 bfqd->word_depths[!!bfqd->wr_busy_queues][op_is_sync(op)];
505
506 bfq_log(bfqd, "[%s] wr_busy %d sync %d depth %u",
507 __func__, bfqd->wr_busy_queues, op_is_sync(op),
508 data->shallow_depth);
509}
510
Arianna Avanzini36eca892017-04-12 18:23:16 +0200511static struct bfq_queue *
512bfq_rq_pos_tree_lookup(struct bfq_data *bfqd, struct rb_root *root,
513 sector_t sector, struct rb_node **ret_parent,
514 struct rb_node ***rb_link)
515{
516 struct rb_node **p, *parent;
517 struct bfq_queue *bfqq = NULL;
518
519 parent = NULL;
520 p = &root->rb_node;
521 while (*p) {
522 struct rb_node **n;
523
524 parent = *p;
525 bfqq = rb_entry(parent, struct bfq_queue, pos_node);
526
527 /*
528 * Sort strictly based on sector. Smallest to the left,
529 * largest to the right.
530 */
531 if (sector > blk_rq_pos(bfqq->next_rq))
532 n = &(*p)->rb_right;
533 else if (sector < blk_rq_pos(bfqq->next_rq))
534 n = &(*p)->rb_left;
535 else
536 break;
537 p = n;
538 bfqq = NULL;
539 }
540
541 *ret_parent = parent;
542 if (rb_link)
543 *rb_link = p;
544
545 bfq_log(bfqd, "rq_pos_tree_lookup %llu: returning %d",
546 (unsigned long long)sector,
547 bfqq ? bfqq->pid : 0);
548
549 return bfqq;
550}
551
Paolo Valente7b8fa3b2017-12-20 12:38:33 +0100552static bool bfq_too_late_for_merging(struct bfq_queue *bfqq)
553{
554 return bfqq->service_from_backlogged > 0 &&
555 time_is_before_jiffies(bfqq->first_IO_time +
556 bfq_merge_time_limit);
557}
558
Paolo Valenteea25da42017-04-19 08:48:24 -0600559void bfq_pos_tree_add_move(struct bfq_data *bfqd, struct bfq_queue *bfqq)
Arianna Avanzini36eca892017-04-12 18:23:16 +0200560{
561 struct rb_node **p, *parent;
562 struct bfq_queue *__bfqq;
563
564 if (bfqq->pos_root) {
565 rb_erase(&bfqq->pos_node, bfqq->pos_root);
566 bfqq->pos_root = NULL;
567 }
568
Paolo Valente7b8fa3b2017-12-20 12:38:33 +0100569 /*
570 * bfqq cannot be merged any longer (see comments in
571 * bfq_setup_cooperator): no point in adding bfqq into the
572 * position tree.
573 */
574 if (bfq_too_late_for_merging(bfqq))
575 return;
576
Arianna Avanzini36eca892017-04-12 18:23:16 +0200577 if (bfq_class_idle(bfqq))
578 return;
579 if (!bfqq->next_rq)
580 return;
581
582 bfqq->pos_root = &bfq_bfqq_to_bfqg(bfqq)->rq_pos_tree;
583 __bfqq = bfq_rq_pos_tree_lookup(bfqd, bfqq->pos_root,
584 blk_rq_pos(bfqq->next_rq), &parent, &p);
585 if (!__bfqq) {
586 rb_link_node(&bfqq->pos_node, parent, p);
587 rb_insert_color(&bfqq->pos_node, bfqq->pos_root);
588 } else
589 bfqq->pos_root = NULL;
590}
591
Paolo Valenteaee69d72017-04-19 08:29:02 -0600592/*
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200593 * Tell whether there are active queues or groups with differentiated weights.
594 */
595static bool bfq_differentiated_weights(struct bfq_data *bfqd)
596{
597 /*
598 * For weights to differ, at least one of the trees must contain
599 * at least two nodes.
600 */
601 return (!RB_EMPTY_ROOT(&bfqd->queue_weights_tree) &&
602 (bfqd->queue_weights_tree.rb_node->rb_left ||
603 bfqd->queue_weights_tree.rb_node->rb_right)
604#ifdef CONFIG_BFQ_GROUP_IOSCHED
605 ) ||
606 (!RB_EMPTY_ROOT(&bfqd->group_weights_tree) &&
607 (bfqd->group_weights_tree.rb_node->rb_left ||
608 bfqd->group_weights_tree.rb_node->rb_right)
609#endif
610 );
611}
612
613/*
614 * The following function returns true if every queue must receive the
615 * same share of the throughput (this condition is used when deciding
616 * whether idling may be disabled, see the comments in the function
617 * bfq_bfqq_may_idle()).
618 *
619 * Such a scenario occurs when:
620 * 1) all active queues have the same weight,
621 * 2) all active groups at the same level in the groups tree have the same
622 * weight,
623 * 3) all active groups at the same level in the groups tree have the same
624 * number of children.
625 *
626 * Unfortunately, keeping the necessary state for evaluating exactly the
627 * above symmetry conditions would be quite complex and time-consuming.
628 * Therefore this function evaluates, instead, the following stronger
629 * sub-conditions, for which it is much easier to maintain the needed
630 * state:
631 * 1) all active queues have the same weight,
632 * 2) all active groups have the same weight,
633 * 3) all active groups have at most one active child each.
634 * In particular, the last two conditions are always true if hierarchical
635 * support and the cgroups interface are not enabled, thus no state needs
636 * to be maintained in this case.
637 */
638static bool bfq_symmetric_scenario(struct bfq_data *bfqd)
639{
640 return !bfq_differentiated_weights(bfqd);
641}
642
643/*
644 * If the weight-counter tree passed as input contains no counter for
645 * the weight of the input entity, then add that counter; otherwise just
646 * increment the existing counter.
647 *
648 * Note that weight-counter trees contain few nodes in mostly symmetric
649 * scenarios. For example, if all queues have the same weight, then the
650 * weight-counter tree for the queues may contain at most one node.
651 * This holds even if low_latency is on, because weight-raised queues
652 * are not inserted in the tree.
653 * In most scenarios, the rate at which nodes are created/destroyed
654 * should be low too.
655 */
Paolo Valenteea25da42017-04-19 08:48:24 -0600656void bfq_weights_tree_add(struct bfq_data *bfqd, struct bfq_entity *entity,
657 struct rb_root *root)
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200658{
659 struct rb_node **new = &(root->rb_node), *parent = NULL;
660
661 /*
662 * Do not insert if the entity is already associated with a
663 * counter, which happens if:
664 * 1) the entity is associated with a queue,
665 * 2) a request arrival has caused the queue to become both
666 * non-weight-raised, and hence change its weight, and
667 * backlogged; in this respect, each of the two events
668 * causes an invocation of this function,
669 * 3) this is the invocation of this function caused by the
670 * second event. This second invocation is actually useless,
671 * and we handle this fact by exiting immediately. More
672 * efficient or clearer solutions might possibly be adopted.
673 */
674 if (entity->weight_counter)
675 return;
676
677 while (*new) {
678 struct bfq_weight_counter *__counter = container_of(*new,
679 struct bfq_weight_counter,
680 weights_node);
681 parent = *new;
682
683 if (entity->weight == __counter->weight) {
684 entity->weight_counter = __counter;
685 goto inc_counter;
686 }
687 if (entity->weight < __counter->weight)
688 new = &((*new)->rb_left);
689 else
690 new = &((*new)->rb_right);
691 }
692
693 entity->weight_counter = kzalloc(sizeof(struct bfq_weight_counter),
694 GFP_ATOMIC);
695
696 /*
697 * In the unlucky event of an allocation failure, we just
698 * exit. This will cause the weight of entity to not be
699 * considered in bfq_differentiated_weights, which, in its
700 * turn, causes the scenario to be deemed wrongly symmetric in
701 * case entity's weight would have been the only weight making
702 * the scenario asymmetric. On the bright side, no unbalance
703 * will however occur when entity becomes inactive again (the
704 * invocation of this function is triggered by an activation
705 * of entity). In fact, bfq_weights_tree_remove does nothing
706 * if !entity->weight_counter.
707 */
708 if (unlikely(!entity->weight_counter))
709 return;
710
711 entity->weight_counter->weight = entity->weight;
712 rb_link_node(&entity->weight_counter->weights_node, parent, new);
713 rb_insert_color(&entity->weight_counter->weights_node, root);
714
715inc_counter:
716 entity->weight_counter->num_active++;
717}
718
719/*
720 * Decrement the weight counter associated with the entity, and, if the
721 * counter reaches 0, remove the counter from the tree.
722 * See the comments to the function bfq_weights_tree_add() for considerations
723 * about overhead.
724 */
Paolo Valenteea25da42017-04-19 08:48:24 -0600725void bfq_weights_tree_remove(struct bfq_data *bfqd, struct bfq_entity *entity,
726 struct rb_root *root)
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200727{
728 if (!entity->weight_counter)
729 return;
730
731 entity->weight_counter->num_active--;
732 if (entity->weight_counter->num_active > 0)
733 goto reset_entity_pointer;
734
735 rb_erase(&entity->weight_counter->weights_node, root);
736 kfree(entity->weight_counter);
737
738reset_entity_pointer:
739 entity->weight_counter = NULL;
740}
741
742/*
Paolo Valenteaee69d72017-04-19 08:29:02 -0600743 * Return expired entry, or NULL to just start from scratch in rbtree.
744 */
745static struct request *bfq_check_fifo(struct bfq_queue *bfqq,
746 struct request *last)
747{
748 struct request *rq;
749
750 if (bfq_bfqq_fifo_expire(bfqq))
751 return NULL;
752
753 bfq_mark_bfqq_fifo_expire(bfqq);
754
755 rq = rq_entry_fifo(bfqq->fifo.next);
756
757 if (rq == last || ktime_get_ns() < rq->fifo_time)
758 return NULL;
759
760 bfq_log_bfqq(bfqq->bfqd, bfqq, "check_fifo: returned %p", rq);
761 return rq;
762}
763
764static struct request *bfq_find_next_rq(struct bfq_data *bfqd,
765 struct bfq_queue *bfqq,
766 struct request *last)
767{
768 struct rb_node *rbnext = rb_next(&last->rb_node);
769 struct rb_node *rbprev = rb_prev(&last->rb_node);
770 struct request *next, *prev = NULL;
771
772 /* Follow expired path, else get first next available. */
773 next = bfq_check_fifo(bfqq, last);
774 if (next)
775 return next;
776
777 if (rbprev)
778 prev = rb_entry_rq(rbprev);
779
780 if (rbnext)
781 next = rb_entry_rq(rbnext);
782 else {
783 rbnext = rb_first(&bfqq->sort_list);
784 if (rbnext && rbnext != &last->rb_node)
785 next = rb_entry_rq(rbnext);
786 }
787
788 return bfq_choose_req(bfqd, next, prev, blk_rq_pos(last));
789}
790
Paolo Valentec074170e2017-04-12 18:23:11 +0200791/* see the definition of bfq_async_charge_factor for details */
Paolo Valenteaee69d72017-04-19 08:29:02 -0600792static unsigned long bfq_serv_to_charge(struct request *rq,
793 struct bfq_queue *bfqq)
794{
Paolo Valente44e44a12017-04-12 18:23:12 +0200795 if (bfq_bfqq_sync(bfqq) || bfqq->wr_coeff > 1)
Paolo Valentec074170e2017-04-12 18:23:11 +0200796 return blk_rq_sectors(rq);
797
Paolo Valentecfd69712017-04-12 18:23:15 +0200798 /*
799 * If there are no weight-raised queues, then amplify service
800 * by just the async charge factor; otherwise amplify service
801 * by twice the async charge factor, to further reduce latency
802 * for weight-raised queues.
803 */
804 if (bfqq->bfqd->wr_busy_queues == 0)
805 return blk_rq_sectors(rq) * bfq_async_charge_factor;
806
807 return blk_rq_sectors(rq) * 2 * bfq_async_charge_factor;
Paolo Valenteaee69d72017-04-19 08:29:02 -0600808}
809
810/**
811 * bfq_updated_next_req - update the queue after a new next_rq selection.
812 * @bfqd: the device data the queue belongs to.
813 * @bfqq: the queue to update.
814 *
815 * If the first request of a queue changes we make sure that the queue
816 * has enough budget to serve at least its first request (if the
817 * request has grown). We do this because if the queue has not enough
818 * budget for its first request, it has to go through two dispatch
819 * rounds to actually get it dispatched.
820 */
821static void bfq_updated_next_req(struct bfq_data *bfqd,
822 struct bfq_queue *bfqq)
823{
824 struct bfq_entity *entity = &bfqq->entity;
825 struct request *next_rq = bfqq->next_rq;
826 unsigned long new_budget;
827
828 if (!next_rq)
829 return;
830
831 if (bfqq == bfqd->in_service_queue)
832 /*
833 * In order not to break guarantees, budgets cannot be
834 * changed after an entity has been selected.
835 */
836 return;
837
838 new_budget = max_t(unsigned long, bfqq->max_budget,
839 bfq_serv_to_charge(next_rq, bfqq));
840 if (entity->budget != new_budget) {
841 entity->budget = new_budget;
842 bfq_log_bfqq(bfqd, bfqq, "updated next rq: new budget %lu",
843 new_budget);
Paolo Valente80294c32017-08-31 08:46:29 +0200844 bfq_requeue_bfqq(bfqd, bfqq, false);
Paolo Valenteaee69d72017-04-19 08:29:02 -0600845 }
846}
847
Paolo Valente3e2bdd62017-09-21 11:04:01 +0200848static unsigned int bfq_wr_duration(struct bfq_data *bfqd)
849{
850 u64 dur;
851
852 if (bfqd->bfq_wr_max_time > 0)
853 return bfqd->bfq_wr_max_time;
854
855 dur = bfqd->RT_prod;
856 do_div(dur, bfqd->peak_rate);
857
858 /*
859 * Limit duration between 3 and 13 seconds. Tests show that
860 * higher values than 13 seconds often yield the opposite of
861 * the desired result, i.e., worsen responsiveness by letting
862 * non-interactive and non-soft-real-time applications
863 * preserve weight raising for a too long time interval.
864 *
865 * On the other end, lower values than 3 seconds make it
866 * difficult for most interactive tasks to complete their jobs
867 * before weight-raising finishes.
868 */
869 if (dur > msecs_to_jiffies(13000))
870 dur = msecs_to_jiffies(13000);
871 else if (dur < msecs_to_jiffies(3000))
872 dur = msecs_to_jiffies(3000);
873
874 return dur;
875}
876
877/* switch back from soft real-time to interactive weight raising */
878static void switch_back_to_interactive_wr(struct bfq_queue *bfqq,
879 struct bfq_data *bfqd)
880{
881 bfqq->wr_coeff = bfqd->bfq_wr_coeff;
882 bfqq->wr_cur_max_time = bfq_wr_duration(bfqd);
883 bfqq->last_wr_start_finish = bfqq->wr_start_at_switch_to_srt;
884}
885
Arianna Avanzini36eca892017-04-12 18:23:16 +0200886static void
Paolo Valente13c931b2017-06-27 12:30:47 -0600887bfq_bfqq_resume_state(struct bfq_queue *bfqq, struct bfq_data *bfqd,
888 struct bfq_io_cq *bic, bool bfq_already_existing)
Arianna Avanzini36eca892017-04-12 18:23:16 +0200889{
Paolo Valente13c931b2017-06-27 12:30:47 -0600890 unsigned int old_wr_coeff = bfqq->wr_coeff;
891 bool busy = bfq_already_existing && bfq_bfqq_busy(bfqq);
892
Paolo Valented5be3fe2017-08-04 07:35:10 +0200893 if (bic->saved_has_short_ttime)
894 bfq_mark_bfqq_has_short_ttime(bfqq);
Arianna Avanzini36eca892017-04-12 18:23:16 +0200895 else
Paolo Valented5be3fe2017-08-04 07:35:10 +0200896 bfq_clear_bfqq_has_short_ttime(bfqq);
Arianna Avanzini36eca892017-04-12 18:23:16 +0200897
898 if (bic->saved_IO_bound)
899 bfq_mark_bfqq_IO_bound(bfqq);
900 else
901 bfq_clear_bfqq_IO_bound(bfqq);
902
903 bfqq->ttime = bic->saved_ttime;
904 bfqq->wr_coeff = bic->saved_wr_coeff;
905 bfqq->wr_start_at_switch_to_srt = bic->saved_wr_start_at_switch_to_srt;
906 bfqq->last_wr_start_finish = bic->saved_last_wr_start_finish;
907 bfqq->wr_cur_max_time = bic->saved_wr_cur_max_time;
908
Arianna Avanzinie1b23242017-04-12 18:23:20 +0200909 if (bfqq->wr_coeff > 1 && (bfq_bfqq_in_large_burst(bfqq) ||
Arianna Avanzini36eca892017-04-12 18:23:16 +0200910 time_is_before_jiffies(bfqq->last_wr_start_finish +
Arianna Avanzinie1b23242017-04-12 18:23:20 +0200911 bfqq->wr_cur_max_time))) {
Paolo Valente3e2bdd62017-09-21 11:04:01 +0200912 if (bfqq->wr_cur_max_time == bfqd->bfq_wr_rt_max_time &&
913 !bfq_bfqq_in_large_burst(bfqq) &&
914 time_is_after_eq_jiffies(bfqq->wr_start_at_switch_to_srt +
915 bfq_wr_duration(bfqd))) {
916 switch_back_to_interactive_wr(bfqq, bfqd);
917 } else {
918 bfqq->wr_coeff = 1;
919 bfq_log_bfqq(bfqq->bfqd, bfqq,
920 "resume state: switching off wr");
921 }
Arianna Avanzini36eca892017-04-12 18:23:16 +0200922 }
923
924 /* make sure weight will be updated, however we got here */
925 bfqq->entity.prio_changed = 1;
Paolo Valente13c931b2017-06-27 12:30:47 -0600926
927 if (likely(!busy))
928 return;
929
930 if (old_wr_coeff == 1 && bfqq->wr_coeff > 1)
931 bfqd->wr_busy_queues++;
932 else if (old_wr_coeff > 1 && bfqq->wr_coeff == 1)
933 bfqd->wr_busy_queues--;
Arianna Avanzini36eca892017-04-12 18:23:16 +0200934}
935
936static int bfqq_process_refs(struct bfq_queue *bfqq)
937{
938 return bfqq->ref - bfqq->allocated - bfqq->entity.on_st;
939}
940
Arianna Avanzinie1b23242017-04-12 18:23:20 +0200941/* Empty burst list and add just bfqq (see comments on bfq_handle_burst) */
942static void bfq_reset_burst_list(struct bfq_data *bfqd, struct bfq_queue *bfqq)
943{
944 struct bfq_queue *item;
945 struct hlist_node *n;
946
947 hlist_for_each_entry_safe(item, n, &bfqd->burst_list, burst_list_node)
948 hlist_del_init(&item->burst_list_node);
949 hlist_add_head(&bfqq->burst_list_node, &bfqd->burst_list);
950 bfqd->burst_size = 1;
951 bfqd->burst_parent_entity = bfqq->entity.parent;
952}
953
954/* Add bfqq to the list of queues in current burst (see bfq_handle_burst) */
955static void bfq_add_to_burst(struct bfq_data *bfqd, struct bfq_queue *bfqq)
956{
957 /* Increment burst size to take into account also bfqq */
958 bfqd->burst_size++;
959
960 if (bfqd->burst_size == bfqd->bfq_large_burst_thresh) {
961 struct bfq_queue *pos, *bfqq_item;
962 struct hlist_node *n;
963
964 /*
965 * Enough queues have been activated shortly after each
966 * other to consider this burst as large.
967 */
968 bfqd->large_burst = true;
969
970 /*
971 * We can now mark all queues in the burst list as
972 * belonging to a large burst.
973 */
974 hlist_for_each_entry(bfqq_item, &bfqd->burst_list,
975 burst_list_node)
976 bfq_mark_bfqq_in_large_burst(bfqq_item);
977 bfq_mark_bfqq_in_large_burst(bfqq);
978
979 /*
980 * From now on, and until the current burst finishes, any
981 * new queue being activated shortly after the last queue
982 * was inserted in the burst can be immediately marked as
983 * belonging to a large burst. So the burst list is not
984 * needed any more. Remove it.
985 */
986 hlist_for_each_entry_safe(pos, n, &bfqd->burst_list,
987 burst_list_node)
988 hlist_del_init(&pos->burst_list_node);
989 } else /*
990 * Burst not yet large: add bfqq to the burst list. Do
991 * not increment the ref counter for bfqq, because bfqq
992 * is removed from the burst list before freeing bfqq
993 * in put_queue.
994 */
995 hlist_add_head(&bfqq->burst_list_node, &bfqd->burst_list);
996}
997
998/*
999 * If many queues belonging to the same group happen to be created
1000 * shortly after each other, then the processes associated with these
1001 * queues have typically a common goal. In particular, bursts of queue
1002 * creations are usually caused by services or applications that spawn
1003 * many parallel threads/processes. Examples are systemd during boot,
1004 * or git grep. To help these processes get their job done as soon as
1005 * possible, it is usually better to not grant either weight-raising
1006 * or device idling to their queues.
1007 *
1008 * In this comment we describe, firstly, the reasons why this fact
1009 * holds, and, secondly, the next function, which implements the main
1010 * steps needed to properly mark these queues so that they can then be
1011 * treated in a different way.
1012 *
1013 * The above services or applications benefit mostly from a high
1014 * throughput: the quicker the requests of the activated queues are
1015 * cumulatively served, the sooner the target job of these queues gets
1016 * completed. As a consequence, weight-raising any of these queues,
1017 * which also implies idling the device for it, is almost always
1018 * counterproductive. In most cases it just lowers throughput.
1019 *
1020 * On the other hand, a burst of queue creations may be caused also by
1021 * the start of an application that does not consist of a lot of
1022 * parallel I/O-bound threads. In fact, with a complex application,
1023 * several short processes may need to be executed to start-up the
1024 * application. In this respect, to start an application as quickly as
1025 * possible, the best thing to do is in any case to privilege the I/O
1026 * related to the application with respect to all other
1027 * I/O. Therefore, the best strategy to start as quickly as possible
1028 * an application that causes a burst of queue creations is to
1029 * weight-raise all the queues created during the burst. This is the
1030 * exact opposite of the best strategy for the other type of bursts.
1031 *
1032 * In the end, to take the best action for each of the two cases, the
1033 * two types of bursts need to be distinguished. Fortunately, this
1034 * seems relatively easy, by looking at the sizes of the bursts. In
1035 * particular, we found a threshold such that only bursts with a
1036 * larger size than that threshold are apparently caused by
1037 * services or commands such as systemd or git grep. For brevity,
1038 * hereafter we call just 'large' these bursts. BFQ *does not*
1039 * weight-raise queues whose creation occurs in a large burst. In
1040 * addition, for each of these queues BFQ performs or does not perform
1041 * idling depending on which choice boosts the throughput more. The
1042 * exact choice depends on the device and request pattern at
1043 * hand.
1044 *
1045 * Unfortunately, false positives may occur while an interactive task
1046 * is starting (e.g., an application is being started). The
1047 * consequence is that the queues associated with the task do not
1048 * enjoy weight raising as expected. Fortunately these false positives
1049 * are very rare. They typically occur if some service happens to
1050 * start doing I/O exactly when the interactive task starts.
1051 *
1052 * Turning back to the next function, it implements all the steps
1053 * needed to detect the occurrence of a large burst and to properly
1054 * mark all the queues belonging to it (so that they can then be
1055 * treated in a different way). This goal is achieved by maintaining a
1056 * "burst list" that holds, temporarily, the queues that belong to the
1057 * burst in progress. The list is then used to mark these queues as
1058 * belonging to a large burst if the burst does become large. The main
1059 * steps are the following.
1060 *
1061 * . when the very first queue is created, the queue is inserted into the
1062 * list (as it could be the first queue in a possible burst)
1063 *
1064 * . if the current burst has not yet become large, and a queue Q that does
1065 * not yet belong to the burst is activated shortly after the last time
1066 * at which a new queue entered the burst list, then the function appends
1067 * Q to the burst list
1068 *
1069 * . if, as a consequence of the previous step, the burst size reaches
1070 * the large-burst threshold, then
1071 *
1072 * . all the queues in the burst list are marked as belonging to a
1073 * large burst
1074 *
1075 * . the burst list is deleted; in fact, the burst list already served
1076 * its purpose (keeping temporarily track of the queues in a burst,
1077 * so as to be able to mark them as belonging to a large burst in the
1078 * previous sub-step), and now is not needed any more
1079 *
1080 * . the device enters a large-burst mode
1081 *
1082 * . if a queue Q that does not belong to the burst is created while
1083 * the device is in large-burst mode and shortly after the last time
1084 * at which a queue either entered the burst list or was marked as
1085 * belonging to the current large burst, then Q is immediately marked
1086 * as belonging to a large burst.
1087 *
1088 * . if a queue Q that does not belong to the burst is created a while
1089 * later, i.e., not shortly after, than the last time at which a queue
1090 * either entered the burst list or was marked as belonging to the
1091 * current large burst, then the current burst is deemed as finished and:
1092 *
1093 * . the large-burst mode is reset if set
1094 *
1095 * . the burst list is emptied
1096 *
1097 * . Q is inserted in the burst list, as Q may be the first queue
1098 * in a possible new burst (then the burst list contains just Q
1099 * after this step).
1100 */
1101static void bfq_handle_burst(struct bfq_data *bfqd, struct bfq_queue *bfqq)
1102{
1103 /*
1104 * If bfqq is already in the burst list or is part of a large
1105 * burst, or finally has just been split, then there is
1106 * nothing else to do.
1107 */
1108 if (!hlist_unhashed(&bfqq->burst_list_node) ||
1109 bfq_bfqq_in_large_burst(bfqq) ||
1110 time_is_after_eq_jiffies(bfqq->split_time +
1111 msecs_to_jiffies(10)))
1112 return;
1113
1114 /*
1115 * If bfqq's creation happens late enough, or bfqq belongs to
1116 * a different group than the burst group, then the current
1117 * burst is finished, and related data structures must be
1118 * reset.
1119 *
1120 * In this respect, consider the special case where bfqq is
1121 * the very first queue created after BFQ is selected for this
1122 * device. In this case, last_ins_in_burst and
1123 * burst_parent_entity are not yet significant when we get
1124 * here. But it is easy to verify that, whether or not the
1125 * following condition is true, bfqq will end up being
1126 * inserted into the burst list. In particular the list will
1127 * happen to contain only bfqq. And this is exactly what has
1128 * to happen, as bfqq may be the first queue of the first
1129 * burst.
1130 */
1131 if (time_is_before_jiffies(bfqd->last_ins_in_burst +
1132 bfqd->bfq_burst_interval) ||
1133 bfqq->entity.parent != bfqd->burst_parent_entity) {
1134 bfqd->large_burst = false;
1135 bfq_reset_burst_list(bfqd, bfqq);
1136 goto end;
1137 }
1138
1139 /*
1140 * If we get here, then bfqq is being activated shortly after the
1141 * last queue. So, if the current burst is also large, we can mark
1142 * bfqq as belonging to this large burst immediately.
1143 */
1144 if (bfqd->large_burst) {
1145 bfq_mark_bfqq_in_large_burst(bfqq);
1146 goto end;
1147 }
1148
1149 /*
1150 * If we get here, then a large-burst state has not yet been
1151 * reached, but bfqq is being activated shortly after the last
1152 * queue. Then we add bfqq to the burst.
1153 */
1154 bfq_add_to_burst(bfqd, bfqq);
1155end:
1156 /*
1157 * At this point, bfqq either has been added to the current
1158 * burst or has caused the current burst to terminate and a
1159 * possible new burst to start. In particular, in the second
1160 * case, bfqq has become the first queue in the possible new
1161 * burst. In both cases last_ins_in_burst needs to be moved
1162 * forward.
1163 */
1164 bfqd->last_ins_in_burst = jiffies;
1165}
1166
Paolo Valenteaee69d72017-04-19 08:29:02 -06001167static int bfq_bfqq_budget_left(struct bfq_queue *bfqq)
1168{
1169 struct bfq_entity *entity = &bfqq->entity;
1170
1171 return entity->budget - entity->service;
1172}
1173
1174/*
1175 * If enough samples have been computed, return the current max budget
1176 * stored in bfqd, which is dynamically updated according to the
1177 * estimated disk peak rate; otherwise return the default max budget
1178 */
1179static int bfq_max_budget(struct bfq_data *bfqd)
1180{
1181 if (bfqd->budgets_assigned < bfq_stats_min_budgets)
1182 return bfq_default_max_budget;
1183 else
1184 return bfqd->bfq_max_budget;
1185}
1186
1187/*
1188 * Return min budget, which is a fraction of the current or default
1189 * max budget (trying with 1/32)
1190 */
1191static int bfq_min_budget(struct bfq_data *bfqd)
1192{
1193 if (bfqd->budgets_assigned < bfq_stats_min_budgets)
1194 return bfq_default_max_budget / 32;
1195 else
1196 return bfqd->bfq_max_budget / 32;
1197}
1198
Paolo Valenteaee69d72017-04-19 08:29:02 -06001199/*
1200 * The next function, invoked after the input queue bfqq switches from
1201 * idle to busy, updates the budget of bfqq. The function also tells
1202 * whether the in-service queue should be expired, by returning
1203 * true. The purpose of expiring the in-service queue is to give bfqq
1204 * the chance to possibly preempt the in-service queue, and the reason
Paolo Valente44e44a12017-04-12 18:23:12 +02001205 * for preempting the in-service queue is to achieve one of the two
1206 * goals below.
Paolo Valenteaee69d72017-04-19 08:29:02 -06001207 *
Paolo Valente44e44a12017-04-12 18:23:12 +02001208 * 1. Guarantee to bfqq its reserved bandwidth even if bfqq has
1209 * expired because it has remained idle. In particular, bfqq may have
1210 * expired for one of the following two reasons:
Paolo Valenteaee69d72017-04-19 08:29:02 -06001211 *
1212 * - BFQQE_NO_MORE_REQUESTS bfqq did not enjoy any device idling
1213 * and did not make it to issue a new request before its last
1214 * request was served;
1215 *
1216 * - BFQQE_TOO_IDLE bfqq did enjoy device idling, but did not issue
1217 * a new request before the expiration of the idling-time.
1218 *
1219 * Even if bfqq has expired for one of the above reasons, the process
1220 * associated with the queue may be however issuing requests greedily,
1221 * and thus be sensitive to the bandwidth it receives (bfqq may have
1222 * remained idle for other reasons: CPU high load, bfqq not enjoying
1223 * idling, I/O throttling somewhere in the path from the process to
1224 * the I/O scheduler, ...). But if, after every expiration for one of
1225 * the above two reasons, bfqq has to wait for the service of at least
1226 * one full budget of another queue before being served again, then
1227 * bfqq is likely to get a much lower bandwidth or resource time than
1228 * its reserved ones. To address this issue, two countermeasures need
1229 * to be taken.
1230 *
1231 * First, the budget and the timestamps of bfqq need to be updated in
1232 * a special way on bfqq reactivation: they need to be updated as if
1233 * bfqq did not remain idle and did not expire. In fact, if they are
1234 * computed as if bfqq expired and remained idle until reactivation,
1235 * then the process associated with bfqq is treated as if, instead of
1236 * being greedy, it stopped issuing requests when bfqq remained idle,
1237 * and restarts issuing requests only on this reactivation. In other
1238 * words, the scheduler does not help the process recover the "service
1239 * hole" between bfqq expiration and reactivation. As a consequence,
1240 * the process receives a lower bandwidth than its reserved one. In
1241 * contrast, to recover this hole, the budget must be updated as if
1242 * bfqq was not expired at all before this reactivation, i.e., it must
1243 * be set to the value of the remaining budget when bfqq was
1244 * expired. Along the same line, timestamps need to be assigned the
1245 * value they had the last time bfqq was selected for service, i.e.,
1246 * before last expiration. Thus timestamps need to be back-shifted
1247 * with respect to their normal computation (see [1] for more details
1248 * on this tricky aspect).
1249 *
1250 * Secondly, to allow the process to recover the hole, the in-service
1251 * queue must be expired too, to give bfqq the chance to preempt it
1252 * immediately. In fact, if bfqq has to wait for a full budget of the
1253 * in-service queue to be completed, then it may become impossible to
1254 * let the process recover the hole, even if the back-shifted
1255 * timestamps of bfqq are lower than those of the in-service queue. If
1256 * this happens for most or all of the holes, then the process may not
1257 * receive its reserved bandwidth. In this respect, it is worth noting
1258 * that, being the service of outstanding requests unpreemptible, a
1259 * little fraction of the holes may however be unrecoverable, thereby
1260 * causing a little loss of bandwidth.
1261 *
1262 * The last important point is detecting whether bfqq does need this
1263 * bandwidth recovery. In this respect, the next function deems the
1264 * process associated with bfqq greedy, and thus allows it to recover
1265 * the hole, if: 1) the process is waiting for the arrival of a new
1266 * request (which implies that bfqq expired for one of the above two
1267 * reasons), and 2) such a request has arrived soon. The first
1268 * condition is controlled through the flag non_blocking_wait_rq,
1269 * while the second through the flag arrived_in_time. If both
1270 * conditions hold, then the function computes the budget in the
1271 * above-described special way, and signals that the in-service queue
1272 * should be expired. Timestamp back-shifting is done later in
1273 * __bfq_activate_entity.
Paolo Valente44e44a12017-04-12 18:23:12 +02001274 *
1275 * 2. Reduce latency. Even if timestamps are not backshifted to let
1276 * the process associated with bfqq recover a service hole, bfqq may
1277 * however happen to have, after being (re)activated, a lower finish
1278 * timestamp than the in-service queue. That is, the next budget of
1279 * bfqq may have to be completed before the one of the in-service
1280 * queue. If this is the case, then preempting the in-service queue
1281 * allows this goal to be achieved, apart from the unpreemptible,
1282 * outstanding requests mentioned above.
1283 *
1284 * Unfortunately, regardless of which of the above two goals one wants
1285 * to achieve, service trees need first to be updated to know whether
1286 * the in-service queue must be preempted. To have service trees
1287 * correctly updated, the in-service queue must be expired and
1288 * rescheduled, and bfqq must be scheduled too. This is one of the
1289 * most costly operations (in future versions, the scheduling
1290 * mechanism may be re-designed in such a way to make it possible to
1291 * know whether preemption is needed without needing to update service
1292 * trees). In addition, queue preemptions almost always cause random
1293 * I/O, and thus loss of throughput. Because of these facts, the next
1294 * function adopts the following simple scheme to avoid both costly
1295 * operations and too frequent preemptions: it requests the expiration
1296 * of the in-service queue (unconditionally) only for queues that need
1297 * to recover a hole, or that either are weight-raised or deserve to
1298 * be weight-raised.
Paolo Valenteaee69d72017-04-19 08:29:02 -06001299 */
1300static bool bfq_bfqq_update_budg_for_activation(struct bfq_data *bfqd,
1301 struct bfq_queue *bfqq,
Paolo Valente44e44a12017-04-12 18:23:12 +02001302 bool arrived_in_time,
1303 bool wr_or_deserves_wr)
Paolo Valenteaee69d72017-04-19 08:29:02 -06001304{
1305 struct bfq_entity *entity = &bfqq->entity;
1306
1307 if (bfq_bfqq_non_blocking_wait_rq(bfqq) && arrived_in_time) {
1308 /*
1309 * We do not clear the flag non_blocking_wait_rq here, as
1310 * the latter is used in bfq_activate_bfqq to signal
1311 * that timestamps need to be back-shifted (and is
1312 * cleared right after).
1313 */
1314
1315 /*
1316 * In next assignment we rely on that either
1317 * entity->service or entity->budget are not updated
1318 * on expiration if bfqq is empty (see
1319 * __bfq_bfqq_recalc_budget). Thus both quantities
1320 * remain unchanged after such an expiration, and the
1321 * following statement therefore assigns to
1322 * entity->budget the remaining budget on such an
1323 * expiration. For clarity, entity->service is not
1324 * updated on expiration in any case, and, in normal
1325 * operation, is reset only when bfqq is selected for
1326 * service (see bfq_get_next_queue).
1327 */
1328 entity->budget = min_t(unsigned long,
1329 bfq_bfqq_budget_left(bfqq),
1330 bfqq->max_budget);
1331
1332 return true;
1333 }
1334
1335 entity->budget = max_t(unsigned long, bfqq->max_budget,
1336 bfq_serv_to_charge(bfqq->next_rq, bfqq));
1337 bfq_clear_bfqq_non_blocking_wait_rq(bfqq);
Paolo Valente44e44a12017-04-12 18:23:12 +02001338 return wr_or_deserves_wr;
1339}
1340
Paolo Valente4baa8bb2017-09-21 11:04:00 +02001341/*
1342 * Return the farthest future time instant according to jiffies
1343 * macros.
1344 */
1345static unsigned long bfq_greatest_from_now(void)
1346{
1347 return jiffies + MAX_JIFFY_OFFSET;
1348}
1349
1350/*
1351 * Return the farthest past time instant according to jiffies
1352 * macros.
1353 */
1354static unsigned long bfq_smallest_from_now(void)
1355{
1356 return jiffies - MAX_JIFFY_OFFSET;
1357}
1358
Paolo Valente44e44a12017-04-12 18:23:12 +02001359static void bfq_update_bfqq_wr_on_rq_arrival(struct bfq_data *bfqd,
1360 struct bfq_queue *bfqq,
1361 unsigned int old_wr_coeff,
1362 bool wr_or_deserves_wr,
Paolo Valente77b7dce2017-04-12 18:23:13 +02001363 bool interactive,
Arianna Avanzinie1b23242017-04-12 18:23:20 +02001364 bool in_burst,
Paolo Valente77b7dce2017-04-12 18:23:13 +02001365 bool soft_rt)
Paolo Valente44e44a12017-04-12 18:23:12 +02001366{
1367 if (old_wr_coeff == 1 && wr_or_deserves_wr) {
1368 /* start a weight-raising period */
Paolo Valente77b7dce2017-04-12 18:23:13 +02001369 if (interactive) {
Paolo Valente8a8747d2018-01-13 12:05:18 +01001370 bfqq->service_from_wr = 0;
Paolo Valente77b7dce2017-04-12 18:23:13 +02001371 bfqq->wr_coeff = bfqd->bfq_wr_coeff;
1372 bfqq->wr_cur_max_time = bfq_wr_duration(bfqd);
1373 } else {
Paolo Valente4baa8bb2017-09-21 11:04:00 +02001374 /*
1375 * No interactive weight raising in progress
1376 * here: assign minus infinity to
1377 * wr_start_at_switch_to_srt, to make sure
1378 * that, at the end of the soft-real-time
1379 * weight raising periods that is starting
1380 * now, no interactive weight-raising period
1381 * may be wrongly considered as still in
1382 * progress (and thus actually started by
1383 * mistake).
1384 */
1385 bfqq->wr_start_at_switch_to_srt =
1386 bfq_smallest_from_now();
Paolo Valente77b7dce2017-04-12 18:23:13 +02001387 bfqq->wr_coeff = bfqd->bfq_wr_coeff *
1388 BFQ_SOFTRT_WEIGHT_FACTOR;
1389 bfqq->wr_cur_max_time =
1390 bfqd->bfq_wr_rt_max_time;
1391 }
Paolo Valente44e44a12017-04-12 18:23:12 +02001392
1393 /*
1394 * If needed, further reduce budget to make sure it is
1395 * close to bfqq's backlog, so as to reduce the
1396 * scheduling-error component due to a too large
1397 * budget. Do not care about throughput consequences,
1398 * but only about latency. Finally, do not assign a
1399 * too small budget either, to avoid increasing
1400 * latency by causing too frequent expirations.
1401 */
1402 bfqq->entity.budget = min_t(unsigned long,
1403 bfqq->entity.budget,
1404 2 * bfq_min_budget(bfqd));
1405 } else if (old_wr_coeff > 1) {
Paolo Valente77b7dce2017-04-12 18:23:13 +02001406 if (interactive) { /* update wr coeff and duration */
1407 bfqq->wr_coeff = bfqd->bfq_wr_coeff;
1408 bfqq->wr_cur_max_time = bfq_wr_duration(bfqd);
Arianna Avanzinie1b23242017-04-12 18:23:20 +02001409 } else if (in_burst)
1410 bfqq->wr_coeff = 1;
1411 else if (soft_rt) {
Paolo Valente77b7dce2017-04-12 18:23:13 +02001412 /*
1413 * The application is now or still meeting the
1414 * requirements for being deemed soft rt. We
1415 * can then correctly and safely (re)charge
1416 * the weight-raising duration for the
1417 * application with the weight-raising
1418 * duration for soft rt applications.
1419 *
1420 * In particular, doing this recharge now, i.e.,
1421 * before the weight-raising period for the
1422 * application finishes, reduces the probability
1423 * of the following negative scenario:
1424 * 1) the weight of a soft rt application is
1425 * raised at startup (as for any newly
1426 * created application),
1427 * 2) since the application is not interactive,
1428 * at a certain time weight-raising is
1429 * stopped for the application,
1430 * 3) at that time the application happens to
1431 * still have pending requests, and hence
1432 * is destined to not have a chance to be
1433 * deemed soft rt before these requests are
1434 * completed (see the comments to the
1435 * function bfq_bfqq_softrt_next_start()
1436 * for details on soft rt detection),
1437 * 4) these pending requests experience a high
1438 * latency because the application is not
1439 * weight-raised while they are pending.
1440 */
1441 if (bfqq->wr_cur_max_time !=
1442 bfqd->bfq_wr_rt_max_time) {
1443 bfqq->wr_start_at_switch_to_srt =
1444 bfqq->last_wr_start_finish;
1445
1446 bfqq->wr_cur_max_time =
1447 bfqd->bfq_wr_rt_max_time;
1448 bfqq->wr_coeff = bfqd->bfq_wr_coeff *
1449 BFQ_SOFTRT_WEIGHT_FACTOR;
1450 }
1451 bfqq->last_wr_start_finish = jiffies;
1452 }
Paolo Valente44e44a12017-04-12 18:23:12 +02001453 }
1454}
1455
1456static bool bfq_bfqq_idle_for_long_time(struct bfq_data *bfqd,
1457 struct bfq_queue *bfqq)
1458{
1459 return bfqq->dispatched == 0 &&
1460 time_is_before_jiffies(
1461 bfqq->budget_timeout +
1462 bfqd->bfq_wr_min_idle_time);
Paolo Valenteaee69d72017-04-19 08:29:02 -06001463}
1464
1465static void bfq_bfqq_handle_idle_busy_switch(struct bfq_data *bfqd,
1466 struct bfq_queue *bfqq,
Paolo Valente44e44a12017-04-12 18:23:12 +02001467 int old_wr_coeff,
1468 struct request *rq,
1469 bool *interactive)
Paolo Valenteaee69d72017-04-19 08:29:02 -06001470{
Arianna Avanzinie1b23242017-04-12 18:23:20 +02001471 bool soft_rt, in_burst, wr_or_deserves_wr,
1472 bfqq_wants_to_preempt,
Paolo Valente44e44a12017-04-12 18:23:12 +02001473 idle_for_long_time = bfq_bfqq_idle_for_long_time(bfqd, bfqq),
Paolo Valenteaee69d72017-04-19 08:29:02 -06001474 /*
1475 * See the comments on
1476 * bfq_bfqq_update_budg_for_activation for
1477 * details on the usage of the next variable.
1478 */
1479 arrived_in_time = ktime_get_ns() <=
1480 bfqq->ttime.last_end_request +
1481 bfqd->bfq_slice_idle * 3;
1482
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02001483
Paolo Valenteaee69d72017-04-19 08:29:02 -06001484 /*
Paolo Valente44e44a12017-04-12 18:23:12 +02001485 * bfqq deserves to be weight-raised if:
1486 * - it is sync,
Arianna Avanzinie1b23242017-04-12 18:23:20 +02001487 * - it does not belong to a large burst,
Arianna Avanzini36eca892017-04-12 18:23:16 +02001488 * - it has been idle for enough time or is soft real-time,
1489 * - is linked to a bfq_io_cq (it is not shared in any sense).
Paolo Valente44e44a12017-04-12 18:23:12 +02001490 */
Arianna Avanzinie1b23242017-04-12 18:23:20 +02001491 in_burst = bfq_bfqq_in_large_burst(bfqq);
Paolo Valente77b7dce2017-04-12 18:23:13 +02001492 soft_rt = bfqd->bfq_wr_max_softrt_rate > 0 &&
Arianna Avanzinie1b23242017-04-12 18:23:20 +02001493 !in_burst &&
Paolo Valente77b7dce2017-04-12 18:23:13 +02001494 time_is_before_jiffies(bfqq->soft_rt_next_start);
Arianna Avanzinie1b23242017-04-12 18:23:20 +02001495 *interactive = !in_burst && idle_for_long_time;
Paolo Valente44e44a12017-04-12 18:23:12 +02001496 wr_or_deserves_wr = bfqd->low_latency &&
1497 (bfqq->wr_coeff > 1 ||
Arianna Avanzini36eca892017-04-12 18:23:16 +02001498 (bfq_bfqq_sync(bfqq) &&
1499 bfqq->bic && (*interactive || soft_rt)));
Paolo Valente44e44a12017-04-12 18:23:12 +02001500
1501 /*
1502 * Using the last flag, update budget and check whether bfqq
1503 * may want to preempt the in-service queue.
Paolo Valenteaee69d72017-04-19 08:29:02 -06001504 */
1505 bfqq_wants_to_preempt =
1506 bfq_bfqq_update_budg_for_activation(bfqd, bfqq,
Paolo Valente44e44a12017-04-12 18:23:12 +02001507 arrived_in_time,
1508 wr_or_deserves_wr);
Paolo Valenteaee69d72017-04-19 08:29:02 -06001509
Arianna Avanzinie1b23242017-04-12 18:23:20 +02001510 /*
1511 * If bfqq happened to be activated in a burst, but has been
1512 * idle for much more than an interactive queue, then we
1513 * assume that, in the overall I/O initiated in the burst, the
1514 * I/O associated with bfqq is finished. So bfqq does not need
1515 * to be treated as a queue belonging to a burst
1516 * anymore. Accordingly, we reset bfqq's in_large_burst flag
1517 * if set, and remove bfqq from the burst list if it's
1518 * there. We do not decrement burst_size, because the fact
1519 * that bfqq does not need to belong to the burst list any
1520 * more does not invalidate the fact that bfqq was created in
1521 * a burst.
1522 */
1523 if (likely(!bfq_bfqq_just_created(bfqq)) &&
1524 idle_for_long_time &&
1525 time_is_before_jiffies(
1526 bfqq->budget_timeout +
1527 msecs_to_jiffies(10000))) {
1528 hlist_del_init(&bfqq->burst_list_node);
1529 bfq_clear_bfqq_in_large_burst(bfqq);
1530 }
1531
1532 bfq_clear_bfqq_just_created(bfqq);
1533
1534
Paolo Valenteaee69d72017-04-19 08:29:02 -06001535 if (!bfq_bfqq_IO_bound(bfqq)) {
1536 if (arrived_in_time) {
1537 bfqq->requests_within_timer++;
1538 if (bfqq->requests_within_timer >=
1539 bfqd->bfq_requests_within_timer)
1540 bfq_mark_bfqq_IO_bound(bfqq);
1541 } else
1542 bfqq->requests_within_timer = 0;
1543 }
1544
Paolo Valente44e44a12017-04-12 18:23:12 +02001545 if (bfqd->low_latency) {
Arianna Avanzini36eca892017-04-12 18:23:16 +02001546 if (unlikely(time_is_after_jiffies(bfqq->split_time)))
1547 /* wraparound */
1548 bfqq->split_time =
1549 jiffies - bfqd->bfq_wr_min_idle_time - 1;
Paolo Valente44e44a12017-04-12 18:23:12 +02001550
Arianna Avanzini36eca892017-04-12 18:23:16 +02001551 if (time_is_before_jiffies(bfqq->split_time +
1552 bfqd->bfq_wr_min_idle_time)) {
1553 bfq_update_bfqq_wr_on_rq_arrival(bfqd, bfqq,
1554 old_wr_coeff,
1555 wr_or_deserves_wr,
1556 *interactive,
Arianna Avanzinie1b23242017-04-12 18:23:20 +02001557 in_burst,
Arianna Avanzini36eca892017-04-12 18:23:16 +02001558 soft_rt);
1559
1560 if (old_wr_coeff != bfqq->wr_coeff)
1561 bfqq->entity.prio_changed = 1;
1562 }
Paolo Valente44e44a12017-04-12 18:23:12 +02001563 }
1564
Paolo Valente77b7dce2017-04-12 18:23:13 +02001565 bfqq->last_idle_bklogged = jiffies;
1566 bfqq->service_from_backlogged = 0;
1567 bfq_clear_bfqq_softrt_update(bfqq);
1568
Paolo Valenteaee69d72017-04-19 08:29:02 -06001569 bfq_add_bfqq_busy(bfqd, bfqq);
1570
1571 /*
1572 * Expire in-service queue only if preemption may be needed
1573 * for guarantees. In this respect, the function
1574 * next_queue_may_preempt just checks a simple, necessary
1575 * condition, and not a sufficient condition based on
1576 * timestamps. In fact, for the latter condition to be
1577 * evaluated, timestamps would need first to be updated, and
1578 * this operation is quite costly (see the comments on the
1579 * function bfq_bfqq_update_budg_for_activation).
1580 */
1581 if (bfqd->in_service_queue && bfqq_wants_to_preempt &&
Paolo Valente77b7dce2017-04-12 18:23:13 +02001582 bfqd->in_service_queue->wr_coeff < bfqq->wr_coeff &&
Paolo Valenteaee69d72017-04-19 08:29:02 -06001583 next_queue_may_preempt(bfqd))
1584 bfq_bfqq_expire(bfqd, bfqd->in_service_queue,
1585 false, BFQQE_PREEMPTED);
1586}
1587
1588static void bfq_add_request(struct request *rq)
1589{
1590 struct bfq_queue *bfqq = RQ_BFQQ(rq);
1591 struct bfq_data *bfqd = bfqq->bfqd;
1592 struct request *next_rq, *prev;
Paolo Valente44e44a12017-04-12 18:23:12 +02001593 unsigned int old_wr_coeff = bfqq->wr_coeff;
1594 bool interactive = false;
Paolo Valenteaee69d72017-04-19 08:29:02 -06001595
1596 bfq_log_bfqq(bfqd, bfqq, "add_request %d", rq_is_sync(rq));
1597 bfqq->queued[rq_is_sync(rq)]++;
1598 bfqd->queued++;
1599
1600 elv_rb_add(&bfqq->sort_list, rq);
1601
1602 /*
1603 * Check if this request is a better next-serve candidate.
1604 */
1605 prev = bfqq->next_rq;
1606 next_rq = bfq_choose_req(bfqd, bfqq->next_rq, rq, bfqd->last_position);
1607 bfqq->next_rq = next_rq;
1608
Arianna Avanzini36eca892017-04-12 18:23:16 +02001609 /*
1610 * Adjust priority tree position, if next_rq changes.
1611 */
1612 if (prev != bfqq->next_rq)
1613 bfq_pos_tree_add_move(bfqd, bfqq);
1614
Paolo Valenteaee69d72017-04-19 08:29:02 -06001615 if (!bfq_bfqq_busy(bfqq)) /* switching to busy ... */
Paolo Valente44e44a12017-04-12 18:23:12 +02001616 bfq_bfqq_handle_idle_busy_switch(bfqd, bfqq, old_wr_coeff,
1617 rq, &interactive);
1618 else {
1619 if (bfqd->low_latency && old_wr_coeff == 1 && !rq_is_sync(rq) &&
1620 time_is_before_jiffies(
1621 bfqq->last_wr_start_finish +
1622 bfqd->bfq_wr_min_inter_arr_async)) {
1623 bfqq->wr_coeff = bfqd->bfq_wr_coeff;
1624 bfqq->wr_cur_max_time = bfq_wr_duration(bfqd);
1625
Paolo Valentecfd69712017-04-12 18:23:15 +02001626 bfqd->wr_busy_queues++;
Paolo Valente44e44a12017-04-12 18:23:12 +02001627 bfqq->entity.prio_changed = 1;
1628 }
1629 if (prev != bfqq->next_rq)
1630 bfq_updated_next_req(bfqd, bfqq);
1631 }
1632
1633 /*
1634 * Assign jiffies to last_wr_start_finish in the following
1635 * cases:
1636 *
1637 * . if bfqq is not going to be weight-raised, because, for
1638 * non weight-raised queues, last_wr_start_finish stores the
1639 * arrival time of the last request; as of now, this piece
1640 * of information is used only for deciding whether to
1641 * weight-raise async queues
1642 *
1643 * . if bfqq is not weight-raised, because, if bfqq is now
1644 * switching to weight-raised, then last_wr_start_finish
1645 * stores the time when weight-raising starts
1646 *
1647 * . if bfqq is interactive, because, regardless of whether
1648 * bfqq is currently weight-raised, the weight-raising
1649 * period must start or restart (this case is considered
1650 * separately because it is not detected by the above
1651 * conditions, if bfqq is already weight-raised)
Paolo Valente77b7dce2017-04-12 18:23:13 +02001652 *
1653 * last_wr_start_finish has to be updated also if bfqq is soft
1654 * real-time, because the weight-raising period is constantly
1655 * restarted on idle-to-busy transitions for these queues, but
1656 * this is already done in bfq_bfqq_handle_idle_busy_switch if
1657 * needed.
Paolo Valente44e44a12017-04-12 18:23:12 +02001658 */
1659 if (bfqd->low_latency &&
1660 (old_wr_coeff == 1 || bfqq->wr_coeff == 1 || interactive))
1661 bfqq->last_wr_start_finish = jiffies;
Paolo Valenteaee69d72017-04-19 08:29:02 -06001662}
1663
1664static struct request *bfq_find_rq_fmerge(struct bfq_data *bfqd,
1665 struct bio *bio,
1666 struct request_queue *q)
1667{
1668 struct bfq_queue *bfqq = bfqd->bio_bfqq;
1669
1670
1671 if (bfqq)
1672 return elv_rb_find(&bfqq->sort_list, bio_end_sector(bio));
1673
1674 return NULL;
1675}
1676
Paolo Valenteab0e43e2017-04-12 18:23:10 +02001677static sector_t get_sdist(sector_t last_pos, struct request *rq)
1678{
1679 if (last_pos)
1680 return abs(blk_rq_pos(rq) - last_pos);
1681
1682 return 0;
1683}
1684
Paolo Valenteaee69d72017-04-19 08:29:02 -06001685#if 0 /* Still not clear if we can do without next two functions */
1686static void bfq_activate_request(struct request_queue *q, struct request *rq)
1687{
1688 struct bfq_data *bfqd = q->elevator->elevator_data;
1689
1690 bfqd->rq_in_driver++;
Paolo Valenteaee69d72017-04-19 08:29:02 -06001691}
1692
1693static void bfq_deactivate_request(struct request_queue *q, struct request *rq)
1694{
1695 struct bfq_data *bfqd = q->elevator->elevator_data;
1696
1697 bfqd->rq_in_driver--;
1698}
1699#endif
1700
1701static void bfq_remove_request(struct request_queue *q,
1702 struct request *rq)
1703{
1704 struct bfq_queue *bfqq = RQ_BFQQ(rq);
1705 struct bfq_data *bfqd = bfqq->bfqd;
1706 const int sync = rq_is_sync(rq);
1707
1708 if (bfqq->next_rq == rq) {
1709 bfqq->next_rq = bfq_find_next_rq(bfqd, bfqq, rq);
1710 bfq_updated_next_req(bfqd, bfqq);
1711 }
1712
1713 if (rq->queuelist.prev != &rq->queuelist)
1714 list_del_init(&rq->queuelist);
1715 bfqq->queued[sync]--;
1716 bfqd->queued--;
1717 elv_rb_del(&bfqq->sort_list, rq);
1718
1719 elv_rqhash_del(q, rq);
1720 if (q->last_merge == rq)
1721 q->last_merge = NULL;
1722
1723 if (RB_EMPTY_ROOT(&bfqq->sort_list)) {
1724 bfqq->next_rq = NULL;
1725
1726 if (bfq_bfqq_busy(bfqq) && bfqq != bfqd->in_service_queue) {
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02001727 bfq_del_bfqq_busy(bfqd, bfqq, false);
Paolo Valenteaee69d72017-04-19 08:29:02 -06001728 /*
1729 * bfqq emptied. In normal operation, when
1730 * bfqq is empty, bfqq->entity.service and
1731 * bfqq->entity.budget must contain,
1732 * respectively, the service received and the
1733 * budget used last time bfqq emptied. These
1734 * facts do not hold in this case, as at least
1735 * this last removal occurred while bfqq is
1736 * not in service. To avoid inconsistencies,
1737 * reset both bfqq->entity.service and
1738 * bfqq->entity.budget, if bfqq has still a
1739 * process that may issue I/O requests to it.
1740 */
1741 bfqq->entity.budget = bfqq->entity.service = 0;
1742 }
Arianna Avanzini36eca892017-04-12 18:23:16 +02001743
1744 /*
1745 * Remove queue from request-position tree as it is empty.
1746 */
1747 if (bfqq->pos_root) {
1748 rb_erase(&bfqq->pos_node, bfqq->pos_root);
1749 bfqq->pos_root = NULL;
1750 }
Paolo Valente05e90282017-12-20 12:38:31 +01001751 } else {
1752 bfq_pos_tree_add_move(bfqd, bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06001753 }
1754
1755 if (rq->cmd_flags & REQ_META)
1756 bfqq->meta_pending--;
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02001757
Paolo Valenteaee69d72017-04-19 08:29:02 -06001758}
1759
1760static bool bfq_bio_merge(struct blk_mq_hw_ctx *hctx, struct bio *bio)
1761{
1762 struct request_queue *q = hctx->queue;
1763 struct bfq_data *bfqd = q->elevator->elevator_data;
1764 struct request *free = NULL;
1765 /*
1766 * bfq_bic_lookup grabs the queue_lock: invoke it now and
1767 * store its return value for later use, to avoid nesting
1768 * queue_lock inside the bfqd->lock. We assume that the bic
1769 * returned by bfq_bic_lookup does not go away before
1770 * bfqd->lock is taken.
1771 */
1772 struct bfq_io_cq *bic = bfq_bic_lookup(bfqd, current->io_context, q);
1773 bool ret;
1774
1775 spin_lock_irq(&bfqd->lock);
1776
1777 if (bic)
1778 bfqd->bio_bfqq = bic_to_bfqq(bic, op_is_sync(bio->bi_opf));
1779 else
1780 bfqd->bio_bfqq = NULL;
1781 bfqd->bio_bic = bic;
1782
1783 ret = blk_mq_sched_try_merge(q, bio, &free);
1784
1785 if (free)
1786 blk_mq_free_request(free);
1787 spin_unlock_irq(&bfqd->lock);
1788
1789 return ret;
1790}
1791
1792static int bfq_request_merge(struct request_queue *q, struct request **req,
1793 struct bio *bio)
1794{
1795 struct bfq_data *bfqd = q->elevator->elevator_data;
1796 struct request *__rq;
1797
1798 __rq = bfq_find_rq_fmerge(bfqd, bio, q);
1799 if (__rq && elv_bio_merge_ok(__rq, bio)) {
1800 *req = __rq;
1801 return ELEVATOR_FRONT_MERGE;
1802 }
1803
1804 return ELEVATOR_NO_MERGE;
1805}
1806
Paolo Valente18e5a572018-05-04 19:17:01 +02001807static struct bfq_queue *bfq_init_rq(struct request *rq);
1808
Paolo Valenteaee69d72017-04-19 08:29:02 -06001809static void bfq_request_merged(struct request_queue *q, struct request *req,
1810 enum elv_merge type)
1811{
1812 if (type == ELEVATOR_FRONT_MERGE &&
1813 rb_prev(&req->rb_node) &&
1814 blk_rq_pos(req) <
1815 blk_rq_pos(container_of(rb_prev(&req->rb_node),
1816 struct request, rb_node))) {
Paolo Valente18e5a572018-05-04 19:17:01 +02001817 struct bfq_queue *bfqq = bfq_init_rq(req);
Paolo Valenteaee69d72017-04-19 08:29:02 -06001818 struct bfq_data *bfqd = bfqq->bfqd;
1819 struct request *prev, *next_rq;
1820
1821 /* Reposition request in its sort_list */
1822 elv_rb_del(&bfqq->sort_list, req);
1823 elv_rb_add(&bfqq->sort_list, req);
1824
1825 /* Choose next request to be served for bfqq */
1826 prev = bfqq->next_rq;
1827 next_rq = bfq_choose_req(bfqd, bfqq->next_rq, req,
1828 bfqd->last_position);
1829 bfqq->next_rq = next_rq;
1830 /*
Arianna Avanzini36eca892017-04-12 18:23:16 +02001831 * If next_rq changes, update both the queue's budget to
1832 * fit the new request and the queue's position in its
1833 * rq_pos_tree.
Paolo Valenteaee69d72017-04-19 08:29:02 -06001834 */
Arianna Avanzini36eca892017-04-12 18:23:16 +02001835 if (prev != bfqq->next_rq) {
Paolo Valenteaee69d72017-04-19 08:29:02 -06001836 bfq_updated_next_req(bfqd, bfqq);
Arianna Avanzini36eca892017-04-12 18:23:16 +02001837 bfq_pos_tree_add_move(bfqd, bfqq);
1838 }
Paolo Valenteaee69d72017-04-19 08:29:02 -06001839 }
1840}
1841
1842static void bfq_requests_merged(struct request_queue *q, struct request *rq,
1843 struct request *next)
1844{
Paolo Valente18e5a572018-05-04 19:17:01 +02001845 struct bfq_queue *bfqq = bfq_init_rq(rq),
1846 *next_bfqq = bfq_init_rq(next);
Paolo Valenteaee69d72017-04-19 08:29:02 -06001847
1848 if (!RB_EMPTY_NODE(&rq->rb_node))
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02001849 goto end;
Paolo Valenteaee69d72017-04-19 08:29:02 -06001850 spin_lock_irq(&bfqq->bfqd->lock);
1851
1852 /*
1853 * If next and rq belong to the same bfq_queue and next is older
1854 * than rq, then reposition rq in the fifo (by substituting next
1855 * with rq). Otherwise, if next and rq belong to different
1856 * bfq_queues, never reposition rq: in fact, we would have to
1857 * reposition it with respect to next's position in its own fifo,
1858 * which would most certainly be too expensive with respect to
1859 * the benefits.
1860 */
1861 if (bfqq == next_bfqq &&
1862 !list_empty(&rq->queuelist) && !list_empty(&next->queuelist) &&
1863 next->fifo_time < rq->fifo_time) {
1864 list_del_init(&rq->queuelist);
1865 list_replace_init(&next->queuelist, &rq->queuelist);
1866 rq->fifo_time = next->fifo_time;
1867 }
1868
1869 if (bfqq->next_rq == next)
1870 bfqq->next_rq = rq;
1871
1872 bfq_remove_request(q, next);
Luca Miccio614822f2017-11-13 07:34:08 +01001873 bfqg_stats_update_io_remove(bfqq_group(bfqq), next->cmd_flags);
Paolo Valenteaee69d72017-04-19 08:29:02 -06001874
1875 spin_unlock_irq(&bfqq->bfqd->lock);
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02001876end:
1877 bfqg_stats_update_io_merged(bfqq_group(bfqq), next->cmd_flags);
Paolo Valenteaee69d72017-04-19 08:29:02 -06001878}
1879
Paolo Valente44e44a12017-04-12 18:23:12 +02001880/* Must be called with bfqq != NULL */
1881static void bfq_bfqq_end_wr(struct bfq_queue *bfqq)
1882{
Paolo Valentecfd69712017-04-12 18:23:15 +02001883 if (bfq_bfqq_busy(bfqq))
1884 bfqq->bfqd->wr_busy_queues--;
Paolo Valente44e44a12017-04-12 18:23:12 +02001885 bfqq->wr_coeff = 1;
1886 bfqq->wr_cur_max_time = 0;
Paolo Valente77b7dce2017-04-12 18:23:13 +02001887 bfqq->last_wr_start_finish = jiffies;
Paolo Valente44e44a12017-04-12 18:23:12 +02001888 /*
1889 * Trigger a weight change on the next invocation of
1890 * __bfq_entity_update_weight_prio.
1891 */
1892 bfqq->entity.prio_changed = 1;
1893}
1894
Paolo Valenteea25da42017-04-19 08:48:24 -06001895void bfq_end_wr_async_queues(struct bfq_data *bfqd,
1896 struct bfq_group *bfqg)
Paolo Valente44e44a12017-04-12 18:23:12 +02001897{
1898 int i, j;
1899
1900 for (i = 0; i < 2; i++)
1901 for (j = 0; j < IOPRIO_BE_NR; j++)
1902 if (bfqg->async_bfqq[i][j])
1903 bfq_bfqq_end_wr(bfqg->async_bfqq[i][j]);
1904 if (bfqg->async_idle_bfqq)
1905 bfq_bfqq_end_wr(bfqg->async_idle_bfqq);
1906}
1907
1908static void bfq_end_wr(struct bfq_data *bfqd)
1909{
1910 struct bfq_queue *bfqq;
1911
1912 spin_lock_irq(&bfqd->lock);
1913
1914 list_for_each_entry(bfqq, &bfqd->active_list, bfqq_list)
1915 bfq_bfqq_end_wr(bfqq);
1916 list_for_each_entry(bfqq, &bfqd->idle_list, bfqq_list)
1917 bfq_bfqq_end_wr(bfqq);
1918 bfq_end_wr_async(bfqd);
1919
1920 spin_unlock_irq(&bfqd->lock);
1921}
1922
Arianna Avanzini36eca892017-04-12 18:23:16 +02001923static sector_t bfq_io_struct_pos(void *io_struct, bool request)
1924{
1925 if (request)
1926 return blk_rq_pos(io_struct);
1927 else
1928 return ((struct bio *)io_struct)->bi_iter.bi_sector;
1929}
1930
1931static int bfq_rq_close_to_sector(void *io_struct, bool request,
1932 sector_t sector)
1933{
1934 return abs(bfq_io_struct_pos(io_struct, request) - sector) <=
1935 BFQQ_CLOSE_THR;
1936}
1937
1938static struct bfq_queue *bfqq_find_close(struct bfq_data *bfqd,
1939 struct bfq_queue *bfqq,
1940 sector_t sector)
1941{
1942 struct rb_root *root = &bfq_bfqq_to_bfqg(bfqq)->rq_pos_tree;
1943 struct rb_node *parent, *node;
1944 struct bfq_queue *__bfqq;
1945
1946 if (RB_EMPTY_ROOT(root))
1947 return NULL;
1948
1949 /*
1950 * First, if we find a request starting at the end of the last
1951 * request, choose it.
1952 */
1953 __bfqq = bfq_rq_pos_tree_lookup(bfqd, root, sector, &parent, NULL);
1954 if (__bfqq)
1955 return __bfqq;
1956
1957 /*
1958 * If the exact sector wasn't found, the parent of the NULL leaf
1959 * will contain the closest sector (rq_pos_tree sorted by
1960 * next_request position).
1961 */
1962 __bfqq = rb_entry(parent, struct bfq_queue, pos_node);
1963 if (bfq_rq_close_to_sector(__bfqq->next_rq, true, sector))
1964 return __bfqq;
1965
1966 if (blk_rq_pos(__bfqq->next_rq) < sector)
1967 node = rb_next(&__bfqq->pos_node);
1968 else
1969 node = rb_prev(&__bfqq->pos_node);
1970 if (!node)
1971 return NULL;
1972
1973 __bfqq = rb_entry(node, struct bfq_queue, pos_node);
1974 if (bfq_rq_close_to_sector(__bfqq->next_rq, true, sector))
1975 return __bfqq;
1976
1977 return NULL;
1978}
1979
1980static struct bfq_queue *bfq_find_close_cooperator(struct bfq_data *bfqd,
1981 struct bfq_queue *cur_bfqq,
1982 sector_t sector)
1983{
1984 struct bfq_queue *bfqq;
1985
1986 /*
1987 * We shall notice if some of the queues are cooperating,
1988 * e.g., working closely on the same area of the device. In
1989 * that case, we can group them together and: 1) don't waste
1990 * time idling, and 2) serve the union of their requests in
1991 * the best possible order for throughput.
1992 */
1993 bfqq = bfqq_find_close(bfqd, cur_bfqq, sector);
1994 if (!bfqq || bfqq == cur_bfqq)
1995 return NULL;
1996
1997 return bfqq;
1998}
1999
2000static struct bfq_queue *
2001bfq_setup_merge(struct bfq_queue *bfqq, struct bfq_queue *new_bfqq)
2002{
2003 int process_refs, new_process_refs;
2004 struct bfq_queue *__bfqq;
2005
2006 /*
2007 * If there are no process references on the new_bfqq, then it is
2008 * unsafe to follow the ->new_bfqq chain as other bfqq's in the chain
2009 * may have dropped their last reference (not just their last process
2010 * reference).
2011 */
2012 if (!bfqq_process_refs(new_bfqq))
2013 return NULL;
2014
2015 /* Avoid a circular list and skip interim queue merges. */
2016 while ((__bfqq = new_bfqq->new_bfqq)) {
2017 if (__bfqq == bfqq)
2018 return NULL;
2019 new_bfqq = __bfqq;
2020 }
2021
2022 process_refs = bfqq_process_refs(bfqq);
2023 new_process_refs = bfqq_process_refs(new_bfqq);
2024 /*
2025 * If the process for the bfqq has gone away, there is no
2026 * sense in merging the queues.
2027 */
2028 if (process_refs == 0 || new_process_refs == 0)
2029 return NULL;
2030
2031 bfq_log_bfqq(bfqq->bfqd, bfqq, "scheduling merge with queue %d",
2032 new_bfqq->pid);
2033
2034 /*
2035 * Merging is just a redirection: the requests of the process
2036 * owning one of the two queues are redirected to the other queue.
2037 * The latter queue, in its turn, is set as shared if this is the
2038 * first time that the requests of some process are redirected to
2039 * it.
2040 *
Paolo Valente6fa3e8d2017-04-12 18:23:21 +02002041 * We redirect bfqq to new_bfqq and not the opposite, because
2042 * we are in the context of the process owning bfqq, thus we
2043 * have the io_cq of this process. So we can immediately
2044 * configure this io_cq to redirect the requests of the
2045 * process to new_bfqq. In contrast, the io_cq of new_bfqq is
2046 * not available any more (new_bfqq->bic == NULL).
Arianna Avanzini36eca892017-04-12 18:23:16 +02002047 *
Paolo Valente6fa3e8d2017-04-12 18:23:21 +02002048 * Anyway, even in case new_bfqq coincides with the in-service
2049 * queue, redirecting requests the in-service queue is the
2050 * best option, as we feed the in-service queue with new
2051 * requests close to the last request served and, by doing so,
2052 * are likely to increase the throughput.
Arianna Avanzini36eca892017-04-12 18:23:16 +02002053 */
2054 bfqq->new_bfqq = new_bfqq;
2055 new_bfqq->ref += process_refs;
2056 return new_bfqq;
2057}
2058
2059static bool bfq_may_be_close_cooperator(struct bfq_queue *bfqq,
2060 struct bfq_queue *new_bfqq)
2061{
Paolo Valente7b8fa3b2017-12-20 12:38:33 +01002062 if (bfq_too_late_for_merging(new_bfqq))
2063 return false;
2064
Arianna Avanzini36eca892017-04-12 18:23:16 +02002065 if (bfq_class_idle(bfqq) || bfq_class_idle(new_bfqq) ||
2066 (bfqq->ioprio_class != new_bfqq->ioprio_class))
2067 return false;
2068
2069 /*
2070 * If either of the queues has already been detected as seeky,
2071 * then merging it with the other queue is unlikely to lead to
2072 * sequential I/O.
2073 */
2074 if (BFQQ_SEEKY(bfqq) || BFQQ_SEEKY(new_bfqq))
2075 return false;
2076
2077 /*
2078 * Interleaved I/O is known to be done by (some) applications
2079 * only for reads, so it does not make sense to merge async
2080 * queues.
2081 */
2082 if (!bfq_bfqq_sync(bfqq) || !bfq_bfqq_sync(new_bfqq))
2083 return false;
2084
2085 return true;
2086}
2087
2088/*
Arianna Avanzini36eca892017-04-12 18:23:16 +02002089 * Attempt to schedule a merge of bfqq with the currently in-service
2090 * queue or with a close queue among the scheduled queues. Return
2091 * NULL if no merge was scheduled, a pointer to the shared bfq_queue
2092 * structure otherwise.
2093 *
2094 * The OOM queue is not allowed to participate to cooperation: in fact, since
2095 * the requests temporarily redirected to the OOM queue could be redirected
2096 * again to dedicated queues at any time, the state needed to correctly
2097 * handle merging with the OOM queue would be quite complex and expensive
2098 * to maintain. Besides, in such a critical condition as an out of memory,
2099 * the benefits of queue merging may be little relevant, or even negligible.
2100 *
Arianna Avanzini36eca892017-04-12 18:23:16 +02002101 * WARNING: queue merging may impair fairness among non-weight raised
2102 * queues, for at least two reasons: 1) the original weight of a
2103 * merged queue may change during the merged state, 2) even being the
2104 * weight the same, a merged queue may be bloated with many more
2105 * requests than the ones produced by its originally-associated
2106 * process.
2107 */
2108static struct bfq_queue *
2109bfq_setup_cooperator(struct bfq_data *bfqd, struct bfq_queue *bfqq,
2110 void *io_struct, bool request)
2111{
2112 struct bfq_queue *in_service_bfqq, *new_bfqq;
2113
Paolo Valente7b8fa3b2017-12-20 12:38:33 +01002114 /*
2115 * Prevent bfqq from being merged if it has been created too
2116 * long ago. The idea is that true cooperating processes, and
2117 * thus their associated bfq_queues, are supposed to be
2118 * created shortly after each other. This is the case, e.g.,
2119 * for KVM/QEMU and dump I/O threads. Basing on this
2120 * assumption, the following filtering greatly reduces the
2121 * probability that two non-cooperating processes, which just
2122 * happen to do close I/O for some short time interval, have
2123 * their queues merged by mistake.
2124 */
2125 if (bfq_too_late_for_merging(bfqq))
2126 return NULL;
2127
Arianna Avanzini36eca892017-04-12 18:23:16 +02002128 if (bfqq->new_bfqq)
2129 return bfqq->new_bfqq;
2130
Angelo Ruocco4403e4e2017-12-20 12:38:34 +01002131 if (!io_struct || unlikely(bfqq == &bfqd->oom_bfqq))
Arianna Avanzini36eca892017-04-12 18:23:16 +02002132 return NULL;
2133
2134 /* If there is only one backlogged queue, don't search. */
2135 if (bfqd->busy_queues == 1)
2136 return NULL;
2137
2138 in_service_bfqq = bfqd->in_service_queue;
2139
Angelo Ruocco4403e4e2017-12-20 12:38:34 +01002140 if (in_service_bfqq && in_service_bfqq != bfqq &&
2141 likely(in_service_bfqq != &bfqd->oom_bfqq) &&
2142 bfq_rq_close_to_sector(io_struct, request, bfqd->last_position) &&
Arianna Avanzini36eca892017-04-12 18:23:16 +02002143 bfqq->entity.parent == in_service_bfqq->entity.parent &&
2144 bfq_may_be_close_cooperator(bfqq, in_service_bfqq)) {
2145 new_bfqq = bfq_setup_merge(bfqq, in_service_bfqq);
2146 if (new_bfqq)
2147 return new_bfqq;
2148 }
2149 /*
2150 * Check whether there is a cooperator among currently scheduled
2151 * queues. The only thing we need is that the bio/request is not
2152 * NULL, as we need it to establish whether a cooperator exists.
2153 */
Arianna Avanzini36eca892017-04-12 18:23:16 +02002154 new_bfqq = bfq_find_close_cooperator(bfqd, bfqq,
2155 bfq_io_struct_pos(io_struct, request));
2156
Angelo Ruocco4403e4e2017-12-20 12:38:34 +01002157 if (new_bfqq && likely(new_bfqq != &bfqd->oom_bfqq) &&
Arianna Avanzini36eca892017-04-12 18:23:16 +02002158 bfq_may_be_close_cooperator(bfqq, new_bfqq))
2159 return bfq_setup_merge(bfqq, new_bfqq);
2160
2161 return NULL;
2162}
2163
2164static void bfq_bfqq_save_state(struct bfq_queue *bfqq)
2165{
2166 struct bfq_io_cq *bic = bfqq->bic;
2167
2168 /*
2169 * If !bfqq->bic, the queue is already shared or its requests
2170 * have already been redirected to a shared queue; both idle window
2171 * and weight raising state have already been saved. Do nothing.
2172 */
2173 if (!bic)
2174 return;
2175
2176 bic->saved_ttime = bfqq->ttime;
Paolo Valented5be3fe2017-08-04 07:35:10 +02002177 bic->saved_has_short_ttime = bfq_bfqq_has_short_ttime(bfqq);
Arianna Avanzini36eca892017-04-12 18:23:16 +02002178 bic->saved_IO_bound = bfq_bfqq_IO_bound(bfqq);
Arianna Avanzinie1b23242017-04-12 18:23:20 +02002179 bic->saved_in_large_burst = bfq_bfqq_in_large_burst(bfqq);
2180 bic->was_in_burst_list = !hlist_unhashed(&bfqq->burst_list_node);
Paolo Valente894df932017-09-21 11:04:02 +02002181 if (unlikely(bfq_bfqq_just_created(bfqq) &&
Angelo Ruocco1be6e8a2017-12-20 12:38:32 +01002182 !bfq_bfqq_in_large_burst(bfqq) &&
2183 bfqq->bfqd->low_latency)) {
Paolo Valente894df932017-09-21 11:04:02 +02002184 /*
2185 * bfqq being merged right after being created: bfqq
2186 * would have deserved interactive weight raising, but
2187 * did not make it to be set in a weight-raised state,
2188 * because of this early merge. Store directly the
2189 * weight-raising state that would have been assigned
2190 * to bfqq, so that to avoid that bfqq unjustly fails
2191 * to enjoy weight raising if split soon.
2192 */
2193 bic->saved_wr_coeff = bfqq->bfqd->bfq_wr_coeff;
2194 bic->saved_wr_cur_max_time = bfq_wr_duration(bfqq->bfqd);
2195 bic->saved_last_wr_start_finish = jiffies;
2196 } else {
2197 bic->saved_wr_coeff = bfqq->wr_coeff;
2198 bic->saved_wr_start_at_switch_to_srt =
2199 bfqq->wr_start_at_switch_to_srt;
2200 bic->saved_last_wr_start_finish = bfqq->last_wr_start_finish;
2201 bic->saved_wr_cur_max_time = bfqq->wr_cur_max_time;
2202 }
Arianna Avanzini36eca892017-04-12 18:23:16 +02002203}
2204
Arianna Avanzini36eca892017-04-12 18:23:16 +02002205static void
2206bfq_merge_bfqqs(struct bfq_data *bfqd, struct bfq_io_cq *bic,
2207 struct bfq_queue *bfqq, struct bfq_queue *new_bfqq)
2208{
2209 bfq_log_bfqq(bfqd, bfqq, "merging with queue %lu",
2210 (unsigned long)new_bfqq->pid);
2211 /* Save weight raising and idle window of the merged queues */
2212 bfq_bfqq_save_state(bfqq);
2213 bfq_bfqq_save_state(new_bfqq);
2214 if (bfq_bfqq_IO_bound(bfqq))
2215 bfq_mark_bfqq_IO_bound(new_bfqq);
2216 bfq_clear_bfqq_IO_bound(bfqq);
2217
2218 /*
2219 * If bfqq is weight-raised, then let new_bfqq inherit
2220 * weight-raising. To reduce false positives, neglect the case
2221 * where bfqq has just been created, but has not yet made it
2222 * to be weight-raised (which may happen because EQM may merge
2223 * bfqq even before bfq_add_request is executed for the first
Arianna Avanzinie1b23242017-04-12 18:23:20 +02002224 * time for bfqq). Handling this case would however be very
2225 * easy, thanks to the flag just_created.
Arianna Avanzini36eca892017-04-12 18:23:16 +02002226 */
2227 if (new_bfqq->wr_coeff == 1 && bfqq->wr_coeff > 1) {
2228 new_bfqq->wr_coeff = bfqq->wr_coeff;
2229 new_bfqq->wr_cur_max_time = bfqq->wr_cur_max_time;
2230 new_bfqq->last_wr_start_finish = bfqq->last_wr_start_finish;
2231 new_bfqq->wr_start_at_switch_to_srt =
2232 bfqq->wr_start_at_switch_to_srt;
2233 if (bfq_bfqq_busy(new_bfqq))
2234 bfqd->wr_busy_queues++;
2235 new_bfqq->entity.prio_changed = 1;
2236 }
2237
2238 if (bfqq->wr_coeff > 1) { /* bfqq has given its wr to new_bfqq */
2239 bfqq->wr_coeff = 1;
2240 bfqq->entity.prio_changed = 1;
2241 if (bfq_bfqq_busy(bfqq))
2242 bfqd->wr_busy_queues--;
2243 }
2244
2245 bfq_log_bfqq(bfqd, new_bfqq, "merge_bfqqs: wr_busy %d",
2246 bfqd->wr_busy_queues);
2247
2248 /*
Arianna Avanzini36eca892017-04-12 18:23:16 +02002249 * Merge queues (that is, let bic redirect its requests to new_bfqq)
2250 */
2251 bic_set_bfqq(bic, new_bfqq, 1);
2252 bfq_mark_bfqq_coop(new_bfqq);
2253 /*
2254 * new_bfqq now belongs to at least two bics (it is a shared queue):
2255 * set new_bfqq->bic to NULL. bfqq either:
2256 * - does not belong to any bic any more, and hence bfqq->bic must
2257 * be set to NULL, or
2258 * - is a queue whose owning bics have already been redirected to a
2259 * different queue, hence the queue is destined to not belong to
2260 * any bic soon and bfqq->bic is already NULL (therefore the next
2261 * assignment causes no harm).
2262 */
2263 new_bfqq->bic = NULL;
2264 bfqq->bic = NULL;
2265 /* release process reference to bfqq */
2266 bfq_put_queue(bfqq);
2267}
2268
Paolo Valenteaee69d72017-04-19 08:29:02 -06002269static bool bfq_allow_bio_merge(struct request_queue *q, struct request *rq,
2270 struct bio *bio)
2271{
2272 struct bfq_data *bfqd = q->elevator->elevator_data;
2273 bool is_sync = op_is_sync(bio->bi_opf);
Arianna Avanzini36eca892017-04-12 18:23:16 +02002274 struct bfq_queue *bfqq = bfqd->bio_bfqq, *new_bfqq;
Paolo Valenteaee69d72017-04-19 08:29:02 -06002275
2276 /*
2277 * Disallow merge of a sync bio into an async request.
2278 */
2279 if (is_sync && !rq_is_sync(rq))
2280 return false;
2281
2282 /*
2283 * Lookup the bfqq that this bio will be queued with. Allow
2284 * merge only if rq is queued there.
2285 */
2286 if (!bfqq)
2287 return false;
2288
Arianna Avanzini36eca892017-04-12 18:23:16 +02002289 /*
2290 * We take advantage of this function to perform an early merge
2291 * of the queues of possible cooperating processes.
2292 */
2293 new_bfqq = bfq_setup_cooperator(bfqd, bfqq, bio, false);
2294 if (new_bfqq) {
2295 /*
2296 * bic still points to bfqq, then it has not yet been
2297 * redirected to some other bfq_queue, and a queue
2298 * merge beween bfqq and new_bfqq can be safely
2299 * fulfillled, i.e., bic can be redirected to new_bfqq
2300 * and bfqq can be put.
2301 */
2302 bfq_merge_bfqqs(bfqd, bfqd->bio_bic, bfqq,
2303 new_bfqq);
2304 /*
2305 * If we get here, bio will be queued into new_queue,
2306 * so use new_bfqq to decide whether bio and rq can be
2307 * merged.
2308 */
2309 bfqq = new_bfqq;
2310
2311 /*
2312 * Change also bqfd->bio_bfqq, as
2313 * bfqd->bio_bic now points to new_bfqq, and
2314 * this function may be invoked again (and then may
2315 * use again bqfd->bio_bfqq).
2316 */
2317 bfqd->bio_bfqq = bfqq;
2318 }
2319
Paolo Valenteaee69d72017-04-19 08:29:02 -06002320 return bfqq == RQ_BFQQ(rq);
2321}
2322
Paolo Valente44e44a12017-04-12 18:23:12 +02002323/*
2324 * Set the maximum time for the in-service queue to consume its
2325 * budget. This prevents seeky processes from lowering the throughput.
2326 * In practice, a time-slice service scheme is used with seeky
2327 * processes.
2328 */
2329static void bfq_set_budget_timeout(struct bfq_data *bfqd,
2330 struct bfq_queue *bfqq)
2331{
Paolo Valente77b7dce2017-04-12 18:23:13 +02002332 unsigned int timeout_coeff;
2333
2334 if (bfqq->wr_cur_max_time == bfqd->bfq_wr_rt_max_time)
2335 timeout_coeff = 1;
2336 else
2337 timeout_coeff = bfqq->entity.weight / bfqq->entity.orig_weight;
2338
Paolo Valente44e44a12017-04-12 18:23:12 +02002339 bfqd->last_budget_start = ktime_get();
2340
2341 bfqq->budget_timeout = jiffies +
Paolo Valente77b7dce2017-04-12 18:23:13 +02002342 bfqd->bfq_timeout * timeout_coeff;
Paolo Valente44e44a12017-04-12 18:23:12 +02002343}
2344
Paolo Valenteaee69d72017-04-19 08:29:02 -06002345static void __bfq_set_in_service_queue(struct bfq_data *bfqd,
2346 struct bfq_queue *bfqq)
2347{
2348 if (bfqq) {
Paolo Valenteaee69d72017-04-19 08:29:02 -06002349 bfq_clear_bfqq_fifo_expire(bfqq);
2350
2351 bfqd->budgets_assigned = (bfqd->budgets_assigned * 7 + 256) / 8;
2352
Paolo Valente77b7dce2017-04-12 18:23:13 +02002353 if (time_is_before_jiffies(bfqq->last_wr_start_finish) &&
2354 bfqq->wr_coeff > 1 &&
2355 bfqq->wr_cur_max_time == bfqd->bfq_wr_rt_max_time &&
2356 time_is_before_jiffies(bfqq->budget_timeout)) {
2357 /*
2358 * For soft real-time queues, move the start
2359 * of the weight-raising period forward by the
2360 * time the queue has not received any
2361 * service. Otherwise, a relatively long
2362 * service delay is likely to cause the
2363 * weight-raising period of the queue to end,
2364 * because of the short duration of the
2365 * weight-raising period of a soft real-time
2366 * queue. It is worth noting that this move
2367 * is not so dangerous for the other queues,
2368 * because soft real-time queues are not
2369 * greedy.
2370 *
2371 * To not add a further variable, we use the
2372 * overloaded field budget_timeout to
2373 * determine for how long the queue has not
2374 * received service, i.e., how much time has
2375 * elapsed since the queue expired. However,
2376 * this is a little imprecise, because
2377 * budget_timeout is set to jiffies if bfqq
2378 * not only expires, but also remains with no
2379 * request.
2380 */
2381 if (time_after(bfqq->budget_timeout,
2382 bfqq->last_wr_start_finish))
2383 bfqq->last_wr_start_finish +=
2384 jiffies - bfqq->budget_timeout;
2385 else
2386 bfqq->last_wr_start_finish = jiffies;
2387 }
2388
Paolo Valente44e44a12017-04-12 18:23:12 +02002389 bfq_set_budget_timeout(bfqd, bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06002390 bfq_log_bfqq(bfqd, bfqq,
2391 "set_in_service_queue, cur-budget = %d",
2392 bfqq->entity.budget);
2393 }
2394
2395 bfqd->in_service_queue = bfqq;
2396}
2397
2398/*
2399 * Get and set a new queue for service.
2400 */
2401static struct bfq_queue *bfq_set_in_service_queue(struct bfq_data *bfqd)
2402{
2403 struct bfq_queue *bfqq = bfq_get_next_queue(bfqd);
2404
2405 __bfq_set_in_service_queue(bfqd, bfqq);
2406 return bfqq;
2407}
2408
Paolo Valenteaee69d72017-04-19 08:29:02 -06002409static void bfq_arm_slice_timer(struct bfq_data *bfqd)
2410{
2411 struct bfq_queue *bfqq = bfqd->in_service_queue;
Paolo Valenteaee69d72017-04-19 08:29:02 -06002412 u32 sl;
2413
Paolo Valenteaee69d72017-04-19 08:29:02 -06002414 bfq_mark_bfqq_wait_request(bfqq);
2415
2416 /*
2417 * We don't want to idle for seeks, but we do want to allow
2418 * fair distribution of slice time for a process doing back-to-back
2419 * seeks. So allow a little bit of time for him to submit a new rq.
2420 */
2421 sl = bfqd->bfq_slice_idle;
2422 /*
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +02002423 * Unless the queue is being weight-raised or the scenario is
2424 * asymmetric, grant only minimum idle time if the queue
2425 * is seeky. A long idling is preserved for a weight-raised
2426 * queue, or, more in general, in an asymmetric scenario,
2427 * because a long idling is needed for guaranteeing to a queue
2428 * its reserved share of the throughput (in particular, it is
2429 * needed if the queue has a higher weight than some other
2430 * queue).
Paolo Valenteaee69d72017-04-19 08:29:02 -06002431 */
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +02002432 if (BFQQ_SEEKY(bfqq) && bfqq->wr_coeff == 1 &&
2433 bfq_symmetric_scenario(bfqd))
Paolo Valenteaee69d72017-04-19 08:29:02 -06002434 sl = min_t(u64, sl, BFQ_MIN_TT);
2435
2436 bfqd->last_idling_start = ktime_get();
2437 hrtimer_start(&bfqd->idle_slice_timer, ns_to_ktime(sl),
2438 HRTIMER_MODE_REL);
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02002439 bfqg_stats_set_start_idle_time(bfqq_group(bfqq));
Paolo Valenteaee69d72017-04-19 08:29:02 -06002440}
2441
2442/*
Paolo Valenteab0e43e2017-04-12 18:23:10 +02002443 * In autotuning mode, max_budget is dynamically recomputed as the
2444 * amount of sectors transferred in timeout at the estimated peak
2445 * rate. This enables BFQ to utilize a full timeslice with a full
2446 * budget, even if the in-service queue is served at peak rate. And
2447 * this maximises throughput with sequential workloads.
2448 */
2449static unsigned long bfq_calc_max_budget(struct bfq_data *bfqd)
2450{
2451 return (u64)bfqd->peak_rate * USEC_PER_MSEC *
2452 jiffies_to_msecs(bfqd->bfq_timeout)>>BFQ_RATE_SHIFT;
2453}
2454
Paolo Valente44e44a12017-04-12 18:23:12 +02002455/*
2456 * Update parameters related to throughput and responsiveness, as a
2457 * function of the estimated peak rate. See comments on
2458 * bfq_calc_max_budget(), and on T_slow and T_fast arrays.
2459 */
2460static void update_thr_responsiveness_params(struct bfq_data *bfqd)
2461{
2462 int dev_type = blk_queue_nonrot(bfqd->queue);
2463
2464 if (bfqd->bfq_user_max_budget == 0)
2465 bfqd->bfq_max_budget =
2466 bfq_calc_max_budget(bfqd);
2467
2468 if (bfqd->device_speed == BFQ_BFQD_FAST &&
2469 bfqd->peak_rate < device_speed_thresh[dev_type]) {
2470 bfqd->device_speed = BFQ_BFQD_SLOW;
2471 bfqd->RT_prod = R_slow[dev_type] *
2472 T_slow[dev_type];
2473 } else if (bfqd->device_speed == BFQ_BFQD_SLOW &&
2474 bfqd->peak_rate > device_speed_thresh[dev_type]) {
2475 bfqd->device_speed = BFQ_BFQD_FAST;
2476 bfqd->RT_prod = R_fast[dev_type] *
2477 T_fast[dev_type];
2478 }
2479
2480 bfq_log(bfqd,
2481"dev_type %s dev_speed_class = %s (%llu sects/sec), thresh %llu setcs/sec",
2482 dev_type == 0 ? "ROT" : "NONROT",
2483 bfqd->device_speed == BFQ_BFQD_FAST ? "FAST" : "SLOW",
2484 bfqd->device_speed == BFQ_BFQD_FAST ?
2485 (USEC_PER_SEC*(u64)R_fast[dev_type])>>BFQ_RATE_SHIFT :
2486 (USEC_PER_SEC*(u64)R_slow[dev_type])>>BFQ_RATE_SHIFT,
2487 (USEC_PER_SEC*(u64)device_speed_thresh[dev_type])>>
2488 BFQ_RATE_SHIFT);
2489}
2490
Paolo Valenteab0e43e2017-04-12 18:23:10 +02002491static void bfq_reset_rate_computation(struct bfq_data *bfqd,
2492 struct request *rq)
2493{
2494 if (rq != NULL) { /* new rq dispatch now, reset accordingly */
2495 bfqd->last_dispatch = bfqd->first_dispatch = ktime_get_ns();
2496 bfqd->peak_rate_samples = 1;
2497 bfqd->sequential_samples = 0;
2498 bfqd->tot_sectors_dispatched = bfqd->last_rq_max_size =
2499 blk_rq_sectors(rq);
2500 } else /* no new rq dispatched, just reset the number of samples */
2501 bfqd->peak_rate_samples = 0; /* full re-init on next disp. */
2502
2503 bfq_log(bfqd,
2504 "reset_rate_computation at end, sample %u/%u tot_sects %llu",
2505 bfqd->peak_rate_samples, bfqd->sequential_samples,
2506 bfqd->tot_sectors_dispatched);
2507}
2508
2509static void bfq_update_rate_reset(struct bfq_data *bfqd, struct request *rq)
2510{
2511 u32 rate, weight, divisor;
2512
2513 /*
2514 * For the convergence property to hold (see comments on
2515 * bfq_update_peak_rate()) and for the assessment to be
2516 * reliable, a minimum number of samples must be present, and
2517 * a minimum amount of time must have elapsed. If not so, do
2518 * not compute new rate. Just reset parameters, to get ready
2519 * for a new evaluation attempt.
2520 */
2521 if (bfqd->peak_rate_samples < BFQ_RATE_MIN_SAMPLES ||
2522 bfqd->delta_from_first < BFQ_RATE_MIN_INTERVAL)
2523 goto reset_computation;
2524
2525 /*
2526 * If a new request completion has occurred after last
2527 * dispatch, then, to approximate the rate at which requests
2528 * have been served by the device, it is more precise to
2529 * extend the observation interval to the last completion.
2530 */
2531 bfqd->delta_from_first =
2532 max_t(u64, bfqd->delta_from_first,
2533 bfqd->last_completion - bfqd->first_dispatch);
2534
2535 /*
2536 * Rate computed in sects/usec, and not sects/nsec, for
2537 * precision issues.
2538 */
2539 rate = div64_ul(bfqd->tot_sectors_dispatched<<BFQ_RATE_SHIFT,
2540 div_u64(bfqd->delta_from_first, NSEC_PER_USEC));
2541
2542 /*
2543 * Peak rate not updated if:
2544 * - the percentage of sequential dispatches is below 3/4 of the
2545 * total, and rate is below the current estimated peak rate
2546 * - rate is unreasonably high (> 20M sectors/sec)
2547 */
2548 if ((bfqd->sequential_samples < (3 * bfqd->peak_rate_samples)>>2 &&
2549 rate <= bfqd->peak_rate) ||
2550 rate > 20<<BFQ_RATE_SHIFT)
2551 goto reset_computation;
2552
2553 /*
2554 * We have to update the peak rate, at last! To this purpose,
2555 * we use a low-pass filter. We compute the smoothing constant
2556 * of the filter as a function of the 'weight' of the new
2557 * measured rate.
2558 *
2559 * As can be seen in next formulas, we define this weight as a
2560 * quantity proportional to how sequential the workload is,
2561 * and to how long the observation time interval is.
2562 *
2563 * The weight runs from 0 to 8. The maximum value of the
2564 * weight, 8, yields the minimum value for the smoothing
2565 * constant. At this minimum value for the smoothing constant,
2566 * the measured rate contributes for half of the next value of
2567 * the estimated peak rate.
2568 *
2569 * So, the first step is to compute the weight as a function
2570 * of how sequential the workload is. Note that the weight
2571 * cannot reach 9, because bfqd->sequential_samples cannot
2572 * become equal to bfqd->peak_rate_samples, which, in its
2573 * turn, holds true because bfqd->sequential_samples is not
2574 * incremented for the first sample.
2575 */
2576 weight = (9 * bfqd->sequential_samples) / bfqd->peak_rate_samples;
2577
2578 /*
2579 * Second step: further refine the weight as a function of the
2580 * duration of the observation interval.
2581 */
2582 weight = min_t(u32, 8,
2583 div_u64(weight * bfqd->delta_from_first,
2584 BFQ_RATE_REF_INTERVAL));
2585
2586 /*
2587 * Divisor ranging from 10, for minimum weight, to 2, for
2588 * maximum weight.
2589 */
2590 divisor = 10 - weight;
2591
2592 /*
2593 * Finally, update peak rate:
2594 *
2595 * peak_rate = peak_rate * (divisor-1) / divisor + rate / divisor
2596 */
2597 bfqd->peak_rate *= divisor-1;
2598 bfqd->peak_rate /= divisor;
2599 rate /= divisor; /* smoothing constant alpha = 1/divisor */
2600
2601 bfqd->peak_rate += rate;
Paolo Valentebc56e2c2018-03-26 16:06:24 +02002602
2603 /*
2604 * For a very slow device, bfqd->peak_rate can reach 0 (see
2605 * the minimum representable values reported in the comments
2606 * on BFQ_RATE_SHIFT). Push to 1 if this happens, to avoid
2607 * divisions by zero where bfqd->peak_rate is used as a
2608 * divisor.
2609 */
2610 bfqd->peak_rate = max_t(u32, 1, bfqd->peak_rate);
2611
Paolo Valente44e44a12017-04-12 18:23:12 +02002612 update_thr_responsiveness_params(bfqd);
Paolo Valenteab0e43e2017-04-12 18:23:10 +02002613
2614reset_computation:
2615 bfq_reset_rate_computation(bfqd, rq);
2616}
2617
2618/*
2619 * Update the read/write peak rate (the main quantity used for
2620 * auto-tuning, see update_thr_responsiveness_params()).
2621 *
2622 * It is not trivial to estimate the peak rate (correctly): because of
2623 * the presence of sw and hw queues between the scheduler and the
2624 * device components that finally serve I/O requests, it is hard to
2625 * say exactly when a given dispatched request is served inside the
2626 * device, and for how long. As a consequence, it is hard to know
2627 * precisely at what rate a given set of requests is actually served
2628 * by the device.
2629 *
2630 * On the opposite end, the dispatch time of any request is trivially
2631 * available, and, from this piece of information, the "dispatch rate"
2632 * of requests can be immediately computed. So, the idea in the next
2633 * function is to use what is known, namely request dispatch times
2634 * (plus, when useful, request completion times), to estimate what is
2635 * unknown, namely in-device request service rate.
2636 *
2637 * The main issue is that, because of the above facts, the rate at
2638 * which a certain set of requests is dispatched over a certain time
2639 * interval can vary greatly with respect to the rate at which the
2640 * same requests are then served. But, since the size of any
2641 * intermediate queue is limited, and the service scheme is lossless
2642 * (no request is silently dropped), the following obvious convergence
2643 * property holds: the number of requests dispatched MUST become
2644 * closer and closer to the number of requests completed as the
2645 * observation interval grows. This is the key property used in
2646 * the next function to estimate the peak service rate as a function
2647 * of the observed dispatch rate. The function assumes to be invoked
2648 * on every request dispatch.
2649 */
2650static void bfq_update_peak_rate(struct bfq_data *bfqd, struct request *rq)
2651{
2652 u64 now_ns = ktime_get_ns();
2653
2654 if (bfqd->peak_rate_samples == 0) { /* first dispatch */
2655 bfq_log(bfqd, "update_peak_rate: goto reset, samples %d",
2656 bfqd->peak_rate_samples);
2657 bfq_reset_rate_computation(bfqd, rq);
2658 goto update_last_values; /* will add one sample */
2659 }
2660
2661 /*
2662 * Device idle for very long: the observation interval lasting
2663 * up to this dispatch cannot be a valid observation interval
2664 * for computing a new peak rate (similarly to the late-
2665 * completion event in bfq_completed_request()). Go to
2666 * update_rate_and_reset to have the following three steps
2667 * taken:
2668 * - close the observation interval at the last (previous)
2669 * request dispatch or completion
2670 * - compute rate, if possible, for that observation interval
2671 * - start a new observation interval with this dispatch
2672 */
2673 if (now_ns - bfqd->last_dispatch > 100*NSEC_PER_MSEC &&
2674 bfqd->rq_in_driver == 0)
2675 goto update_rate_and_reset;
2676
2677 /* Update sampling information */
2678 bfqd->peak_rate_samples++;
2679
2680 if ((bfqd->rq_in_driver > 0 ||
2681 now_ns - bfqd->last_completion < BFQ_MIN_TT)
2682 && get_sdist(bfqd->last_position, rq) < BFQQ_SEEK_THR)
2683 bfqd->sequential_samples++;
2684
2685 bfqd->tot_sectors_dispatched += blk_rq_sectors(rq);
2686
2687 /* Reset max observed rq size every 32 dispatches */
2688 if (likely(bfqd->peak_rate_samples % 32))
2689 bfqd->last_rq_max_size =
2690 max_t(u32, blk_rq_sectors(rq), bfqd->last_rq_max_size);
2691 else
2692 bfqd->last_rq_max_size = blk_rq_sectors(rq);
2693
2694 bfqd->delta_from_first = now_ns - bfqd->first_dispatch;
2695
2696 /* Target observation interval not yet reached, go on sampling */
2697 if (bfqd->delta_from_first < BFQ_RATE_REF_INTERVAL)
2698 goto update_last_values;
2699
2700update_rate_and_reset:
2701 bfq_update_rate_reset(bfqd, rq);
2702update_last_values:
2703 bfqd->last_position = blk_rq_pos(rq) + blk_rq_sectors(rq);
2704 bfqd->last_dispatch = now_ns;
2705}
2706
2707/*
Paolo Valenteaee69d72017-04-19 08:29:02 -06002708 * Remove request from internal lists.
2709 */
2710static void bfq_dispatch_remove(struct request_queue *q, struct request *rq)
2711{
2712 struct bfq_queue *bfqq = RQ_BFQQ(rq);
2713
2714 /*
2715 * For consistency, the next instruction should have been
2716 * executed after removing the request from the queue and
2717 * dispatching it. We execute instead this instruction before
2718 * bfq_remove_request() (and hence introduce a temporary
2719 * inconsistency), for efficiency. In fact, should this
2720 * dispatch occur for a non in-service bfqq, this anticipated
2721 * increment prevents two counters related to bfqq->dispatched
2722 * from risking to be, first, uselessly decremented, and then
2723 * incremented again when the (new) value of bfqq->dispatched
2724 * happens to be taken into account.
2725 */
2726 bfqq->dispatched++;
Paolo Valenteab0e43e2017-04-12 18:23:10 +02002727 bfq_update_peak_rate(q->elevator->elevator_data, rq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06002728
2729 bfq_remove_request(q, rq);
2730}
2731
2732static void __bfq_bfqq_expire(struct bfq_data *bfqd, struct bfq_queue *bfqq)
2733{
Arianna Avanzini36eca892017-04-12 18:23:16 +02002734 /*
2735 * If this bfqq is shared between multiple processes, check
2736 * to make sure that those processes are still issuing I/Os
2737 * within the mean seek distance. If not, it may be time to
2738 * break the queues apart again.
2739 */
2740 if (bfq_bfqq_coop(bfqq) && BFQQ_SEEKY(bfqq))
2741 bfq_mark_bfqq_split_coop(bfqq);
2742
Paolo Valente44e44a12017-04-12 18:23:12 +02002743 if (RB_EMPTY_ROOT(&bfqq->sort_list)) {
2744 if (bfqq->dispatched == 0)
2745 /*
2746 * Overloading budget_timeout field to store
2747 * the time at which the queue remains with no
2748 * backlog and no outstanding request; used by
2749 * the weight-raising mechanism.
2750 */
2751 bfqq->budget_timeout = jiffies;
2752
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02002753 bfq_del_bfqq_busy(bfqd, bfqq, true);
Arianna Avanzini36eca892017-04-12 18:23:16 +02002754 } else {
Paolo Valente80294c32017-08-31 08:46:29 +02002755 bfq_requeue_bfqq(bfqd, bfqq, true);
Arianna Avanzini36eca892017-04-12 18:23:16 +02002756 /*
2757 * Resort priority tree of potential close cooperators.
2758 */
2759 bfq_pos_tree_add_move(bfqd, bfqq);
2760 }
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02002761
2762 /*
2763 * All in-service entities must have been properly deactivated
2764 * or requeued before executing the next function, which
2765 * resets all in-service entites as no more in service.
2766 */
2767 __bfq_bfqd_reset_in_service(bfqd);
Paolo Valenteaee69d72017-04-19 08:29:02 -06002768}
2769
2770/**
2771 * __bfq_bfqq_recalc_budget - try to adapt the budget to the @bfqq behavior.
2772 * @bfqd: device data.
2773 * @bfqq: queue to update.
2774 * @reason: reason for expiration.
2775 *
2776 * Handle the feedback on @bfqq budget at queue expiration.
2777 * See the body for detailed comments.
2778 */
2779static void __bfq_bfqq_recalc_budget(struct bfq_data *bfqd,
2780 struct bfq_queue *bfqq,
2781 enum bfqq_expiration reason)
2782{
2783 struct request *next_rq;
2784 int budget, min_budget;
2785
Paolo Valenteaee69d72017-04-19 08:29:02 -06002786 min_budget = bfq_min_budget(bfqd);
2787
Paolo Valente44e44a12017-04-12 18:23:12 +02002788 if (bfqq->wr_coeff == 1)
2789 budget = bfqq->max_budget;
2790 else /*
2791 * Use a constant, low budget for weight-raised queues,
2792 * to help achieve a low latency. Keep it slightly higher
2793 * than the minimum possible budget, to cause a little
2794 * bit fewer expirations.
2795 */
2796 budget = 2 * min_budget;
2797
Paolo Valenteaee69d72017-04-19 08:29:02 -06002798 bfq_log_bfqq(bfqd, bfqq, "recalc_budg: last budg %d, budg left %d",
2799 bfqq->entity.budget, bfq_bfqq_budget_left(bfqq));
2800 bfq_log_bfqq(bfqd, bfqq, "recalc_budg: last max_budg %d, min budg %d",
2801 budget, bfq_min_budget(bfqd));
2802 bfq_log_bfqq(bfqd, bfqq, "recalc_budg: sync %d, seeky %d",
2803 bfq_bfqq_sync(bfqq), BFQQ_SEEKY(bfqd->in_service_queue));
2804
Paolo Valente44e44a12017-04-12 18:23:12 +02002805 if (bfq_bfqq_sync(bfqq) && bfqq->wr_coeff == 1) {
Paolo Valenteaee69d72017-04-19 08:29:02 -06002806 switch (reason) {
2807 /*
2808 * Caveat: in all the following cases we trade latency
2809 * for throughput.
2810 */
2811 case BFQQE_TOO_IDLE:
Paolo Valente54b60452017-04-12 18:23:09 +02002812 /*
2813 * This is the only case where we may reduce
2814 * the budget: if there is no request of the
2815 * process still waiting for completion, then
2816 * we assume (tentatively) that the timer has
2817 * expired because the batch of requests of
2818 * the process could have been served with a
2819 * smaller budget. Hence, betting that
2820 * process will behave in the same way when it
2821 * becomes backlogged again, we reduce its
2822 * next budget. As long as we guess right,
2823 * this budget cut reduces the latency
2824 * experienced by the process.
2825 *
2826 * However, if there are still outstanding
2827 * requests, then the process may have not yet
2828 * issued its next request just because it is
2829 * still waiting for the completion of some of
2830 * the still outstanding ones. So in this
2831 * subcase we do not reduce its budget, on the
2832 * contrary we increase it to possibly boost
2833 * the throughput, as discussed in the
2834 * comments to the BUDGET_TIMEOUT case.
2835 */
2836 if (bfqq->dispatched > 0) /* still outstanding reqs */
2837 budget = min(budget * 2, bfqd->bfq_max_budget);
2838 else {
2839 if (budget > 5 * min_budget)
2840 budget -= 4 * min_budget;
2841 else
2842 budget = min_budget;
2843 }
Paolo Valenteaee69d72017-04-19 08:29:02 -06002844 break;
2845 case BFQQE_BUDGET_TIMEOUT:
Paolo Valente54b60452017-04-12 18:23:09 +02002846 /*
2847 * We double the budget here because it gives
2848 * the chance to boost the throughput if this
2849 * is not a seeky process (and has bumped into
2850 * this timeout because of, e.g., ZBR).
2851 */
2852 budget = min(budget * 2, bfqd->bfq_max_budget);
Paolo Valenteaee69d72017-04-19 08:29:02 -06002853 break;
2854 case BFQQE_BUDGET_EXHAUSTED:
2855 /*
2856 * The process still has backlog, and did not
2857 * let either the budget timeout or the disk
2858 * idling timeout expire. Hence it is not
2859 * seeky, has a short thinktime and may be
2860 * happy with a higher budget too. So
2861 * definitely increase the budget of this good
2862 * candidate to boost the disk throughput.
2863 */
Paolo Valente54b60452017-04-12 18:23:09 +02002864 budget = min(budget * 4, bfqd->bfq_max_budget);
Paolo Valenteaee69d72017-04-19 08:29:02 -06002865 break;
2866 case BFQQE_NO_MORE_REQUESTS:
2867 /*
2868 * For queues that expire for this reason, it
2869 * is particularly important to keep the
2870 * budget close to the actual service they
2871 * need. Doing so reduces the timestamp
2872 * misalignment problem described in the
2873 * comments in the body of
2874 * __bfq_activate_entity. In fact, suppose
2875 * that a queue systematically expires for
2876 * BFQQE_NO_MORE_REQUESTS and presents a
2877 * new request in time to enjoy timestamp
2878 * back-shifting. The larger the budget of the
2879 * queue is with respect to the service the
2880 * queue actually requests in each service
2881 * slot, the more times the queue can be
2882 * reactivated with the same virtual finish
2883 * time. It follows that, even if this finish
2884 * time is pushed to the system virtual time
2885 * to reduce the consequent timestamp
2886 * misalignment, the queue unjustly enjoys for
2887 * many re-activations a lower finish time
2888 * than all newly activated queues.
2889 *
2890 * The service needed by bfqq is measured
2891 * quite precisely by bfqq->entity.service.
2892 * Since bfqq does not enjoy device idling,
2893 * bfqq->entity.service is equal to the number
2894 * of sectors that the process associated with
2895 * bfqq requested to read/write before waiting
2896 * for request completions, or blocking for
2897 * other reasons.
2898 */
2899 budget = max_t(int, bfqq->entity.service, min_budget);
2900 break;
2901 default:
2902 return;
2903 }
Paolo Valente44e44a12017-04-12 18:23:12 +02002904 } else if (!bfq_bfqq_sync(bfqq)) {
Paolo Valenteaee69d72017-04-19 08:29:02 -06002905 /*
2906 * Async queues get always the maximum possible
2907 * budget, as for them we do not care about latency
2908 * (in addition, their ability to dispatch is limited
2909 * by the charging factor).
2910 */
2911 budget = bfqd->bfq_max_budget;
2912 }
2913
2914 bfqq->max_budget = budget;
2915
2916 if (bfqd->budgets_assigned >= bfq_stats_min_budgets &&
2917 !bfqd->bfq_user_max_budget)
2918 bfqq->max_budget = min(bfqq->max_budget, bfqd->bfq_max_budget);
2919
2920 /*
2921 * If there is still backlog, then assign a new budget, making
2922 * sure that it is large enough for the next request. Since
2923 * the finish time of bfqq must be kept in sync with the
2924 * budget, be sure to call __bfq_bfqq_expire() *after* this
2925 * update.
2926 *
2927 * If there is no backlog, then no need to update the budget;
2928 * it will be updated on the arrival of a new request.
2929 */
2930 next_rq = bfqq->next_rq;
2931 if (next_rq)
2932 bfqq->entity.budget = max_t(unsigned long, bfqq->max_budget,
2933 bfq_serv_to_charge(next_rq, bfqq));
2934
2935 bfq_log_bfqq(bfqd, bfqq, "head sect: %u, new budget %d",
2936 next_rq ? blk_rq_sectors(next_rq) : 0,
2937 bfqq->entity.budget);
2938}
2939
Paolo Valenteaee69d72017-04-19 08:29:02 -06002940/*
Paolo Valenteab0e43e2017-04-12 18:23:10 +02002941 * Return true if the process associated with bfqq is "slow". The slow
2942 * flag is used, in addition to the budget timeout, to reduce the
2943 * amount of service provided to seeky processes, and thus reduce
2944 * their chances to lower the throughput. More details in the comments
2945 * on the function bfq_bfqq_expire().
2946 *
2947 * An important observation is in order: as discussed in the comments
2948 * on the function bfq_update_peak_rate(), with devices with internal
2949 * queues, it is hard if ever possible to know when and for how long
2950 * an I/O request is processed by the device (apart from the trivial
2951 * I/O pattern where a new request is dispatched only after the
2952 * previous one has been completed). This makes it hard to evaluate
2953 * the real rate at which the I/O requests of each bfq_queue are
2954 * served. In fact, for an I/O scheduler like BFQ, serving a
2955 * bfq_queue means just dispatching its requests during its service
2956 * slot (i.e., until the budget of the queue is exhausted, or the
2957 * queue remains idle, or, finally, a timeout fires). But, during the
2958 * service slot of a bfq_queue, around 100 ms at most, the device may
2959 * be even still processing requests of bfq_queues served in previous
2960 * service slots. On the opposite end, the requests of the in-service
2961 * bfq_queue may be completed after the service slot of the queue
2962 * finishes.
2963 *
2964 * Anyway, unless more sophisticated solutions are used
2965 * (where possible), the sum of the sizes of the requests dispatched
2966 * during the service slot of a bfq_queue is probably the only
2967 * approximation available for the service received by the bfq_queue
2968 * during its service slot. And this sum is the quantity used in this
2969 * function to evaluate the I/O speed of a process.
Paolo Valenteaee69d72017-04-19 08:29:02 -06002970 */
Paolo Valenteab0e43e2017-04-12 18:23:10 +02002971static bool bfq_bfqq_is_slow(struct bfq_data *bfqd, struct bfq_queue *bfqq,
2972 bool compensate, enum bfqq_expiration reason,
2973 unsigned long *delta_ms)
Paolo Valenteaee69d72017-04-19 08:29:02 -06002974{
Paolo Valenteab0e43e2017-04-12 18:23:10 +02002975 ktime_t delta_ktime;
2976 u32 delta_usecs;
2977 bool slow = BFQQ_SEEKY(bfqq); /* if delta too short, use seekyness */
Paolo Valenteaee69d72017-04-19 08:29:02 -06002978
Paolo Valenteab0e43e2017-04-12 18:23:10 +02002979 if (!bfq_bfqq_sync(bfqq))
Paolo Valenteaee69d72017-04-19 08:29:02 -06002980 return false;
2981
2982 if (compensate)
Paolo Valenteab0e43e2017-04-12 18:23:10 +02002983 delta_ktime = bfqd->last_idling_start;
Paolo Valenteaee69d72017-04-19 08:29:02 -06002984 else
Paolo Valenteab0e43e2017-04-12 18:23:10 +02002985 delta_ktime = ktime_get();
2986 delta_ktime = ktime_sub(delta_ktime, bfqd->last_budget_start);
2987 delta_usecs = ktime_to_us(delta_ktime);
Paolo Valenteaee69d72017-04-19 08:29:02 -06002988
2989 /* don't use too short time intervals */
Paolo Valenteab0e43e2017-04-12 18:23:10 +02002990 if (delta_usecs < 1000) {
2991 if (blk_queue_nonrot(bfqd->queue))
2992 /*
2993 * give same worst-case guarantees as idling
2994 * for seeky
2995 */
2996 *delta_ms = BFQ_MIN_TT / NSEC_PER_MSEC;
2997 else /* charge at least one seek */
2998 *delta_ms = bfq_slice_idle / NSEC_PER_MSEC;
Paolo Valenteaee69d72017-04-19 08:29:02 -06002999
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003000 return slow;
Paolo Valenteaee69d72017-04-19 08:29:02 -06003001 }
3002
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003003 *delta_ms = delta_usecs / USEC_PER_MSEC;
Paolo Valenteaee69d72017-04-19 08:29:02 -06003004
3005 /*
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003006 * Use only long (> 20ms) intervals to filter out excessive
3007 * spikes in service rate estimation.
Paolo Valenteaee69d72017-04-19 08:29:02 -06003008 */
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003009 if (delta_usecs > 20000) {
3010 /*
3011 * Caveat for rotational devices: processes doing I/O
3012 * in the slower disk zones tend to be slow(er) even
3013 * if not seeky. In this respect, the estimated peak
3014 * rate is likely to be an average over the disk
3015 * surface. Accordingly, to not be too harsh with
3016 * unlucky processes, a process is deemed slow only if
3017 * its rate has been lower than half of the estimated
3018 * peak rate.
3019 */
3020 slow = bfqq->entity.service < bfqd->bfq_max_budget / 2;
3021 }
3022
3023 bfq_log_bfqq(bfqd, bfqq, "bfq_bfqq_is_slow: slow %d", slow);
3024
3025 return slow;
Paolo Valenteaee69d72017-04-19 08:29:02 -06003026}
3027
3028/*
Paolo Valente77b7dce2017-04-12 18:23:13 +02003029 * To be deemed as soft real-time, an application must meet two
3030 * requirements. First, the application must not require an average
3031 * bandwidth higher than the approximate bandwidth required to playback or
3032 * record a compressed high-definition video.
3033 * The next function is invoked on the completion of the last request of a
3034 * batch, to compute the next-start time instant, soft_rt_next_start, such
3035 * that, if the next request of the application does not arrive before
3036 * soft_rt_next_start, then the above requirement on the bandwidth is met.
3037 *
3038 * The second requirement is that the request pattern of the application is
3039 * isochronous, i.e., that, after issuing a request or a batch of requests,
3040 * the application stops issuing new requests until all its pending requests
3041 * have been completed. After that, the application may issue a new batch,
3042 * and so on.
3043 * For this reason the next function is invoked to compute
3044 * soft_rt_next_start only for applications that meet this requirement,
3045 * whereas soft_rt_next_start is set to infinity for applications that do
3046 * not.
3047 *
Paolo Valentea34b0242017-12-15 07:23:12 +01003048 * Unfortunately, even a greedy (i.e., I/O-bound) application may
3049 * happen to meet, occasionally or systematically, both the above
3050 * bandwidth and isochrony requirements. This may happen at least in
3051 * the following circumstances. First, if the CPU load is high. The
3052 * application may stop issuing requests while the CPUs are busy
3053 * serving other processes, then restart, then stop again for a while,
3054 * and so on. The other circumstances are related to the storage
3055 * device: the storage device is highly loaded or reaches a low-enough
3056 * throughput with the I/O of the application (e.g., because the I/O
3057 * is random and/or the device is slow). In all these cases, the
3058 * I/O of the application may be simply slowed down enough to meet
3059 * the bandwidth and isochrony requirements. To reduce the probability
3060 * that greedy applications are deemed as soft real-time in these
3061 * corner cases, a further rule is used in the computation of
3062 * soft_rt_next_start: the return value of this function is forced to
3063 * be higher than the maximum between the following two quantities.
Paolo Valente77b7dce2017-04-12 18:23:13 +02003064 *
Paolo Valentea34b0242017-12-15 07:23:12 +01003065 * (a) Current time plus: (1) the maximum time for which the arrival
3066 * of a request is waited for when a sync queue becomes idle,
3067 * namely bfqd->bfq_slice_idle, and (2) a few extra jiffies. We
3068 * postpone for a moment the reason for adding a few extra
3069 * jiffies; we get back to it after next item (b). Lower-bounding
3070 * the return value of this function with the current time plus
3071 * bfqd->bfq_slice_idle tends to filter out greedy applications,
3072 * because the latter issue their next request as soon as possible
3073 * after the last one has been completed. In contrast, a soft
3074 * real-time application spends some time processing data, after a
3075 * batch of its requests has been completed.
3076 *
3077 * (b) Current value of bfqq->soft_rt_next_start. As pointed out
3078 * above, greedy applications may happen to meet both the
3079 * bandwidth and isochrony requirements under heavy CPU or
3080 * storage-device load. In more detail, in these scenarios, these
3081 * applications happen, only for limited time periods, to do I/O
3082 * slowly enough to meet all the requirements described so far,
3083 * including the filtering in above item (a). These slow-speed
3084 * time intervals are usually interspersed between other time
3085 * intervals during which these applications do I/O at a very high
3086 * speed. Fortunately, exactly because of the high speed of the
3087 * I/O in the high-speed intervals, the values returned by this
3088 * function happen to be so high, near the end of any such
3089 * high-speed interval, to be likely to fall *after* the end of
3090 * the low-speed time interval that follows. These high values are
3091 * stored in bfqq->soft_rt_next_start after each invocation of
3092 * this function. As a consequence, if the last value of
3093 * bfqq->soft_rt_next_start is constantly used to lower-bound the
3094 * next value that this function may return, then, from the very
3095 * beginning of a low-speed interval, bfqq->soft_rt_next_start is
3096 * likely to be constantly kept so high that any I/O request
3097 * issued during the low-speed interval is considered as arriving
3098 * to soon for the application to be deemed as soft
3099 * real-time. Then, in the high-speed interval that follows, the
3100 * application will not be deemed as soft real-time, just because
3101 * it will do I/O at a high speed. And so on.
3102 *
3103 * Getting back to the filtering in item (a), in the following two
3104 * cases this filtering might be easily passed by a greedy
3105 * application, if the reference quantity was just
3106 * bfqd->bfq_slice_idle:
3107 * 1) HZ is so low that the duration of a jiffy is comparable to or
3108 * higher than bfqd->bfq_slice_idle. This happens, e.g., on slow
3109 * devices with HZ=100. The time granularity may be so coarse
3110 * that the approximation, in jiffies, of bfqd->bfq_slice_idle
3111 * is rather lower than the exact value.
Paolo Valente77b7dce2017-04-12 18:23:13 +02003112 * 2) jiffies, instead of increasing at a constant rate, may stop increasing
3113 * for a while, then suddenly 'jump' by several units to recover the lost
3114 * increments. This seems to happen, e.g., inside virtual machines.
Paolo Valentea34b0242017-12-15 07:23:12 +01003115 * To address this issue, in the filtering in (a) we do not use as a
3116 * reference time interval just bfqd->bfq_slice_idle, but
3117 * bfqd->bfq_slice_idle plus a few jiffies. In particular, we add the
3118 * minimum number of jiffies for which the filter seems to be quite
3119 * precise also in embedded systems and KVM/QEMU virtual machines.
Paolo Valente77b7dce2017-04-12 18:23:13 +02003120 */
3121static unsigned long bfq_bfqq_softrt_next_start(struct bfq_data *bfqd,
3122 struct bfq_queue *bfqq)
3123{
Paolo Valentea34b0242017-12-15 07:23:12 +01003124 return max3(bfqq->soft_rt_next_start,
3125 bfqq->last_idle_bklogged +
3126 HZ * bfqq->service_from_backlogged /
3127 bfqd->bfq_wr_max_softrt_rate,
3128 jiffies + nsecs_to_jiffies(bfqq->bfqd->bfq_slice_idle) + 4);
Paolo Valente77b7dce2017-04-12 18:23:13 +02003129}
3130
Paolo Valenteaee69d72017-04-19 08:29:02 -06003131/**
3132 * bfq_bfqq_expire - expire a queue.
3133 * @bfqd: device owning the queue.
3134 * @bfqq: the queue to expire.
3135 * @compensate: if true, compensate for the time spent idling.
3136 * @reason: the reason causing the expiration.
3137 *
Paolo Valentec074170e2017-04-12 18:23:11 +02003138 * If the process associated with bfqq does slow I/O (e.g., because it
3139 * issues random requests), we charge bfqq with the time it has been
3140 * in service instead of the service it has received (see
3141 * bfq_bfqq_charge_time for details on how this goal is achieved). As
3142 * a consequence, bfqq will typically get higher timestamps upon
3143 * reactivation, and hence it will be rescheduled as if it had
3144 * received more service than what it has actually received. In the
3145 * end, bfqq receives less service in proportion to how slowly its
3146 * associated process consumes its budgets (and hence how seriously it
3147 * tends to lower the throughput). In addition, this time-charging
3148 * strategy guarantees time fairness among slow processes. In
3149 * contrast, if the process associated with bfqq is not slow, we
3150 * charge bfqq exactly with the service it has received.
Paolo Valenteaee69d72017-04-19 08:29:02 -06003151 *
Paolo Valentec074170e2017-04-12 18:23:11 +02003152 * Charging time to the first type of queues and the exact service to
3153 * the other has the effect of using the WF2Q+ policy to schedule the
3154 * former on a timeslice basis, without violating service domain
3155 * guarantees among the latter.
Paolo Valenteaee69d72017-04-19 08:29:02 -06003156 */
Paolo Valenteea25da42017-04-19 08:48:24 -06003157void bfq_bfqq_expire(struct bfq_data *bfqd,
3158 struct bfq_queue *bfqq,
3159 bool compensate,
3160 enum bfqq_expiration reason)
Paolo Valenteaee69d72017-04-19 08:29:02 -06003161{
3162 bool slow;
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003163 unsigned long delta = 0;
3164 struct bfq_entity *entity = &bfqq->entity;
Paolo Valenteaee69d72017-04-19 08:29:02 -06003165 int ref;
3166
3167 /*
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003168 * Check whether the process is slow (see bfq_bfqq_is_slow).
Paolo Valenteaee69d72017-04-19 08:29:02 -06003169 */
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003170 slow = bfq_bfqq_is_slow(bfqd, bfqq, compensate, reason, &delta);
Paolo Valenteaee69d72017-04-19 08:29:02 -06003171
3172 /*
Paolo Valentec074170e2017-04-12 18:23:11 +02003173 * As above explained, charge slow (typically seeky) and
3174 * timed-out queues with the time and not the service
3175 * received, to favor sequential workloads.
3176 *
3177 * Processes doing I/O in the slower disk zones will tend to
3178 * be slow(er) even if not seeky. Therefore, since the
3179 * estimated peak rate is actually an average over the disk
3180 * surface, these processes may timeout just for bad luck. To
3181 * avoid punishing them, do not charge time to processes that
3182 * succeeded in consuming at least 2/3 of their budget. This
3183 * allows BFQ to preserve enough elasticity to still perform
3184 * bandwidth, and not time, distribution with little unlucky
3185 * or quasi-sequential processes.
Paolo Valenteaee69d72017-04-19 08:29:02 -06003186 */
Paolo Valente44e44a12017-04-12 18:23:12 +02003187 if (bfqq->wr_coeff == 1 &&
3188 (slow ||
3189 (reason == BFQQE_BUDGET_TIMEOUT &&
3190 bfq_bfqq_budget_left(bfqq) >= entity->budget / 3)))
Paolo Valentec074170e2017-04-12 18:23:11 +02003191 bfq_bfqq_charge_time(bfqd, bfqq, delta);
Paolo Valenteaee69d72017-04-19 08:29:02 -06003192
3193 if (reason == BFQQE_TOO_IDLE &&
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003194 entity->service <= 2 * entity->budget / 10)
Paolo Valenteaee69d72017-04-19 08:29:02 -06003195 bfq_clear_bfqq_IO_bound(bfqq);
3196
Paolo Valente44e44a12017-04-12 18:23:12 +02003197 if (bfqd->low_latency && bfqq->wr_coeff == 1)
3198 bfqq->last_wr_start_finish = jiffies;
3199
Paolo Valente77b7dce2017-04-12 18:23:13 +02003200 if (bfqd->low_latency && bfqd->bfq_wr_max_softrt_rate > 0 &&
3201 RB_EMPTY_ROOT(&bfqq->sort_list)) {
3202 /*
3203 * If we get here, and there are no outstanding
3204 * requests, then the request pattern is isochronous
3205 * (see the comments on the function
3206 * bfq_bfqq_softrt_next_start()). Thus we can compute
3207 * soft_rt_next_start. If, instead, the queue still
3208 * has outstanding requests, then we have to wait for
3209 * the completion of all the outstanding requests to
3210 * discover whether the request pattern is actually
3211 * isochronous.
3212 */
3213 if (bfqq->dispatched == 0)
3214 bfqq->soft_rt_next_start =
3215 bfq_bfqq_softrt_next_start(bfqd, bfqq);
3216 else {
3217 /*
3218 * The application is still waiting for the
3219 * completion of one or more requests:
3220 * prevent it from possibly being incorrectly
3221 * deemed as soft real-time by setting its
3222 * soft_rt_next_start to infinity. In fact,
3223 * without this assignment, the application
3224 * would be incorrectly deemed as soft
3225 * real-time if:
3226 * 1) it issued a new request before the
3227 * completion of all its in-flight
3228 * requests, and
3229 * 2) at that time, its soft_rt_next_start
3230 * happened to be in the past.
3231 */
3232 bfqq->soft_rt_next_start =
3233 bfq_greatest_from_now();
3234 /*
3235 * Schedule an update of soft_rt_next_start to when
3236 * the task may be discovered to be isochronous.
3237 */
3238 bfq_mark_bfqq_softrt_update(bfqq);
3239 }
3240 }
3241
Paolo Valenteaee69d72017-04-19 08:29:02 -06003242 bfq_log_bfqq(bfqd, bfqq,
Paolo Valented5be3fe2017-08-04 07:35:10 +02003243 "expire (%d, slow %d, num_disp %d, short_ttime %d)", reason,
3244 slow, bfqq->dispatched, bfq_bfqq_has_short_ttime(bfqq));
Paolo Valenteaee69d72017-04-19 08:29:02 -06003245
3246 /*
3247 * Increase, decrease or leave budget unchanged according to
3248 * reason.
3249 */
3250 __bfq_bfqq_recalc_budget(bfqd, bfqq, reason);
3251 ref = bfqq->ref;
3252 __bfq_bfqq_expire(bfqd, bfqq);
3253
3254 /* mark bfqq as waiting a request only if a bic still points to it */
3255 if (ref > 1 && !bfq_bfqq_busy(bfqq) &&
3256 reason != BFQQE_BUDGET_TIMEOUT &&
3257 reason != BFQQE_BUDGET_EXHAUSTED)
3258 bfq_mark_bfqq_non_blocking_wait_rq(bfqq);
3259}
3260
3261/*
3262 * Budget timeout is not implemented through a dedicated timer, but
3263 * just checked on request arrivals and completions, as well as on
3264 * idle timer expirations.
3265 */
3266static bool bfq_bfqq_budget_timeout(struct bfq_queue *bfqq)
3267{
Paolo Valente44e44a12017-04-12 18:23:12 +02003268 return time_is_before_eq_jiffies(bfqq->budget_timeout);
Paolo Valenteaee69d72017-04-19 08:29:02 -06003269}
3270
3271/*
3272 * If we expire a queue that is actively waiting (i.e., with the
3273 * device idled) for the arrival of a new request, then we may incur
3274 * the timestamp misalignment problem described in the body of the
3275 * function __bfq_activate_entity. Hence we return true only if this
3276 * condition does not hold, or if the queue is slow enough to deserve
3277 * only to be kicked off for preserving a high throughput.
3278 */
3279static bool bfq_may_expire_for_budg_timeout(struct bfq_queue *bfqq)
3280{
3281 bfq_log_bfqq(bfqq->bfqd, bfqq,
3282 "may_budget_timeout: wait_request %d left %d timeout %d",
3283 bfq_bfqq_wait_request(bfqq),
3284 bfq_bfqq_budget_left(bfqq) >= bfqq->entity.budget / 3,
3285 bfq_bfqq_budget_timeout(bfqq));
3286
3287 return (!bfq_bfqq_wait_request(bfqq) ||
3288 bfq_bfqq_budget_left(bfqq) >= bfqq->entity.budget / 3)
3289 &&
3290 bfq_bfqq_budget_timeout(bfqq);
3291}
3292
3293/*
3294 * For a queue that becomes empty, device idling is allowed only if
Paolo Valente44e44a12017-04-12 18:23:12 +02003295 * this function returns true for the queue. As a consequence, since
3296 * device idling plays a critical role in both throughput boosting and
3297 * service guarantees, the return value of this function plays a
3298 * critical role in both these aspects as well.
3299 *
3300 * In a nutshell, this function returns true only if idling is
3301 * beneficial for throughput or, even if detrimental for throughput,
3302 * idling is however necessary to preserve service guarantees (low
3303 * latency, desired throughput distribution, ...). In particular, on
3304 * NCQ-capable devices, this function tries to return false, so as to
3305 * help keep the drives' internal queues full, whenever this helps the
3306 * device boost the throughput without causing any service-guarantee
3307 * issue.
3308 *
3309 * In more detail, the return value of this function is obtained by,
3310 * first, computing a number of boolean variables that take into
3311 * account throughput and service-guarantee issues, and, then,
3312 * combining these variables in a logical expression. Most of the
3313 * issues taken into account are not trivial. We discuss these issues
3314 * individually while introducing the variables.
Paolo Valenteaee69d72017-04-19 08:29:02 -06003315 */
3316static bool bfq_bfqq_may_idle(struct bfq_queue *bfqq)
3317{
3318 struct bfq_data *bfqd = bfqq->bfqd;
Paolo Valenteedaf9422017-08-04 07:35:11 +02003319 bool rot_without_queueing =
3320 !blk_queue_nonrot(bfqd->queue) && !bfqd->hw_tag,
3321 bfqq_sequential_and_IO_bound,
3322 idling_boosts_thr, idling_boosts_thr_without_issues,
Arianna Avanzinie1b23242017-04-12 18:23:20 +02003323 idling_needed_for_service_guarantees,
Paolo Valentecfd69712017-04-12 18:23:15 +02003324 asymmetric_scenario;
Paolo Valenteaee69d72017-04-19 08:29:02 -06003325
3326 if (bfqd->strict_guarantees)
3327 return true;
3328
3329 /*
Paolo Valented5be3fe2017-08-04 07:35:10 +02003330 * Idling is performed only if slice_idle > 0. In addition, we
3331 * do not idle if
3332 * (a) bfqq is async
3333 * (b) bfqq is in the idle io prio class: in this case we do
3334 * not idle because we want to minimize the bandwidth that
3335 * queues in this class can steal to higher-priority queues
3336 */
3337 if (bfqd->bfq_slice_idle == 0 || !bfq_bfqq_sync(bfqq) ||
3338 bfq_class_idle(bfqq))
3339 return false;
3340
Paolo Valenteedaf9422017-08-04 07:35:11 +02003341 bfqq_sequential_and_IO_bound = !BFQQ_SEEKY(bfqq) &&
3342 bfq_bfqq_IO_bound(bfqq) && bfq_bfqq_has_short_ttime(bfqq);
3343
Paolo Valented5be3fe2017-08-04 07:35:10 +02003344 /*
Paolo Valente44e44a12017-04-12 18:23:12 +02003345 * The next variable takes into account the cases where idling
3346 * boosts the throughput.
3347 *
Paolo Valentee01eff02017-04-12 18:23:19 +02003348 * The value of the variable is computed considering, first, that
3349 * idling is virtually always beneficial for the throughput if:
Paolo Valenteedaf9422017-08-04 07:35:11 +02003350 * (a) the device is not NCQ-capable and rotational, or
3351 * (b) regardless of the presence of NCQ, the device is rotational and
3352 * the request pattern for bfqq is I/O-bound and sequential, or
3353 * (c) regardless of whether it is rotational, the device is
3354 * not NCQ-capable and the request pattern for bfqq is
3355 * I/O-bound and sequential.
Paolo Valentebf2b79e2017-04-12 18:23:18 +02003356 *
3357 * Secondly, and in contrast to the above item (b), idling an
3358 * NCQ-capable flash-based device would not boost the
Paolo Valentee01eff02017-04-12 18:23:19 +02003359 * throughput even with sequential I/O; rather it would lower
Paolo Valentebf2b79e2017-04-12 18:23:18 +02003360 * the throughput in proportion to how fast the device
3361 * is. Accordingly, the next variable is true if any of the
Paolo Valenteedaf9422017-08-04 07:35:11 +02003362 * above conditions (a), (b) or (c) is true, and, in
3363 * particular, happens to be false if bfqd is an NCQ-capable
3364 * flash-based device.
Paolo Valenteaee69d72017-04-19 08:29:02 -06003365 */
Paolo Valenteedaf9422017-08-04 07:35:11 +02003366 idling_boosts_thr = rot_without_queueing ||
3367 ((!blk_queue_nonrot(bfqd->queue) || !bfqd->hw_tag) &&
3368 bfqq_sequential_and_IO_bound);
Paolo Valenteaee69d72017-04-19 08:29:02 -06003369
3370 /*
Paolo Valentecfd69712017-04-12 18:23:15 +02003371 * The value of the next variable,
3372 * idling_boosts_thr_without_issues, is equal to that of
3373 * idling_boosts_thr, unless a special case holds. In this
3374 * special case, described below, idling may cause problems to
3375 * weight-raised queues.
3376 *
3377 * When the request pool is saturated (e.g., in the presence
3378 * of write hogs), if the processes associated with
3379 * non-weight-raised queues ask for requests at a lower rate,
3380 * then processes associated with weight-raised queues have a
3381 * higher probability to get a request from the pool
3382 * immediately (or at least soon) when they need one. Thus
3383 * they have a higher probability to actually get a fraction
3384 * of the device throughput proportional to their high
3385 * weight. This is especially true with NCQ-capable drives,
3386 * which enqueue several requests in advance, and further
3387 * reorder internally-queued requests.
3388 *
3389 * For this reason, we force to false the value of
3390 * idling_boosts_thr_without_issues if there are weight-raised
3391 * busy queues. In this case, and if bfqq is not weight-raised,
3392 * this guarantees that the device is not idled for bfqq (if,
3393 * instead, bfqq is weight-raised, then idling will be
3394 * guaranteed by another variable, see below). Combined with
3395 * the timestamping rules of BFQ (see [1] for details), this
3396 * behavior causes bfqq, and hence any sync non-weight-raised
3397 * queue, to get a lower number of requests served, and thus
3398 * to ask for a lower number of requests from the request
3399 * pool, before the busy weight-raised queues get served
3400 * again. This often mitigates starvation problems in the
3401 * presence of heavy write workloads and NCQ, thereby
3402 * guaranteeing a higher application and system responsiveness
3403 * in these hostile scenarios.
3404 */
3405 idling_boosts_thr_without_issues = idling_boosts_thr &&
3406 bfqd->wr_busy_queues == 0;
3407
3408 /*
Paolo Valentebf2b79e2017-04-12 18:23:18 +02003409 * There is then a case where idling must be performed not
3410 * for throughput concerns, but to preserve service
3411 * guarantees.
3412 *
3413 * To introduce this case, we can note that allowing the drive
3414 * to enqueue more than one request at a time, and hence
Paolo Valente44e44a12017-04-12 18:23:12 +02003415 * delegating de facto final scheduling decisions to the
Paolo Valentebf2b79e2017-04-12 18:23:18 +02003416 * drive's internal scheduler, entails loss of control on the
Paolo Valente44e44a12017-04-12 18:23:12 +02003417 * actual request service order. In particular, the critical
Paolo Valentebf2b79e2017-04-12 18:23:18 +02003418 * situation is when requests from different processes happen
Paolo Valente44e44a12017-04-12 18:23:12 +02003419 * to be present, at the same time, in the internal queue(s)
3420 * of the drive. In such a situation, the drive, by deciding
3421 * the service order of the internally-queued requests, does
3422 * determine also the actual throughput distribution among
3423 * these processes. But the drive typically has no notion or
3424 * concern about per-process throughput distribution, and
3425 * makes its decisions only on a per-request basis. Therefore,
3426 * the service distribution enforced by the drive's internal
3427 * scheduler is likely to coincide with the desired
3428 * device-throughput distribution only in a completely
Paolo Valentebf2b79e2017-04-12 18:23:18 +02003429 * symmetric scenario where:
3430 * (i) each of these processes must get the same throughput as
3431 * the others;
3432 * (ii) all these processes have the same I/O pattern
3433 (either sequential or random).
3434 * In fact, in such a scenario, the drive will tend to treat
3435 * the requests of each of these processes in about the same
3436 * way as the requests of the others, and thus to provide
3437 * each of these processes with about the same throughput
3438 * (which is exactly the desired throughput distribution). In
3439 * contrast, in any asymmetric scenario, device idling is
3440 * certainly needed to guarantee that bfqq receives its
3441 * assigned fraction of the device throughput (see [1] for
3442 * details).
Paolo Valente44e44a12017-04-12 18:23:12 +02003443 *
Paolo Valentebf2b79e2017-04-12 18:23:18 +02003444 * We address this issue by controlling, actually, only the
3445 * symmetry sub-condition (i), i.e., provided that
3446 * sub-condition (i) holds, idling is not performed,
3447 * regardless of whether sub-condition (ii) holds. In other
3448 * words, only if sub-condition (i) holds, then idling is
3449 * allowed, and the device tends to be prevented from queueing
3450 * many requests, possibly of several processes. The reason
3451 * for not controlling also sub-condition (ii) is that we
3452 * exploit preemption to preserve guarantees in case of
3453 * symmetric scenarios, even if (ii) does not hold, as
3454 * explained in the next two paragraphs.
Paolo Valente44e44a12017-04-12 18:23:12 +02003455 *
Paolo Valentebf2b79e2017-04-12 18:23:18 +02003456 * Even if a queue, say Q, is expired when it remains idle, Q
3457 * can still preempt the new in-service queue if the next
3458 * request of Q arrives soon (see the comments on
3459 * bfq_bfqq_update_budg_for_activation). If all queues and
3460 * groups have the same weight, this form of preemption,
3461 * combined with the hole-recovery heuristic described in the
3462 * comments on function bfq_bfqq_update_budg_for_activation,
3463 * are enough to preserve a correct bandwidth distribution in
3464 * the mid term, even without idling. In fact, even if not
3465 * idling allows the internal queues of the device to contain
3466 * many requests, and thus to reorder requests, we can rather
3467 * safely assume that the internal scheduler still preserves a
3468 * minimum of mid-term fairness. The motivation for using
3469 * preemption instead of idling is that, by not idling,
3470 * service guarantees are preserved without minimally
3471 * sacrificing throughput. In other words, both a high
3472 * throughput and its desired distribution are obtained.
3473 *
3474 * More precisely, this preemption-based, idleless approach
3475 * provides fairness in terms of IOPS, and not sectors per
3476 * second. This can be seen with a simple example. Suppose
3477 * that there are two queues with the same weight, but that
3478 * the first queue receives requests of 8 sectors, while the
3479 * second queue receives requests of 1024 sectors. In
3480 * addition, suppose that each of the two queues contains at
3481 * most one request at a time, which implies that each queue
3482 * always remains idle after it is served. Finally, after
3483 * remaining idle, each queue receives very quickly a new
3484 * request. It follows that the two queues are served
3485 * alternatively, preempting each other if needed. This
3486 * implies that, although both queues have the same weight,
3487 * the queue with large requests receives a service that is
3488 * 1024/8 times as high as the service received by the other
3489 * queue.
3490 *
3491 * On the other hand, device idling is performed, and thus
3492 * pure sector-domain guarantees are provided, for the
3493 * following queues, which are likely to need stronger
3494 * throughput guarantees: weight-raised queues, and queues
3495 * with a higher weight than other queues. When such queues
3496 * are active, sub-condition (i) is false, which triggers
3497 * device idling.
3498 *
3499 * According to the above considerations, the next variable is
3500 * true (only) if sub-condition (i) holds. To compute the
3501 * value of this variable, we not only use the return value of
3502 * the function bfq_symmetric_scenario(), but also check
3503 * whether bfqq is being weight-raised, because
3504 * bfq_symmetric_scenario() does not take into account also
3505 * weight-raised queues (see comments on
3506 * bfq_weights_tree_add()).
Paolo Valente44e44a12017-04-12 18:23:12 +02003507 *
3508 * As a side note, it is worth considering that the above
3509 * device-idling countermeasures may however fail in the
3510 * following unlucky scenario: if idling is (correctly)
Paolo Valentebf2b79e2017-04-12 18:23:18 +02003511 * disabled in a time period during which all symmetry
3512 * sub-conditions hold, and hence the device is allowed to
Paolo Valente44e44a12017-04-12 18:23:12 +02003513 * enqueue many requests, but at some later point in time some
3514 * sub-condition stops to hold, then it may become impossible
3515 * to let requests be served in the desired order until all
3516 * the requests already queued in the device have been served.
Paolo Valenteaee69d72017-04-19 08:29:02 -06003517 */
Paolo Valentebf2b79e2017-04-12 18:23:18 +02003518 asymmetric_scenario = bfqq->wr_coeff > 1 ||
3519 !bfq_symmetric_scenario(bfqd);
Paolo Valente44e44a12017-04-12 18:23:12 +02003520
3521 /*
Arianna Avanzinie1b23242017-04-12 18:23:20 +02003522 * Finally, there is a case where maximizing throughput is the
3523 * best choice even if it may cause unfairness toward
3524 * bfqq. Such a case is when bfqq became active in a burst of
3525 * queue activations. Queues that became active during a large
3526 * burst benefit only from throughput, as discussed in the
3527 * comments on bfq_handle_burst. Thus, if bfqq became active
3528 * in a burst and not idling the device maximizes throughput,
3529 * then the device must no be idled, because not idling the
3530 * device provides bfqq and all other queues in the burst with
3531 * maximum benefit. Combining this and the above case, we can
3532 * now establish when idling is actually needed to preserve
3533 * service guarantees.
3534 */
3535 idling_needed_for_service_guarantees =
3536 asymmetric_scenario && !bfq_bfqq_in_large_burst(bfqq);
3537
3538 /*
Paolo Valented5be3fe2017-08-04 07:35:10 +02003539 * We have now all the components we need to compute the
3540 * return value of the function, which is true only if idling
3541 * either boosts the throughput (without issues), or is
3542 * necessary to preserve service guarantees.
Paolo Valente44e44a12017-04-12 18:23:12 +02003543 */
Paolo Valented5be3fe2017-08-04 07:35:10 +02003544 return idling_boosts_thr_without_issues ||
3545 idling_needed_for_service_guarantees;
Paolo Valenteaee69d72017-04-19 08:29:02 -06003546}
3547
3548/*
3549 * If the in-service queue is empty but the function bfq_bfqq_may_idle
3550 * returns true, then:
3551 * 1) the queue must remain in service and cannot be expired, and
3552 * 2) the device must be idled to wait for the possible arrival of a new
3553 * request for the queue.
3554 * See the comments on the function bfq_bfqq_may_idle for the reasons
3555 * why performing device idling is the best choice to boost the throughput
3556 * and preserve service guarantees when bfq_bfqq_may_idle itself
3557 * returns true.
3558 */
3559static bool bfq_bfqq_must_idle(struct bfq_queue *bfqq)
3560{
Paolo Valented5be3fe2017-08-04 07:35:10 +02003561 return RB_EMPTY_ROOT(&bfqq->sort_list) && bfq_bfqq_may_idle(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06003562}
3563
3564/*
3565 * Select a queue for service. If we have a current queue in service,
3566 * check whether to continue servicing it, or retrieve and set a new one.
3567 */
3568static struct bfq_queue *bfq_select_queue(struct bfq_data *bfqd)
3569{
3570 struct bfq_queue *bfqq;
3571 struct request *next_rq;
3572 enum bfqq_expiration reason = BFQQE_BUDGET_TIMEOUT;
3573
3574 bfqq = bfqd->in_service_queue;
3575 if (!bfqq)
3576 goto new_queue;
3577
3578 bfq_log_bfqq(bfqd, bfqq, "select_queue: already in-service queue");
3579
3580 if (bfq_may_expire_for_budg_timeout(bfqq) &&
3581 !bfq_bfqq_wait_request(bfqq) &&
3582 !bfq_bfqq_must_idle(bfqq))
3583 goto expire;
3584
3585check_queue:
3586 /*
3587 * This loop is rarely executed more than once. Even when it
3588 * happens, it is much more convenient to re-execute this loop
3589 * than to return NULL and trigger a new dispatch to get a
3590 * request served.
3591 */
3592 next_rq = bfqq->next_rq;
3593 /*
3594 * If bfqq has requests queued and it has enough budget left to
3595 * serve them, keep the queue, otherwise expire it.
3596 */
3597 if (next_rq) {
3598 if (bfq_serv_to_charge(next_rq, bfqq) >
3599 bfq_bfqq_budget_left(bfqq)) {
3600 /*
3601 * Expire the queue for budget exhaustion,
3602 * which makes sure that the next budget is
3603 * enough to serve the next request, even if
3604 * it comes from the fifo expired path.
3605 */
3606 reason = BFQQE_BUDGET_EXHAUSTED;
3607 goto expire;
3608 } else {
3609 /*
3610 * The idle timer may be pending because we may
3611 * not disable disk idling even when a new request
3612 * arrives.
3613 */
3614 if (bfq_bfqq_wait_request(bfqq)) {
3615 /*
3616 * If we get here: 1) at least a new request
3617 * has arrived but we have not disabled the
3618 * timer because the request was too small,
3619 * 2) then the block layer has unplugged
3620 * the device, causing the dispatch to be
3621 * invoked.
3622 *
3623 * Since the device is unplugged, now the
3624 * requests are probably large enough to
3625 * provide a reasonable throughput.
3626 * So we disable idling.
3627 */
3628 bfq_clear_bfqq_wait_request(bfqq);
3629 hrtimer_try_to_cancel(&bfqd->idle_slice_timer);
3630 }
3631 goto keep_queue;
3632 }
3633 }
3634
3635 /*
3636 * No requests pending. However, if the in-service queue is idling
3637 * for a new request, or has requests waiting for a completion and
3638 * may idle after their completion, then keep it anyway.
3639 */
3640 if (bfq_bfqq_wait_request(bfqq) ||
3641 (bfqq->dispatched != 0 && bfq_bfqq_may_idle(bfqq))) {
3642 bfqq = NULL;
3643 goto keep_queue;
3644 }
3645
3646 reason = BFQQE_NO_MORE_REQUESTS;
3647expire:
3648 bfq_bfqq_expire(bfqd, bfqq, false, reason);
3649new_queue:
3650 bfqq = bfq_set_in_service_queue(bfqd);
3651 if (bfqq) {
3652 bfq_log_bfqq(bfqd, bfqq, "select_queue: checking new queue");
3653 goto check_queue;
3654 }
3655keep_queue:
3656 if (bfqq)
3657 bfq_log_bfqq(bfqd, bfqq, "select_queue: returned this queue");
3658 else
3659 bfq_log(bfqd, "select_queue: no queue returned");
3660
3661 return bfqq;
3662}
3663
Paolo Valente44e44a12017-04-12 18:23:12 +02003664static void bfq_update_wr_data(struct bfq_data *bfqd, struct bfq_queue *bfqq)
3665{
3666 struct bfq_entity *entity = &bfqq->entity;
3667
3668 if (bfqq->wr_coeff > 1) { /* queue is being weight-raised */
3669 bfq_log_bfqq(bfqd, bfqq,
3670 "raising period dur %u/%u msec, old coeff %u, w %d(%d)",
3671 jiffies_to_msecs(jiffies - bfqq->last_wr_start_finish),
3672 jiffies_to_msecs(bfqq->wr_cur_max_time),
3673 bfqq->wr_coeff,
3674 bfqq->entity.weight, bfqq->entity.orig_weight);
3675
3676 if (entity->prio_changed)
3677 bfq_log_bfqq(bfqd, bfqq, "WARN: pending prio change");
3678
3679 /*
Arianna Avanzinie1b23242017-04-12 18:23:20 +02003680 * If the queue was activated in a burst, or too much
3681 * time has elapsed from the beginning of this
3682 * weight-raising period, then end weight raising.
Paolo Valente44e44a12017-04-12 18:23:12 +02003683 */
Arianna Avanzinie1b23242017-04-12 18:23:20 +02003684 if (bfq_bfqq_in_large_burst(bfqq))
3685 bfq_bfqq_end_wr(bfqq);
3686 else if (time_is_before_jiffies(bfqq->last_wr_start_finish +
3687 bfqq->wr_cur_max_time)) {
Paolo Valente77b7dce2017-04-12 18:23:13 +02003688 if (bfqq->wr_cur_max_time != bfqd->bfq_wr_rt_max_time ||
3689 time_is_before_jiffies(bfqq->wr_start_at_switch_to_srt +
Arianna Avanzinie1b23242017-04-12 18:23:20 +02003690 bfq_wr_duration(bfqd)))
Paolo Valente77b7dce2017-04-12 18:23:13 +02003691 bfq_bfqq_end_wr(bfqq);
3692 else {
Paolo Valente3e2bdd62017-09-21 11:04:01 +02003693 switch_back_to_interactive_wr(bfqq, bfqd);
Paolo Valente77b7dce2017-04-12 18:23:13 +02003694 bfqq->entity.prio_changed = 1;
3695 }
Paolo Valente44e44a12017-04-12 18:23:12 +02003696 }
Paolo Valente8a8747d2018-01-13 12:05:18 +01003697 if (bfqq->wr_coeff > 1 &&
3698 bfqq->wr_cur_max_time != bfqd->bfq_wr_rt_max_time &&
3699 bfqq->service_from_wr > max_service_from_wr) {
3700 /* see comments on max_service_from_wr */
3701 bfq_bfqq_end_wr(bfqq);
3702 }
Paolo Valente44e44a12017-04-12 18:23:12 +02003703 }
Paolo Valente431b17f2017-07-03 10:00:10 +02003704 /*
3705 * To improve latency (for this or other queues), immediately
3706 * update weight both if it must be raised and if it must be
3707 * lowered. Since, entity may be on some active tree here, and
3708 * might have a pending change of its ioprio class, invoke
3709 * next function with the last parameter unset (see the
3710 * comments on the function).
3711 */
Paolo Valente44e44a12017-04-12 18:23:12 +02003712 if ((entity->weight > entity->orig_weight) != (bfqq->wr_coeff > 1))
Paolo Valente431b17f2017-07-03 10:00:10 +02003713 __bfq_entity_update_weight_prio(bfq_entity_service_tree(entity),
3714 entity, false);
Paolo Valente44e44a12017-04-12 18:23:12 +02003715}
3716
Paolo Valenteaee69d72017-04-19 08:29:02 -06003717/*
3718 * Dispatch next request from bfqq.
3719 */
3720static struct request *bfq_dispatch_rq_from_bfqq(struct bfq_data *bfqd,
3721 struct bfq_queue *bfqq)
3722{
3723 struct request *rq = bfqq->next_rq;
3724 unsigned long service_to_charge;
3725
3726 service_to_charge = bfq_serv_to_charge(rq, bfqq);
3727
3728 bfq_bfqq_served(bfqq, service_to_charge);
3729
3730 bfq_dispatch_remove(bfqd->queue, rq);
3731
Paolo Valente44e44a12017-04-12 18:23:12 +02003732 /*
3733 * If weight raising has to terminate for bfqq, then next
3734 * function causes an immediate update of bfqq's weight,
3735 * without waiting for next activation. As a consequence, on
3736 * expiration, bfqq will be timestamped as if has never been
3737 * weight-raised during this service slot, even if it has
3738 * received part or even most of the service as a
3739 * weight-raised queue. This inflates bfqq's timestamps, which
3740 * is beneficial, as bfqq is then more willing to leave the
3741 * device immediately to possible other weight-raised queues.
3742 */
3743 bfq_update_wr_data(bfqd, bfqq);
3744
Paolo Valenteaee69d72017-04-19 08:29:02 -06003745 /*
3746 * Expire bfqq, pretending that its budget expired, if bfqq
3747 * belongs to CLASS_IDLE and other queues are waiting for
3748 * service.
3749 */
3750 if (bfqd->busy_queues > 1 && bfq_class_idle(bfqq))
3751 goto expire;
3752
3753 return rq;
3754
3755expire:
3756 bfq_bfqq_expire(bfqd, bfqq, false, BFQQE_BUDGET_EXHAUSTED);
3757 return rq;
3758}
3759
3760static bool bfq_has_work(struct blk_mq_hw_ctx *hctx)
3761{
3762 struct bfq_data *bfqd = hctx->queue->elevator->elevator_data;
3763
3764 /*
3765 * Avoiding lock: a race on bfqd->busy_queues should cause at
3766 * most a call to dispatch for nothing
3767 */
3768 return !list_empty_careful(&bfqd->dispatch) ||
3769 bfqd->busy_queues > 0;
3770}
3771
3772static struct request *__bfq_dispatch_request(struct blk_mq_hw_ctx *hctx)
3773{
3774 struct bfq_data *bfqd = hctx->queue->elevator->elevator_data;
3775 struct request *rq = NULL;
3776 struct bfq_queue *bfqq = NULL;
3777
3778 if (!list_empty(&bfqd->dispatch)) {
3779 rq = list_first_entry(&bfqd->dispatch, struct request,
3780 queuelist);
3781 list_del_init(&rq->queuelist);
3782
3783 bfqq = RQ_BFQQ(rq);
3784
3785 if (bfqq) {
3786 /*
3787 * Increment counters here, because this
3788 * dispatch does not follow the standard
3789 * dispatch flow (where counters are
3790 * incremented)
3791 */
3792 bfqq->dispatched++;
3793
3794 goto inc_in_driver_start_rq;
3795 }
3796
3797 /*
Paolo Valentea7877392018-02-07 22:19:20 +01003798 * We exploit the bfq_finish_requeue_request hook to
3799 * decrement rq_in_driver, but
3800 * bfq_finish_requeue_request will not be invoked on
3801 * this request. So, to avoid unbalance, just start
3802 * this request, without incrementing rq_in_driver. As
3803 * a negative consequence, rq_in_driver is deceptively
3804 * lower than it should be while this request is in
3805 * service. This may cause bfq_schedule_dispatch to be
3806 * invoked uselessly.
Paolo Valenteaee69d72017-04-19 08:29:02 -06003807 *
3808 * As for implementing an exact solution, the
Paolo Valentea7877392018-02-07 22:19:20 +01003809 * bfq_finish_requeue_request hook, if defined, is
3810 * probably invoked also on this request. So, by
3811 * exploiting this hook, we could 1) increment
3812 * rq_in_driver here, and 2) decrement it in
3813 * bfq_finish_requeue_request. Such a solution would
3814 * let the value of the counter be always accurate,
3815 * but it would entail using an extra interface
3816 * function. This cost seems higher than the benefit,
3817 * being the frequency of non-elevator-private
Paolo Valenteaee69d72017-04-19 08:29:02 -06003818 * requests very low.
3819 */
3820 goto start_rq;
3821 }
3822
3823 bfq_log(bfqd, "dispatch requests: %d busy queues", bfqd->busy_queues);
3824
3825 if (bfqd->busy_queues == 0)
3826 goto exit;
3827
3828 /*
3829 * Force device to serve one request at a time if
3830 * strict_guarantees is true. Forcing this service scheme is
3831 * currently the ONLY way to guarantee that the request
3832 * service order enforced by the scheduler is respected by a
3833 * queueing device. Otherwise the device is free even to make
3834 * some unlucky request wait for as long as the device
3835 * wishes.
3836 *
3837 * Of course, serving one request at at time may cause loss of
3838 * throughput.
3839 */
3840 if (bfqd->strict_guarantees && bfqd->rq_in_driver > 0)
3841 goto exit;
3842
3843 bfqq = bfq_select_queue(bfqd);
3844 if (!bfqq)
3845 goto exit;
3846
3847 rq = bfq_dispatch_rq_from_bfqq(bfqd, bfqq);
3848
3849 if (rq) {
3850inc_in_driver_start_rq:
3851 bfqd->rq_in_driver++;
3852start_rq:
3853 rq->rq_flags |= RQF_STARTED;
3854 }
3855exit:
3856 return rq;
3857}
3858
Paolo Valente9b25bd02017-12-04 11:42:05 +01003859#if defined(CONFIG_BFQ_GROUP_IOSCHED) && defined(CONFIG_DEBUG_BLK_CGROUP)
3860static void bfq_update_dispatch_stats(struct request_queue *q,
3861 struct request *rq,
3862 struct bfq_queue *in_serv_queue,
3863 bool idle_timer_disabled)
Paolo Valenteaee69d72017-04-19 08:29:02 -06003864{
Paolo Valente9b25bd02017-12-04 11:42:05 +01003865 struct bfq_queue *bfqq = rq ? RQ_BFQQ(rq) : NULL;
Paolo Valenteaee69d72017-04-19 08:29:02 -06003866
Paolo Valente24bfd192017-11-13 07:34:09 +01003867 if (!idle_timer_disabled && !bfqq)
Paolo Valente9b25bd02017-12-04 11:42:05 +01003868 return;
Paolo Valente24bfd192017-11-13 07:34:09 +01003869
3870 /*
3871 * rq and bfqq are guaranteed to exist until this function
3872 * ends, for the following reasons. First, rq can be
3873 * dispatched to the device, and then can be completed and
3874 * freed, only after this function ends. Second, rq cannot be
3875 * merged (and thus freed because of a merge) any longer,
3876 * because it has already started. Thus rq cannot be freed
3877 * before this function ends, and, since rq has a reference to
3878 * bfqq, the same guarantee holds for bfqq too.
3879 *
3880 * In addition, the following queue lock guarantees that
3881 * bfqq_group(bfqq) exists as well.
3882 */
Paolo Valente9b25bd02017-12-04 11:42:05 +01003883 spin_lock_irq(q->queue_lock);
Paolo Valente24bfd192017-11-13 07:34:09 +01003884 if (idle_timer_disabled)
3885 /*
3886 * Since the idle timer has been disabled,
3887 * in_serv_queue contained some request when
3888 * __bfq_dispatch_request was invoked above, which
3889 * implies that rq was picked exactly from
3890 * in_serv_queue. Thus in_serv_queue == bfqq, and is
3891 * therefore guaranteed to exist because of the above
3892 * arguments.
3893 */
3894 bfqg_stats_update_idle_time(bfqq_group(in_serv_queue));
3895 if (bfqq) {
3896 struct bfq_group *bfqg = bfqq_group(bfqq);
3897
3898 bfqg_stats_update_avg_queue_size(bfqg);
3899 bfqg_stats_set_start_empty_time(bfqg);
3900 bfqg_stats_update_io_remove(bfqg, rq->cmd_flags);
3901 }
Paolo Valente9b25bd02017-12-04 11:42:05 +01003902 spin_unlock_irq(q->queue_lock);
3903}
3904#else
3905static inline void bfq_update_dispatch_stats(struct request_queue *q,
3906 struct request *rq,
3907 struct bfq_queue *in_serv_queue,
3908 bool idle_timer_disabled) {}
Paolo Valente24bfd192017-11-13 07:34:09 +01003909#endif
3910
Paolo Valente9b25bd02017-12-04 11:42:05 +01003911static struct request *bfq_dispatch_request(struct blk_mq_hw_ctx *hctx)
3912{
3913 struct bfq_data *bfqd = hctx->queue->elevator->elevator_data;
3914 struct request *rq;
3915 struct bfq_queue *in_serv_queue;
3916 bool waiting_rq, idle_timer_disabled;
3917
3918 spin_lock_irq(&bfqd->lock);
3919
3920 in_serv_queue = bfqd->in_service_queue;
3921 waiting_rq = in_serv_queue && bfq_bfqq_wait_request(in_serv_queue);
3922
3923 rq = __bfq_dispatch_request(hctx);
3924
3925 idle_timer_disabled =
3926 waiting_rq && !bfq_bfqq_wait_request(in_serv_queue);
3927
3928 spin_unlock_irq(&bfqd->lock);
3929
3930 bfq_update_dispatch_stats(hctx->queue, rq, in_serv_queue,
3931 idle_timer_disabled);
3932
Paolo Valenteaee69d72017-04-19 08:29:02 -06003933 return rq;
3934}
3935
3936/*
3937 * Task holds one reference to the queue, dropped when task exits. Each rq
3938 * in-flight on this queue also holds a reference, dropped when rq is freed.
3939 *
3940 * Scheduler lock must be held here. Recall not to use bfqq after calling
3941 * this function on it.
3942 */
Paolo Valenteea25da42017-04-19 08:48:24 -06003943void bfq_put_queue(struct bfq_queue *bfqq)
Paolo Valenteaee69d72017-04-19 08:29:02 -06003944{
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02003945#ifdef CONFIG_BFQ_GROUP_IOSCHED
3946 struct bfq_group *bfqg = bfqq_group(bfqq);
3947#endif
3948
Paolo Valenteaee69d72017-04-19 08:29:02 -06003949 if (bfqq->bfqd)
3950 bfq_log_bfqq(bfqq->bfqd, bfqq, "put_queue: %p %d",
3951 bfqq, bfqq->ref);
3952
3953 bfqq->ref--;
3954 if (bfqq->ref)
3955 return;
3956
Paolo Valente99fead82017-10-09 13:11:23 +02003957 if (!hlist_unhashed(&bfqq->burst_list_node)) {
Arianna Avanzinie1b23242017-04-12 18:23:20 +02003958 hlist_del_init(&bfqq->burst_list_node);
Paolo Valente99fead82017-10-09 13:11:23 +02003959 /*
3960 * Decrement also burst size after the removal, if the
3961 * process associated with bfqq is exiting, and thus
3962 * does not contribute to the burst any longer. This
3963 * decrement helps filter out false positives of large
3964 * bursts, when some short-lived process (often due to
3965 * the execution of commands by some service) happens
3966 * to start and exit while a complex application is
3967 * starting, and thus spawning several processes that
3968 * do I/O (and that *must not* be treated as a large
3969 * burst, see comments on bfq_handle_burst).
3970 *
3971 * In particular, the decrement is performed only if:
3972 * 1) bfqq is not a merged queue, because, if it is,
3973 * then this free of bfqq is not triggered by the exit
3974 * of the process bfqq is associated with, but exactly
3975 * by the fact that bfqq has just been merged.
3976 * 2) burst_size is greater than 0, to handle
3977 * unbalanced decrements. Unbalanced decrements may
3978 * happen in te following case: bfqq is inserted into
3979 * the current burst list--without incrementing
3980 * bust_size--because of a split, but the current
3981 * burst list is not the burst list bfqq belonged to
3982 * (see comments on the case of a split in
3983 * bfq_set_request).
3984 */
3985 if (bfqq->bic && bfqq->bfqd->burst_size > 0)
3986 bfqq->bfqd->burst_size--;
Paolo Valente7cb04002017-09-21 11:04:03 +02003987 }
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02003988
Paolo Valenteaee69d72017-04-19 08:29:02 -06003989 kmem_cache_free(bfq_pool, bfqq);
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02003990#ifdef CONFIG_BFQ_GROUP_IOSCHED
Paolo Valente8f9bebc2017-06-05 10:11:15 +02003991 bfqg_and_blkg_put(bfqg);
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02003992#endif
Paolo Valenteaee69d72017-04-19 08:29:02 -06003993}
3994
Arianna Avanzini36eca892017-04-12 18:23:16 +02003995static void bfq_put_cooperator(struct bfq_queue *bfqq)
3996{
3997 struct bfq_queue *__bfqq, *next;
3998
3999 /*
4000 * If this queue was scheduled to merge with another queue, be
4001 * sure to drop the reference taken on that queue (and others in
4002 * the merge chain). See bfq_setup_merge and bfq_merge_bfqqs.
4003 */
4004 __bfqq = bfqq->new_bfqq;
4005 while (__bfqq) {
4006 if (__bfqq == bfqq)
4007 break;
4008 next = __bfqq->new_bfqq;
4009 bfq_put_queue(__bfqq);
4010 __bfqq = next;
4011 }
4012}
4013
Paolo Valenteaee69d72017-04-19 08:29:02 -06004014static void bfq_exit_bfqq(struct bfq_data *bfqd, struct bfq_queue *bfqq)
4015{
4016 if (bfqq == bfqd->in_service_queue) {
4017 __bfq_bfqq_expire(bfqd, bfqq);
4018 bfq_schedule_dispatch(bfqd);
4019 }
4020
4021 bfq_log_bfqq(bfqd, bfqq, "exit_bfqq: %p, %d", bfqq, bfqq->ref);
4022
Arianna Avanzini36eca892017-04-12 18:23:16 +02004023 bfq_put_cooperator(bfqq);
4024
Paolo Valenteaee69d72017-04-19 08:29:02 -06004025 bfq_put_queue(bfqq); /* release process reference */
4026}
4027
4028static void bfq_exit_icq_bfqq(struct bfq_io_cq *bic, bool is_sync)
4029{
4030 struct bfq_queue *bfqq = bic_to_bfqq(bic, is_sync);
4031 struct bfq_data *bfqd;
4032
4033 if (bfqq)
4034 bfqd = bfqq->bfqd; /* NULL if scheduler already exited */
4035
4036 if (bfqq && bfqd) {
4037 unsigned long flags;
4038
4039 spin_lock_irqsave(&bfqd->lock, flags);
4040 bfq_exit_bfqq(bfqd, bfqq);
4041 bic_set_bfqq(bic, NULL, is_sync);
Paolo Valente6fa3e8d2017-04-12 18:23:21 +02004042 spin_unlock_irqrestore(&bfqd->lock, flags);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004043 }
4044}
4045
4046static void bfq_exit_icq(struct io_cq *icq)
4047{
4048 struct bfq_io_cq *bic = icq_to_bic(icq);
4049
4050 bfq_exit_icq_bfqq(bic, true);
4051 bfq_exit_icq_bfqq(bic, false);
4052}
4053
4054/*
4055 * Update the entity prio values; note that the new values will not
4056 * be used until the next (re)activation.
4057 */
4058static void
4059bfq_set_next_ioprio_data(struct bfq_queue *bfqq, struct bfq_io_cq *bic)
4060{
4061 struct task_struct *tsk = current;
4062 int ioprio_class;
4063 struct bfq_data *bfqd = bfqq->bfqd;
4064
4065 if (!bfqd)
4066 return;
4067
4068 ioprio_class = IOPRIO_PRIO_CLASS(bic->ioprio);
4069 switch (ioprio_class) {
4070 default:
4071 dev_err(bfqq->bfqd->queue->backing_dev_info->dev,
4072 "bfq: bad prio class %d\n", ioprio_class);
Bart Van Asschefa393d12017-08-30 11:42:07 -07004073 /* fall through */
Paolo Valenteaee69d72017-04-19 08:29:02 -06004074 case IOPRIO_CLASS_NONE:
4075 /*
4076 * No prio set, inherit CPU scheduling settings.
4077 */
4078 bfqq->new_ioprio = task_nice_ioprio(tsk);
4079 bfqq->new_ioprio_class = task_nice_ioclass(tsk);
4080 break;
4081 case IOPRIO_CLASS_RT:
4082 bfqq->new_ioprio = IOPRIO_PRIO_DATA(bic->ioprio);
4083 bfqq->new_ioprio_class = IOPRIO_CLASS_RT;
4084 break;
4085 case IOPRIO_CLASS_BE:
4086 bfqq->new_ioprio = IOPRIO_PRIO_DATA(bic->ioprio);
4087 bfqq->new_ioprio_class = IOPRIO_CLASS_BE;
4088 break;
4089 case IOPRIO_CLASS_IDLE:
4090 bfqq->new_ioprio_class = IOPRIO_CLASS_IDLE;
4091 bfqq->new_ioprio = 7;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004092 break;
4093 }
4094
4095 if (bfqq->new_ioprio >= IOPRIO_BE_NR) {
4096 pr_crit("bfq_set_next_ioprio_data: new_ioprio %d\n",
4097 bfqq->new_ioprio);
4098 bfqq->new_ioprio = IOPRIO_BE_NR;
4099 }
4100
4101 bfqq->entity.new_weight = bfq_ioprio_to_weight(bfqq->new_ioprio);
4102 bfqq->entity.prio_changed = 1;
4103}
4104
Paolo Valenteea25da42017-04-19 08:48:24 -06004105static struct bfq_queue *bfq_get_queue(struct bfq_data *bfqd,
4106 struct bio *bio, bool is_sync,
4107 struct bfq_io_cq *bic);
4108
Paolo Valenteaee69d72017-04-19 08:29:02 -06004109static void bfq_check_ioprio_change(struct bfq_io_cq *bic, struct bio *bio)
4110{
4111 struct bfq_data *bfqd = bic_to_bfqd(bic);
4112 struct bfq_queue *bfqq;
4113 int ioprio = bic->icq.ioc->ioprio;
4114
4115 /*
4116 * This condition may trigger on a newly created bic, be sure to
4117 * drop the lock before returning.
4118 */
4119 if (unlikely(!bfqd) || likely(bic->ioprio == ioprio))
4120 return;
4121
4122 bic->ioprio = ioprio;
4123
4124 bfqq = bic_to_bfqq(bic, false);
4125 if (bfqq) {
4126 /* release process reference on this queue */
4127 bfq_put_queue(bfqq);
4128 bfqq = bfq_get_queue(bfqd, bio, BLK_RW_ASYNC, bic);
4129 bic_set_bfqq(bic, bfqq, false);
4130 }
4131
4132 bfqq = bic_to_bfqq(bic, true);
4133 if (bfqq)
4134 bfq_set_next_ioprio_data(bfqq, bic);
4135}
4136
4137static void bfq_init_bfqq(struct bfq_data *bfqd, struct bfq_queue *bfqq,
4138 struct bfq_io_cq *bic, pid_t pid, int is_sync)
4139{
4140 RB_CLEAR_NODE(&bfqq->entity.rb_node);
4141 INIT_LIST_HEAD(&bfqq->fifo);
Arianna Avanzinie1b23242017-04-12 18:23:20 +02004142 INIT_HLIST_NODE(&bfqq->burst_list_node);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004143
4144 bfqq->ref = 0;
4145 bfqq->bfqd = bfqd;
4146
4147 if (bic)
4148 bfq_set_next_ioprio_data(bfqq, bic);
4149
4150 if (is_sync) {
Paolo Valented5be3fe2017-08-04 07:35:10 +02004151 /*
4152 * No need to mark as has_short_ttime if in
4153 * idle_class, because no device idling is performed
4154 * for queues in idle class
4155 */
Paolo Valenteaee69d72017-04-19 08:29:02 -06004156 if (!bfq_class_idle(bfqq))
Paolo Valented5be3fe2017-08-04 07:35:10 +02004157 /* tentatively mark as has_short_ttime */
4158 bfq_mark_bfqq_has_short_ttime(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004159 bfq_mark_bfqq_sync(bfqq);
Arianna Avanzinie1b23242017-04-12 18:23:20 +02004160 bfq_mark_bfqq_just_created(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004161 } else
4162 bfq_clear_bfqq_sync(bfqq);
4163
4164 /* set end request to minus infinity from now */
4165 bfqq->ttime.last_end_request = ktime_get_ns() + 1;
4166
4167 bfq_mark_bfqq_IO_bound(bfqq);
4168
4169 bfqq->pid = pid;
4170
4171 /* Tentative initial value to trade off between thr and lat */
Paolo Valente54b60452017-04-12 18:23:09 +02004172 bfqq->max_budget = (2 * bfq_max_budget(bfqd)) / 3;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004173 bfqq->budget_timeout = bfq_smallest_from_now();
Paolo Valenteaee69d72017-04-19 08:29:02 -06004174
Paolo Valente44e44a12017-04-12 18:23:12 +02004175 bfqq->wr_coeff = 1;
Arianna Avanzini36eca892017-04-12 18:23:16 +02004176 bfqq->last_wr_start_finish = jiffies;
Paolo Valente77b7dce2017-04-12 18:23:13 +02004177 bfqq->wr_start_at_switch_to_srt = bfq_smallest_from_now();
Arianna Avanzini36eca892017-04-12 18:23:16 +02004178 bfqq->split_time = bfq_smallest_from_now();
Paolo Valente77b7dce2017-04-12 18:23:13 +02004179
4180 /*
Paolo Valentea34b0242017-12-15 07:23:12 +01004181 * To not forget the possibly high bandwidth consumed by a
4182 * process/queue in the recent past,
4183 * bfq_bfqq_softrt_next_start() returns a value at least equal
4184 * to the current value of bfqq->soft_rt_next_start (see
4185 * comments on bfq_bfqq_softrt_next_start). Set
4186 * soft_rt_next_start to now, to mean that bfqq has consumed
4187 * no bandwidth so far.
Paolo Valente77b7dce2017-04-12 18:23:13 +02004188 */
Paolo Valentea34b0242017-12-15 07:23:12 +01004189 bfqq->soft_rt_next_start = jiffies;
Paolo Valente44e44a12017-04-12 18:23:12 +02004190
Paolo Valenteaee69d72017-04-19 08:29:02 -06004191 /* first request is almost certainly seeky */
4192 bfqq->seek_history = 1;
4193}
4194
4195static struct bfq_queue **bfq_async_queue_prio(struct bfq_data *bfqd,
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004196 struct bfq_group *bfqg,
Paolo Valenteaee69d72017-04-19 08:29:02 -06004197 int ioprio_class, int ioprio)
4198{
4199 switch (ioprio_class) {
4200 case IOPRIO_CLASS_RT:
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004201 return &bfqg->async_bfqq[0][ioprio];
Paolo Valenteaee69d72017-04-19 08:29:02 -06004202 case IOPRIO_CLASS_NONE:
4203 ioprio = IOPRIO_NORM;
4204 /* fall through */
4205 case IOPRIO_CLASS_BE:
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004206 return &bfqg->async_bfqq[1][ioprio];
Paolo Valenteaee69d72017-04-19 08:29:02 -06004207 case IOPRIO_CLASS_IDLE:
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004208 return &bfqg->async_idle_bfqq;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004209 default:
4210 return NULL;
4211 }
4212}
4213
4214static struct bfq_queue *bfq_get_queue(struct bfq_data *bfqd,
4215 struct bio *bio, bool is_sync,
4216 struct bfq_io_cq *bic)
4217{
4218 const int ioprio = IOPRIO_PRIO_DATA(bic->ioprio);
4219 const int ioprio_class = IOPRIO_PRIO_CLASS(bic->ioprio);
4220 struct bfq_queue **async_bfqq = NULL;
4221 struct bfq_queue *bfqq;
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004222 struct bfq_group *bfqg;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004223
4224 rcu_read_lock();
4225
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004226 bfqg = bfq_find_set_group(bfqd, bio_blkcg(bio));
4227 if (!bfqg) {
4228 bfqq = &bfqd->oom_bfqq;
4229 goto out;
4230 }
4231
Paolo Valenteaee69d72017-04-19 08:29:02 -06004232 if (!is_sync) {
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004233 async_bfqq = bfq_async_queue_prio(bfqd, bfqg, ioprio_class,
Paolo Valenteaee69d72017-04-19 08:29:02 -06004234 ioprio);
4235 bfqq = *async_bfqq;
4236 if (bfqq)
4237 goto out;
4238 }
4239
4240 bfqq = kmem_cache_alloc_node(bfq_pool,
4241 GFP_NOWAIT | __GFP_ZERO | __GFP_NOWARN,
4242 bfqd->queue->node);
4243
4244 if (bfqq) {
4245 bfq_init_bfqq(bfqd, bfqq, bic, current->pid,
4246 is_sync);
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004247 bfq_init_entity(&bfqq->entity, bfqg);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004248 bfq_log_bfqq(bfqd, bfqq, "allocated");
4249 } else {
4250 bfqq = &bfqd->oom_bfqq;
4251 bfq_log_bfqq(bfqd, bfqq, "using oom bfqq");
4252 goto out;
4253 }
4254
4255 /*
4256 * Pin the queue now that it's allocated, scheduler exit will
4257 * prune it.
4258 */
4259 if (async_bfqq) {
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004260 bfqq->ref++; /*
4261 * Extra group reference, w.r.t. sync
4262 * queue. This extra reference is removed
4263 * only if bfqq->bfqg disappears, to
4264 * guarantee that this queue is not freed
4265 * until its group goes away.
4266 */
4267 bfq_log_bfqq(bfqd, bfqq, "get_queue, bfqq not in async: %p, %d",
Paolo Valenteaee69d72017-04-19 08:29:02 -06004268 bfqq, bfqq->ref);
4269 *async_bfqq = bfqq;
4270 }
4271
4272out:
4273 bfqq->ref++; /* get a process reference to this queue */
4274 bfq_log_bfqq(bfqd, bfqq, "get_queue, at end: %p, %d", bfqq, bfqq->ref);
4275 rcu_read_unlock();
4276 return bfqq;
4277}
4278
4279static void bfq_update_io_thinktime(struct bfq_data *bfqd,
4280 struct bfq_queue *bfqq)
4281{
4282 struct bfq_ttime *ttime = &bfqq->ttime;
4283 u64 elapsed = ktime_get_ns() - bfqq->ttime.last_end_request;
4284
4285 elapsed = min_t(u64, elapsed, 2ULL * bfqd->bfq_slice_idle);
4286
4287 ttime->ttime_samples = (7*bfqq->ttime.ttime_samples + 256) / 8;
4288 ttime->ttime_total = div_u64(7*ttime->ttime_total + 256*elapsed, 8);
4289 ttime->ttime_mean = div64_ul(ttime->ttime_total + 128,
4290 ttime->ttime_samples);
4291}
4292
4293static void
4294bfq_update_io_seektime(struct bfq_data *bfqd, struct bfq_queue *bfqq,
4295 struct request *rq)
4296{
Paolo Valenteaee69d72017-04-19 08:29:02 -06004297 bfqq->seek_history <<= 1;
Paolo Valenteab0e43e2017-04-12 18:23:10 +02004298 bfqq->seek_history |=
4299 get_sdist(bfqq->last_request_pos, rq) > BFQQ_SEEK_THR &&
Paolo Valenteaee69d72017-04-19 08:29:02 -06004300 (!blk_queue_nonrot(bfqd->queue) ||
4301 blk_rq_sectors(rq) < BFQQ_SECT_THR_NONROT);
4302}
4303
Paolo Valented5be3fe2017-08-04 07:35:10 +02004304static void bfq_update_has_short_ttime(struct bfq_data *bfqd,
4305 struct bfq_queue *bfqq,
4306 struct bfq_io_cq *bic)
Paolo Valenteaee69d72017-04-19 08:29:02 -06004307{
Paolo Valented5be3fe2017-08-04 07:35:10 +02004308 bool has_short_ttime = true;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004309
Paolo Valented5be3fe2017-08-04 07:35:10 +02004310 /*
4311 * No need to update has_short_ttime if bfqq is async or in
4312 * idle io prio class, or if bfq_slice_idle is zero, because
4313 * no device idling is performed for bfqq in this case.
4314 */
4315 if (!bfq_bfqq_sync(bfqq) || bfq_class_idle(bfqq) ||
4316 bfqd->bfq_slice_idle == 0)
Paolo Valenteaee69d72017-04-19 08:29:02 -06004317 return;
4318
Arianna Avanzini36eca892017-04-12 18:23:16 +02004319 /* Idle window just restored, statistics are meaningless. */
4320 if (time_is_after_eq_jiffies(bfqq->split_time +
4321 bfqd->bfq_wr_min_idle_time))
4322 return;
4323
Paolo Valented5be3fe2017-08-04 07:35:10 +02004324 /* Think time is infinite if no process is linked to
4325 * bfqq. Otherwise check average think time to
4326 * decide whether to mark as has_short_ttime
4327 */
Paolo Valenteaee69d72017-04-19 08:29:02 -06004328 if (atomic_read(&bic->icq.ioc->active_ref) == 0 ||
Paolo Valented5be3fe2017-08-04 07:35:10 +02004329 (bfq_sample_valid(bfqq->ttime.ttime_samples) &&
4330 bfqq->ttime.ttime_mean > bfqd->bfq_slice_idle))
4331 has_short_ttime = false;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004332
Paolo Valented5be3fe2017-08-04 07:35:10 +02004333 bfq_log_bfqq(bfqd, bfqq, "update_has_short_ttime: has_short_ttime %d",
4334 has_short_ttime);
4335
4336 if (has_short_ttime)
4337 bfq_mark_bfqq_has_short_ttime(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004338 else
Paolo Valented5be3fe2017-08-04 07:35:10 +02004339 bfq_clear_bfqq_has_short_ttime(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004340}
4341
4342/*
4343 * Called when a new fs request (rq) is added to bfqq. Check if there's
4344 * something we should do about it.
4345 */
4346static void bfq_rq_enqueued(struct bfq_data *bfqd, struct bfq_queue *bfqq,
4347 struct request *rq)
4348{
4349 struct bfq_io_cq *bic = RQ_BIC(rq);
4350
4351 if (rq->cmd_flags & REQ_META)
4352 bfqq->meta_pending++;
4353
4354 bfq_update_io_thinktime(bfqd, bfqq);
Paolo Valented5be3fe2017-08-04 07:35:10 +02004355 bfq_update_has_short_ttime(bfqd, bfqq, bic);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004356 bfq_update_io_seektime(bfqd, bfqq, rq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004357
4358 bfq_log_bfqq(bfqd, bfqq,
Paolo Valented5be3fe2017-08-04 07:35:10 +02004359 "rq_enqueued: has_short_ttime=%d (seeky %d)",
4360 bfq_bfqq_has_short_ttime(bfqq), BFQQ_SEEKY(bfqq));
Paolo Valenteaee69d72017-04-19 08:29:02 -06004361
4362 bfqq->last_request_pos = blk_rq_pos(rq) + blk_rq_sectors(rq);
4363
4364 if (bfqq == bfqd->in_service_queue && bfq_bfqq_wait_request(bfqq)) {
4365 bool small_req = bfqq->queued[rq_is_sync(rq)] == 1 &&
4366 blk_rq_sectors(rq) < 32;
4367 bool budget_timeout = bfq_bfqq_budget_timeout(bfqq);
4368
4369 /*
4370 * There is just this request queued: if the request
4371 * is small and the queue is not to be expired, then
4372 * just exit.
4373 *
4374 * In this way, if the device is being idled to wait
4375 * for a new request from the in-service queue, we
4376 * avoid unplugging the device and committing the
4377 * device to serve just a small request. On the
4378 * contrary, we wait for the block layer to decide
4379 * when to unplug the device: hopefully, new requests
4380 * will be merged to this one quickly, then the device
4381 * will be unplugged and larger requests will be
4382 * dispatched.
4383 */
4384 if (small_req && !budget_timeout)
4385 return;
4386
4387 /*
4388 * A large enough request arrived, or the queue is to
4389 * be expired: in both cases disk idling is to be
4390 * stopped, so clear wait_request flag and reset
4391 * timer.
4392 */
4393 bfq_clear_bfqq_wait_request(bfqq);
4394 hrtimer_try_to_cancel(&bfqd->idle_slice_timer);
4395
4396 /*
4397 * The queue is not empty, because a new request just
4398 * arrived. Hence we can safely expire the queue, in
4399 * case of budget timeout, without risking that the
4400 * timestamps of the queue are not updated correctly.
4401 * See [1] for more details.
4402 */
4403 if (budget_timeout)
4404 bfq_bfqq_expire(bfqd, bfqq, false,
4405 BFQQE_BUDGET_TIMEOUT);
4406 }
4407}
4408
Paolo Valente24bfd192017-11-13 07:34:09 +01004409/* returns true if it causes the idle timer to be disabled */
4410static bool __bfq_insert_request(struct bfq_data *bfqd, struct request *rq)
Paolo Valenteaee69d72017-04-19 08:29:02 -06004411{
Arianna Avanzini36eca892017-04-12 18:23:16 +02004412 struct bfq_queue *bfqq = RQ_BFQQ(rq),
4413 *new_bfqq = bfq_setup_cooperator(bfqd, bfqq, rq, true);
Paolo Valente24bfd192017-11-13 07:34:09 +01004414 bool waiting, idle_timer_disabled = false;
Arianna Avanzini36eca892017-04-12 18:23:16 +02004415
4416 if (new_bfqq) {
4417 if (bic_to_bfqq(RQ_BIC(rq), 1) != bfqq)
4418 new_bfqq = bic_to_bfqq(RQ_BIC(rq), 1);
4419 /*
4420 * Release the request's reference to the old bfqq
4421 * and make sure one is taken to the shared queue.
4422 */
4423 new_bfqq->allocated++;
4424 bfqq->allocated--;
4425 new_bfqq->ref++;
4426 /*
4427 * If the bic associated with the process
4428 * issuing this request still points to bfqq
4429 * (and thus has not been already redirected
4430 * to new_bfqq or even some other bfq_queue),
4431 * then complete the merge and redirect it to
4432 * new_bfqq.
4433 */
4434 if (bic_to_bfqq(RQ_BIC(rq), 1) == bfqq)
4435 bfq_merge_bfqqs(bfqd, RQ_BIC(rq),
4436 bfqq, new_bfqq);
Paolo Valente894df932017-09-21 11:04:02 +02004437
4438 bfq_clear_bfqq_just_created(bfqq);
Arianna Avanzini36eca892017-04-12 18:23:16 +02004439 /*
4440 * rq is about to be enqueued into new_bfqq,
4441 * release rq reference on bfqq
4442 */
4443 bfq_put_queue(bfqq);
4444 rq->elv.priv[1] = new_bfqq;
4445 bfqq = new_bfqq;
4446 }
Paolo Valenteaee69d72017-04-19 08:29:02 -06004447
Paolo Valente24bfd192017-11-13 07:34:09 +01004448 waiting = bfqq && bfq_bfqq_wait_request(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004449 bfq_add_request(rq);
Paolo Valente24bfd192017-11-13 07:34:09 +01004450 idle_timer_disabled = waiting && !bfq_bfqq_wait_request(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004451
4452 rq->fifo_time = ktime_get_ns() + bfqd->bfq_fifo_expire[rq_is_sync(rq)];
4453 list_add_tail(&rq->queuelist, &bfqq->fifo);
4454
4455 bfq_rq_enqueued(bfqd, bfqq, rq);
Paolo Valente24bfd192017-11-13 07:34:09 +01004456
4457 return idle_timer_disabled;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004458}
4459
Paolo Valente9b25bd02017-12-04 11:42:05 +01004460#if defined(CONFIG_BFQ_GROUP_IOSCHED) && defined(CONFIG_DEBUG_BLK_CGROUP)
4461static void bfq_update_insert_stats(struct request_queue *q,
4462 struct bfq_queue *bfqq,
4463 bool idle_timer_disabled,
4464 unsigned int cmd_flags)
4465{
4466 if (!bfqq)
4467 return;
4468
4469 /*
4470 * bfqq still exists, because it can disappear only after
4471 * either it is merged with another queue, or the process it
4472 * is associated with exits. But both actions must be taken by
4473 * the same process currently executing this flow of
4474 * instructions.
4475 *
4476 * In addition, the following queue lock guarantees that
4477 * bfqq_group(bfqq) exists as well.
4478 */
4479 spin_lock_irq(q->queue_lock);
4480 bfqg_stats_update_io_add(bfqq_group(bfqq), bfqq, cmd_flags);
4481 if (idle_timer_disabled)
4482 bfqg_stats_update_idle_time(bfqq_group(bfqq));
4483 spin_unlock_irq(q->queue_lock);
4484}
4485#else
4486static inline void bfq_update_insert_stats(struct request_queue *q,
4487 struct bfq_queue *bfqq,
4488 bool idle_timer_disabled,
4489 unsigned int cmd_flags) {}
4490#endif
4491
Paolo Valenteaee69d72017-04-19 08:29:02 -06004492static void bfq_insert_request(struct blk_mq_hw_ctx *hctx, struct request *rq,
4493 bool at_head)
4494{
4495 struct request_queue *q = hctx->queue;
4496 struct bfq_data *bfqd = q->elevator->elevator_data;
Paolo Valente18e5a572018-05-04 19:17:01 +02004497 struct bfq_queue *bfqq;
Paolo Valente24bfd192017-11-13 07:34:09 +01004498 bool idle_timer_disabled = false;
4499 unsigned int cmd_flags;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004500
4501 spin_lock_irq(&bfqd->lock);
4502 if (blk_mq_sched_try_insert_merge(q, rq)) {
4503 spin_unlock_irq(&bfqd->lock);
4504 return;
4505 }
4506
4507 spin_unlock_irq(&bfqd->lock);
4508
4509 blk_mq_sched_request_inserted(rq);
4510
4511 spin_lock_irq(&bfqd->lock);
Paolo Valente18e5a572018-05-04 19:17:01 +02004512 bfqq = bfq_init_rq(rq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004513 if (at_head || blk_rq_is_passthrough(rq)) {
4514 if (at_head)
4515 list_add(&rq->queuelist, &bfqd->dispatch);
4516 else
4517 list_add_tail(&rq->queuelist, &bfqd->dispatch);
Paolo Valente18e5a572018-05-04 19:17:01 +02004518 } else { /* bfqq is assumed to be non null here */
Paolo Valente24bfd192017-11-13 07:34:09 +01004519 idle_timer_disabled = __bfq_insert_request(bfqd, rq);
Luca Miccio614822f2017-11-13 07:34:08 +01004520 /*
4521 * Update bfqq, because, if a queue merge has occurred
4522 * in __bfq_insert_request, then rq has been
4523 * redirected into a new queue.
4524 */
4525 bfqq = RQ_BFQQ(rq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004526
4527 if (rq_mergeable(rq)) {
4528 elv_rqhash_add(q, rq);
4529 if (!q->last_merge)
4530 q->last_merge = rq;
4531 }
4532 }
4533
Paolo Valente24bfd192017-11-13 07:34:09 +01004534 /*
4535 * Cache cmd_flags before releasing scheduler lock, because rq
4536 * may disappear afterwards (for example, because of a request
4537 * merge).
4538 */
4539 cmd_flags = rq->cmd_flags;
Paolo Valente9b25bd02017-12-04 11:42:05 +01004540
Paolo Valente6fa3e8d2017-04-12 18:23:21 +02004541 spin_unlock_irq(&bfqd->lock);
Paolo Valente24bfd192017-11-13 07:34:09 +01004542
Paolo Valente9b25bd02017-12-04 11:42:05 +01004543 bfq_update_insert_stats(q, bfqq, idle_timer_disabled,
4544 cmd_flags);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004545}
4546
4547static void bfq_insert_requests(struct blk_mq_hw_ctx *hctx,
4548 struct list_head *list, bool at_head)
4549{
4550 while (!list_empty(list)) {
4551 struct request *rq;
4552
4553 rq = list_first_entry(list, struct request, queuelist);
4554 list_del_init(&rq->queuelist);
4555 bfq_insert_request(hctx, rq, at_head);
4556 }
4557}
4558
4559static void bfq_update_hw_tag(struct bfq_data *bfqd)
4560{
4561 bfqd->max_rq_in_driver = max_t(int, bfqd->max_rq_in_driver,
4562 bfqd->rq_in_driver);
4563
4564 if (bfqd->hw_tag == 1)
4565 return;
4566
4567 /*
4568 * This sample is valid if the number of outstanding requests
4569 * is large enough to allow a queueing behavior. Note that the
4570 * sum is not exact, as it's not taking into account deactivated
4571 * requests.
4572 */
4573 if (bfqd->rq_in_driver + bfqd->queued < BFQ_HW_QUEUE_THRESHOLD)
4574 return;
4575
4576 if (bfqd->hw_tag_samples++ < BFQ_HW_QUEUE_SAMPLES)
4577 return;
4578
4579 bfqd->hw_tag = bfqd->max_rq_in_driver > BFQ_HW_QUEUE_THRESHOLD;
4580 bfqd->max_rq_in_driver = 0;
4581 bfqd->hw_tag_samples = 0;
4582}
4583
4584static void bfq_completed_request(struct bfq_queue *bfqq, struct bfq_data *bfqd)
4585{
Paolo Valenteab0e43e2017-04-12 18:23:10 +02004586 u64 now_ns;
4587 u32 delta_us;
4588
Paolo Valenteaee69d72017-04-19 08:29:02 -06004589 bfq_update_hw_tag(bfqd);
4590
4591 bfqd->rq_in_driver--;
4592 bfqq->dispatched--;
4593
Paolo Valente44e44a12017-04-12 18:23:12 +02004594 if (!bfqq->dispatched && !bfq_bfqq_busy(bfqq)) {
4595 /*
4596 * Set budget_timeout (which we overload to store the
4597 * time at which the queue remains with no backlog and
4598 * no outstanding request; used by the weight-raising
4599 * mechanism).
4600 */
4601 bfqq->budget_timeout = jiffies;
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +02004602
4603 bfq_weights_tree_remove(bfqd, &bfqq->entity,
4604 &bfqd->queue_weights_tree);
Paolo Valente44e44a12017-04-12 18:23:12 +02004605 }
4606
Paolo Valenteab0e43e2017-04-12 18:23:10 +02004607 now_ns = ktime_get_ns();
4608
4609 bfqq->ttime.last_end_request = now_ns;
4610
4611 /*
4612 * Using us instead of ns, to get a reasonable precision in
4613 * computing rate in next check.
4614 */
4615 delta_us = div_u64(now_ns - bfqd->last_completion, NSEC_PER_USEC);
4616
4617 /*
4618 * If the request took rather long to complete, and, according
4619 * to the maximum request size recorded, this completion latency
4620 * implies that the request was certainly served at a very low
4621 * rate (less than 1M sectors/sec), then the whole observation
4622 * interval that lasts up to this time instant cannot be a
4623 * valid time interval for computing a new peak rate. Invoke
4624 * bfq_update_rate_reset to have the following three steps
4625 * taken:
4626 * - close the observation interval at the last (previous)
4627 * request dispatch or completion
4628 * - compute rate, if possible, for that observation interval
4629 * - reset to zero samples, which will trigger a proper
4630 * re-initialization of the observation interval on next
4631 * dispatch
4632 */
4633 if (delta_us > BFQ_MIN_TT/NSEC_PER_USEC &&
4634 (bfqd->last_rq_max_size<<BFQ_RATE_SHIFT)/delta_us <
4635 1UL<<(BFQ_RATE_SHIFT - 10))
4636 bfq_update_rate_reset(bfqd, NULL);
4637 bfqd->last_completion = now_ns;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004638
4639 /*
Paolo Valente77b7dce2017-04-12 18:23:13 +02004640 * If we are waiting to discover whether the request pattern
4641 * of the task associated with the queue is actually
4642 * isochronous, and both requisites for this condition to hold
4643 * are now satisfied, then compute soft_rt_next_start (see the
4644 * comments on the function bfq_bfqq_softrt_next_start()). We
4645 * schedule this delayed check when bfqq expires, if it still
4646 * has in-flight requests.
4647 */
4648 if (bfq_bfqq_softrt_update(bfqq) && bfqq->dispatched == 0 &&
4649 RB_EMPTY_ROOT(&bfqq->sort_list))
4650 bfqq->soft_rt_next_start =
4651 bfq_bfqq_softrt_next_start(bfqd, bfqq);
4652
4653 /*
Paolo Valenteaee69d72017-04-19 08:29:02 -06004654 * If this is the in-service queue, check if it needs to be expired,
4655 * or if we want to idle in case it has no pending requests.
4656 */
4657 if (bfqd->in_service_queue == bfqq) {
Paolo Valente44e44a12017-04-12 18:23:12 +02004658 if (bfqq->dispatched == 0 && bfq_bfqq_must_idle(bfqq)) {
Paolo Valenteaee69d72017-04-19 08:29:02 -06004659 bfq_arm_slice_timer(bfqd);
4660 return;
4661 } else if (bfq_may_expire_for_budg_timeout(bfqq))
4662 bfq_bfqq_expire(bfqd, bfqq, false,
4663 BFQQE_BUDGET_TIMEOUT);
4664 else if (RB_EMPTY_ROOT(&bfqq->sort_list) &&
4665 (bfqq->dispatched == 0 ||
4666 !bfq_bfqq_may_idle(bfqq)))
4667 bfq_bfqq_expire(bfqd, bfqq, false,
4668 BFQQE_NO_MORE_REQUESTS);
4669 }
Hou Tao3f7cb4f2017-07-11 21:58:15 +08004670
4671 if (!bfqd->rq_in_driver)
4672 bfq_schedule_dispatch(bfqd);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004673}
4674
Paolo Valentea7877392018-02-07 22:19:20 +01004675static void bfq_finish_requeue_request_body(struct bfq_queue *bfqq)
Paolo Valenteaee69d72017-04-19 08:29:02 -06004676{
4677 bfqq->allocated--;
4678
4679 bfq_put_queue(bfqq);
4680}
4681
Paolo Valentea7877392018-02-07 22:19:20 +01004682/*
4683 * Handle either a requeue or a finish for rq. The things to do are
4684 * the same in both cases: all references to rq are to be dropped. In
4685 * particular, rq is considered completed from the point of view of
4686 * the scheduler.
4687 */
4688static void bfq_finish_requeue_request(struct request *rq)
Paolo Valenteaee69d72017-04-19 08:29:02 -06004689{
Paolo Valentea7877392018-02-07 22:19:20 +01004690 struct bfq_queue *bfqq = RQ_BFQQ(rq);
Christoph Hellwig5bbf4e52017-06-16 18:15:26 +02004691 struct bfq_data *bfqd;
4692
Paolo Valentea7877392018-02-07 22:19:20 +01004693 /*
4694 * Requeue and finish hooks are invoked in blk-mq without
4695 * checking whether the involved request is actually still
4696 * referenced in the scheduler. To handle this fact, the
4697 * following two checks make this function exit in case of
4698 * spurious invocations, for which there is nothing to do.
4699 *
4700 * First, check whether rq has nothing to do with an elevator.
4701 */
4702 if (unlikely(!(rq->rq_flags & RQF_ELVPRIV)))
Christoph Hellwig5bbf4e52017-06-16 18:15:26 +02004703 return;
4704
Paolo Valentea7877392018-02-07 22:19:20 +01004705 /*
4706 * rq either is not associated with any icq, or is an already
4707 * requeued request that has not (yet) been re-inserted into
4708 * a bfq_queue.
4709 */
4710 if (!rq->elv.icq || !bfqq)
4711 return;
4712
Christoph Hellwig5bbf4e52017-06-16 18:15:26 +02004713 bfqd = bfqq->bfqd;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004714
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004715 if (rq->rq_flags & RQF_STARTED)
4716 bfqg_stats_update_completion(bfqq_group(bfqq),
Omar Sandoval522a7772018-05-09 02:08:53 -07004717 rq->start_time_ns,
4718 rq->io_start_time_ns,
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004719 rq->cmd_flags);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004720
4721 if (likely(rq->rq_flags & RQF_STARTED)) {
4722 unsigned long flags;
4723
4724 spin_lock_irqsave(&bfqd->lock, flags);
4725
4726 bfq_completed_request(bfqq, bfqd);
Paolo Valentea7877392018-02-07 22:19:20 +01004727 bfq_finish_requeue_request_body(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004728
Paolo Valente6fa3e8d2017-04-12 18:23:21 +02004729 spin_unlock_irqrestore(&bfqd->lock, flags);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004730 } else {
4731 /*
4732 * Request rq may be still/already in the scheduler,
Paolo Valentea7877392018-02-07 22:19:20 +01004733 * in which case we need to remove it (this should
4734 * never happen in case of requeue). And we cannot
Paolo Valenteaee69d72017-04-19 08:29:02 -06004735 * defer such a check and removal, to avoid
4736 * inconsistencies in the time interval from the end
4737 * of this function to the start of the deferred work.
4738 * This situation seems to occur only in process
4739 * context, as a consequence of a merge. In the
4740 * current version of the code, this implies that the
4741 * lock is held.
4742 */
4743
Luca Miccio614822f2017-11-13 07:34:08 +01004744 if (!RB_EMPTY_NODE(&rq->rb_node)) {
Christoph Hellwig7b9e9362017-06-16 18:15:21 +02004745 bfq_remove_request(rq->q, rq);
Luca Miccio614822f2017-11-13 07:34:08 +01004746 bfqg_stats_update_io_remove(bfqq_group(bfqq),
4747 rq->cmd_flags);
4748 }
Paolo Valentea7877392018-02-07 22:19:20 +01004749 bfq_finish_requeue_request_body(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004750 }
4751
Paolo Valentea7877392018-02-07 22:19:20 +01004752 /*
4753 * Reset private fields. In case of a requeue, this allows
4754 * this function to correctly do nothing if it is spuriously
4755 * invoked again on this same request (see the check at the
4756 * beginning of the function). Probably, a better general
4757 * design would be to prevent blk-mq from invoking the requeue
4758 * or finish hooks of an elevator, for a request that is not
4759 * referred by that elevator.
4760 *
4761 * Resetting the following fields would break the
4762 * request-insertion logic if rq is re-inserted into a bfq
4763 * internal queue, without a re-preparation. Here we assume
4764 * that re-insertions of requeued requests, without
4765 * re-preparation, can happen only for pass_through or at_head
4766 * requests (which are not re-inserted into bfq internal
4767 * queues).
4768 */
Paolo Valenteaee69d72017-04-19 08:29:02 -06004769 rq->elv.priv[0] = NULL;
4770 rq->elv.priv[1] = NULL;
4771}
4772
4773/*
Arianna Avanzini36eca892017-04-12 18:23:16 +02004774 * Returns NULL if a new bfqq should be allocated, or the old bfqq if this
4775 * was the last process referring to that bfqq.
4776 */
4777static struct bfq_queue *
4778bfq_split_bfqq(struct bfq_io_cq *bic, struct bfq_queue *bfqq)
4779{
4780 bfq_log_bfqq(bfqq->bfqd, bfqq, "splitting queue");
4781
4782 if (bfqq_process_refs(bfqq) == 1) {
4783 bfqq->pid = current->pid;
4784 bfq_clear_bfqq_coop(bfqq);
4785 bfq_clear_bfqq_split_coop(bfqq);
4786 return bfqq;
4787 }
4788
4789 bic_set_bfqq(bic, NULL, 1);
4790
4791 bfq_put_cooperator(bfqq);
4792
4793 bfq_put_queue(bfqq);
4794 return NULL;
4795}
4796
4797static struct bfq_queue *bfq_get_bfqq_handle_split(struct bfq_data *bfqd,
4798 struct bfq_io_cq *bic,
4799 struct bio *bio,
4800 bool split, bool is_sync,
4801 bool *new_queue)
4802{
4803 struct bfq_queue *bfqq = bic_to_bfqq(bic, is_sync);
4804
4805 if (likely(bfqq && bfqq != &bfqd->oom_bfqq))
4806 return bfqq;
4807
4808 if (new_queue)
4809 *new_queue = true;
4810
4811 if (bfqq)
4812 bfq_put_queue(bfqq);
4813 bfqq = bfq_get_queue(bfqd, bio, is_sync, bic);
4814
4815 bic_set_bfqq(bic, bfqq, is_sync);
Arianna Avanzinie1b23242017-04-12 18:23:20 +02004816 if (split && is_sync) {
4817 if ((bic->was_in_burst_list && bfqd->large_burst) ||
4818 bic->saved_in_large_burst)
4819 bfq_mark_bfqq_in_large_burst(bfqq);
4820 else {
4821 bfq_clear_bfqq_in_large_burst(bfqq);
4822 if (bic->was_in_burst_list)
Paolo Valente99fead82017-10-09 13:11:23 +02004823 /*
4824 * If bfqq was in the current
4825 * burst list before being
4826 * merged, then we have to add
4827 * it back. And we do not need
4828 * to increase burst_size, as
4829 * we did not decrement
4830 * burst_size when we removed
4831 * bfqq from the burst list as
4832 * a consequence of a merge
4833 * (see comments in
4834 * bfq_put_queue). In this
4835 * respect, it would be rather
4836 * costly to know whether the
4837 * current burst list is still
4838 * the same burst list from
4839 * which bfqq was removed on
4840 * the merge. To avoid this
4841 * cost, if bfqq was in a
4842 * burst list, then we add
4843 * bfqq to the current burst
4844 * list without any further
4845 * check. This can cause
4846 * inappropriate insertions,
4847 * but rarely enough to not
4848 * harm the detection of large
4849 * bursts significantly.
4850 */
Arianna Avanzinie1b23242017-04-12 18:23:20 +02004851 hlist_add_head(&bfqq->burst_list_node,
4852 &bfqd->burst_list);
4853 }
Arianna Avanzini36eca892017-04-12 18:23:16 +02004854 bfqq->split_time = jiffies;
Arianna Avanzinie1b23242017-04-12 18:23:20 +02004855 }
Arianna Avanzini36eca892017-04-12 18:23:16 +02004856
4857 return bfqq;
4858}
4859
4860/*
Paolo Valente18e5a572018-05-04 19:17:01 +02004861 * Only reset private fields. The actual request preparation will be
4862 * performed by bfq_init_rq, when rq is either inserted or merged. See
4863 * comments on bfq_init_rq for the reason behind this delayed
4864 * preparation.
Paolo Valenteaee69d72017-04-19 08:29:02 -06004865 */
Christoph Hellwig5bbf4e52017-06-16 18:15:26 +02004866static void bfq_prepare_request(struct request *rq, struct bio *bio)
Paolo Valenteaee69d72017-04-19 08:29:02 -06004867{
Paolo Valente18e5a572018-05-04 19:17:01 +02004868 /*
4869 * Regardless of whether we have an icq attached, we have to
4870 * clear the scheduler pointers, as they might point to
4871 * previously allocated bic/bfqq structs.
4872 */
4873 rq->elv.priv[0] = rq->elv.priv[1] = NULL;
4874}
4875
4876/*
4877 * If needed, init rq, allocate bfq data structures associated with
4878 * rq, and increment reference counters in the destination bfq_queue
4879 * for rq. Return the destination bfq_queue for rq, or NULL is rq is
4880 * not associated with any bfq_queue.
4881 *
4882 * This function is invoked by the functions that perform rq insertion
4883 * or merging. One may have expected the above preparation operations
4884 * to be performed in bfq_prepare_request, and not delayed to when rq
4885 * is inserted or merged. The rationale behind this delayed
4886 * preparation is that, after the prepare_request hook is invoked for
4887 * rq, rq may still be transformed into a request with no icq, i.e., a
4888 * request not associated with any queue. No bfq hook is invoked to
4889 * signal this tranformation. As a consequence, should these
4890 * preparation operations be performed when the prepare_request hook
4891 * is invoked, and should rq be transformed one moment later, bfq
4892 * would end up in an inconsistent state, because it would have
4893 * incremented some queue counters for an rq destined to
4894 * transformation, without any chance to correctly lower these
4895 * counters back. In contrast, no transformation can still happen for
4896 * rq after rq has been inserted or merged. So, it is safe to execute
4897 * these preparation operations when rq is finally inserted or merged.
4898 */
4899static struct bfq_queue *bfq_init_rq(struct request *rq)
4900{
Christoph Hellwig5bbf4e52017-06-16 18:15:26 +02004901 struct request_queue *q = rq->q;
Paolo Valente18e5a572018-05-04 19:17:01 +02004902 struct bio *bio = rq->bio;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004903 struct bfq_data *bfqd = q->elevator->elevator_data;
Christoph Hellwig9f210732017-06-16 18:15:24 +02004904 struct bfq_io_cq *bic;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004905 const int is_sync = rq_is_sync(rq);
4906 struct bfq_queue *bfqq;
Arianna Avanzini36eca892017-04-12 18:23:16 +02004907 bool new_queue = false;
Paolo Valente13c931b2017-06-27 12:30:47 -06004908 bool bfqq_already_existing = false, split = false;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004909
Paolo Valente18e5a572018-05-04 19:17:01 +02004910 if (unlikely(!rq->elv.icq))
4911 return NULL;
4912
Jens Axboe72961c42018-04-17 17:08:52 -06004913 /*
Paolo Valente18e5a572018-05-04 19:17:01 +02004914 * Assuming that elv.priv[1] is set only if everything is set
4915 * for this rq. This holds true, because this function is
4916 * invoked only for insertion or merging, and, after such
4917 * events, a request cannot be manipulated any longer before
4918 * being removed from bfq.
Jens Axboe72961c42018-04-17 17:08:52 -06004919 */
Paolo Valente18e5a572018-05-04 19:17:01 +02004920 if (rq->elv.priv[1])
4921 return rq->elv.priv[1];
Jens Axboe72961c42018-04-17 17:08:52 -06004922
Christoph Hellwig9f210732017-06-16 18:15:24 +02004923 bic = icq_to_bic(rq->elv.icq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004924
Colin Ian King8c9ff1a2017-04-20 15:07:18 +01004925 bfq_check_ioprio_change(bic, bio);
4926
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004927 bfq_bic_update_cgroup(bic, bio);
4928
Arianna Avanzini36eca892017-04-12 18:23:16 +02004929 bfqq = bfq_get_bfqq_handle_split(bfqd, bic, bio, false, is_sync,
4930 &new_queue);
4931
4932 if (likely(!new_queue)) {
4933 /* If the queue was seeky for too long, break it apart. */
4934 if (bfq_bfqq_coop(bfqq) && bfq_bfqq_split_coop(bfqq)) {
4935 bfq_log_bfqq(bfqd, bfqq, "breaking apart bfqq");
Arianna Avanzinie1b23242017-04-12 18:23:20 +02004936
4937 /* Update bic before losing reference to bfqq */
4938 if (bfq_bfqq_in_large_burst(bfqq))
4939 bic->saved_in_large_burst = true;
4940
Arianna Avanzini36eca892017-04-12 18:23:16 +02004941 bfqq = bfq_split_bfqq(bic, bfqq);
Paolo Valente6fa3e8d2017-04-12 18:23:21 +02004942 split = true;
Arianna Avanzini36eca892017-04-12 18:23:16 +02004943
4944 if (!bfqq)
4945 bfqq = bfq_get_bfqq_handle_split(bfqd, bic, bio,
4946 true, is_sync,
4947 NULL);
Paolo Valente13c931b2017-06-27 12:30:47 -06004948 else
4949 bfqq_already_existing = true;
Arianna Avanzini36eca892017-04-12 18:23:16 +02004950 }
Paolo Valenteaee69d72017-04-19 08:29:02 -06004951 }
4952
4953 bfqq->allocated++;
4954 bfqq->ref++;
4955 bfq_log_bfqq(bfqd, bfqq, "get_request %p: bfqq %p, %d",
4956 rq, bfqq, bfqq->ref);
4957
4958 rq->elv.priv[0] = bic;
4959 rq->elv.priv[1] = bfqq;
4960
Arianna Avanzini36eca892017-04-12 18:23:16 +02004961 /*
4962 * If a bfq_queue has only one process reference, it is owned
4963 * by only this bic: we can then set bfqq->bic = bic. in
4964 * addition, if the queue has also just been split, we have to
4965 * resume its state.
4966 */
4967 if (likely(bfqq != &bfqd->oom_bfqq) && bfqq_process_refs(bfqq) == 1) {
4968 bfqq->bic = bic;
Paolo Valente6fa3e8d2017-04-12 18:23:21 +02004969 if (split) {
Arianna Avanzini36eca892017-04-12 18:23:16 +02004970 /*
4971 * The queue has just been split from a shared
4972 * queue: restore the idle window and the
4973 * possible weight raising period.
4974 */
Paolo Valente13c931b2017-06-27 12:30:47 -06004975 bfq_bfqq_resume_state(bfqq, bfqd, bic,
4976 bfqq_already_existing);
Arianna Avanzini36eca892017-04-12 18:23:16 +02004977 }
4978 }
4979
Arianna Avanzinie1b23242017-04-12 18:23:20 +02004980 if (unlikely(bfq_bfqq_just_created(bfqq)))
4981 bfq_handle_burst(bfqd, bfqq);
4982
Paolo Valente18e5a572018-05-04 19:17:01 +02004983 return bfqq;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004984}
4985
4986static void bfq_idle_slice_timer_body(struct bfq_queue *bfqq)
4987{
4988 struct bfq_data *bfqd = bfqq->bfqd;
4989 enum bfqq_expiration reason;
4990 unsigned long flags;
4991
4992 spin_lock_irqsave(&bfqd->lock, flags);
4993 bfq_clear_bfqq_wait_request(bfqq);
4994
4995 if (bfqq != bfqd->in_service_queue) {
4996 spin_unlock_irqrestore(&bfqd->lock, flags);
4997 return;
4998 }
4999
5000 if (bfq_bfqq_budget_timeout(bfqq))
5001 /*
5002 * Also here the queue can be safely expired
5003 * for budget timeout without wasting
5004 * guarantees
5005 */
5006 reason = BFQQE_BUDGET_TIMEOUT;
5007 else if (bfqq->queued[0] == 0 && bfqq->queued[1] == 0)
5008 /*
5009 * The queue may not be empty upon timer expiration,
5010 * because we may not disable the timer when the
5011 * first request of the in-service queue arrives
5012 * during disk idling.
5013 */
5014 reason = BFQQE_TOO_IDLE;
5015 else
5016 goto schedule_dispatch;
5017
5018 bfq_bfqq_expire(bfqd, bfqq, true, reason);
5019
5020schedule_dispatch:
Paolo Valente6fa3e8d2017-04-12 18:23:21 +02005021 spin_unlock_irqrestore(&bfqd->lock, flags);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005022 bfq_schedule_dispatch(bfqd);
5023}
5024
5025/*
5026 * Handler of the expiration of the timer running if the in-service queue
5027 * is idling inside its time slice.
5028 */
5029static enum hrtimer_restart bfq_idle_slice_timer(struct hrtimer *timer)
5030{
5031 struct bfq_data *bfqd = container_of(timer, struct bfq_data,
5032 idle_slice_timer);
5033 struct bfq_queue *bfqq = bfqd->in_service_queue;
5034
5035 /*
5036 * Theoretical race here: the in-service queue can be NULL or
5037 * different from the queue that was idling if a new request
5038 * arrives for the current queue and there is a full dispatch
5039 * cycle that changes the in-service queue. This can hardly
5040 * happen, but in the worst case we just expire a queue too
5041 * early.
5042 */
5043 if (bfqq)
5044 bfq_idle_slice_timer_body(bfqq);
5045
5046 return HRTIMER_NORESTART;
5047}
5048
5049static void __bfq_put_async_bfqq(struct bfq_data *bfqd,
5050 struct bfq_queue **bfqq_ptr)
5051{
5052 struct bfq_queue *bfqq = *bfqq_ptr;
5053
5054 bfq_log(bfqd, "put_async_bfqq: %p", bfqq);
5055 if (bfqq) {
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005056 bfq_bfqq_move(bfqd, bfqq, bfqd->root_group);
5057
Paolo Valenteaee69d72017-04-19 08:29:02 -06005058 bfq_log_bfqq(bfqd, bfqq, "put_async_bfqq: putting %p, %d",
5059 bfqq, bfqq->ref);
5060 bfq_put_queue(bfqq);
5061 *bfqq_ptr = NULL;
5062 }
5063}
5064
5065/*
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005066 * Release all the bfqg references to its async queues. If we are
5067 * deallocating the group these queues may still contain requests, so
5068 * we reparent them to the root cgroup (i.e., the only one that will
5069 * exist for sure until all the requests on a device are gone).
Paolo Valenteaee69d72017-04-19 08:29:02 -06005070 */
Paolo Valenteea25da42017-04-19 08:48:24 -06005071void bfq_put_async_queues(struct bfq_data *bfqd, struct bfq_group *bfqg)
Paolo Valenteaee69d72017-04-19 08:29:02 -06005072{
5073 int i, j;
5074
5075 for (i = 0; i < 2; i++)
5076 for (j = 0; j < IOPRIO_BE_NR; j++)
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005077 __bfq_put_async_bfqq(bfqd, &bfqg->async_bfqq[i][j]);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005078
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005079 __bfq_put_async_bfqq(bfqd, &bfqg->async_idle_bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005080}
5081
Jens Axboef0635b82018-05-09 13:27:21 -06005082/*
5083 * See the comments on bfq_limit_depth for the purpose of
Jens Axboe483b7bf2018-05-09 15:26:55 -06005084 * the depths set in the function. Return minimum shallow depth we'll use.
Jens Axboef0635b82018-05-09 13:27:21 -06005085 */
Jens Axboe483b7bf2018-05-09 15:26:55 -06005086static unsigned int bfq_update_depths(struct bfq_data *bfqd,
5087 struct sbitmap_queue *bt)
Jens Axboef0635b82018-05-09 13:27:21 -06005088{
Jens Axboe483b7bf2018-05-09 15:26:55 -06005089 unsigned int i, j, min_shallow = UINT_MAX;
5090
Jens Axboef0635b82018-05-09 13:27:21 -06005091 /*
5092 * In-word depths if no bfq_queue is being weight-raised:
5093 * leaving 25% of tags only for sync reads.
5094 *
5095 * In next formulas, right-shift the value
Jens Axboebd7d4ef2018-05-09 15:25:22 -06005096 * (1U<<bt->sb.shift), instead of computing directly
5097 * (1U<<(bt->sb.shift - something)), to be robust against
5098 * any possible value of bt->sb.shift, without having to
Jens Axboef0635b82018-05-09 13:27:21 -06005099 * limit 'something'.
5100 */
5101 /* no more than 50% of tags for async I/O */
Jens Axboebd7d4ef2018-05-09 15:25:22 -06005102 bfqd->word_depths[0][0] = max((1U << bt->sb.shift) >> 1, 1U);
Jens Axboef0635b82018-05-09 13:27:21 -06005103 /*
5104 * no more than 75% of tags for sync writes (25% extra tags
5105 * w.r.t. async I/O, to prevent async I/O from starving sync
5106 * writes)
5107 */
Jens Axboebd7d4ef2018-05-09 15:25:22 -06005108 bfqd->word_depths[0][1] = max(((1U << bt->sb.shift) * 3) >> 2, 1U);
Jens Axboef0635b82018-05-09 13:27:21 -06005109
5110 /*
5111 * In-word depths in case some bfq_queue is being weight-
5112 * raised: leaving ~63% of tags for sync reads. This is the
5113 * highest percentage for which, in our tests, application
5114 * start-up times didn't suffer from any regression due to tag
5115 * shortage.
5116 */
5117 /* no more than ~18% of tags for async I/O */
Jens Axboebd7d4ef2018-05-09 15:25:22 -06005118 bfqd->word_depths[1][0] = max(((1U << bt->sb.shift) * 3) >> 4, 1U);
Jens Axboef0635b82018-05-09 13:27:21 -06005119 /* no more than ~37% of tags for sync writes (~20% extra tags) */
Jens Axboebd7d4ef2018-05-09 15:25:22 -06005120 bfqd->word_depths[1][1] = max(((1U << bt->sb.shift) * 6) >> 4, 1U);
Jens Axboe483b7bf2018-05-09 15:26:55 -06005121
5122 for (i = 0; i < 2; i++)
5123 for (j = 0; j < 2; j++)
5124 min_shallow = min(min_shallow, bfqd->word_depths[i][j]);
5125
5126 return min_shallow;
Jens Axboef0635b82018-05-09 13:27:21 -06005127}
5128
5129static int bfq_init_hctx(struct blk_mq_hw_ctx *hctx, unsigned int index)
5130{
5131 struct bfq_data *bfqd = hctx->queue->elevator->elevator_data;
5132 struct blk_mq_tags *tags = hctx->sched_tags;
Jens Axboe483b7bf2018-05-09 15:26:55 -06005133 unsigned int min_shallow;
Jens Axboef0635b82018-05-09 13:27:21 -06005134
Jens Axboe483b7bf2018-05-09 15:26:55 -06005135 min_shallow = bfq_update_depths(bfqd, &tags->bitmap_tags);
5136 sbitmap_queue_min_shallow_depth(&tags->bitmap_tags, min_shallow);
Jens Axboef0635b82018-05-09 13:27:21 -06005137 return 0;
5138}
5139
Paolo Valenteaee69d72017-04-19 08:29:02 -06005140static void bfq_exit_queue(struct elevator_queue *e)
5141{
5142 struct bfq_data *bfqd = e->elevator_data;
5143 struct bfq_queue *bfqq, *n;
5144
5145 hrtimer_cancel(&bfqd->idle_slice_timer);
5146
5147 spin_lock_irq(&bfqd->lock);
5148 list_for_each_entry_safe(bfqq, n, &bfqd->idle_list, bfqq_list)
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005149 bfq_deactivate_bfqq(bfqd, bfqq, false, false);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005150 spin_unlock_irq(&bfqd->lock);
5151
5152 hrtimer_cancel(&bfqd->idle_slice_timer);
5153
Jens Axboe8abef102018-01-09 12:20:51 -07005154#ifdef CONFIG_BFQ_GROUP_IOSCHED
Paolo Valente0d52af52018-01-09 10:27:59 +01005155 /* release oom-queue reference to root group */
5156 bfqg_and_blkg_put(bfqd->root_group);
5157
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005158 blkcg_deactivate_policy(bfqd->queue, &blkcg_policy_bfq);
5159#else
5160 spin_lock_irq(&bfqd->lock);
5161 bfq_put_async_queues(bfqd, bfqd->root_group);
5162 kfree(bfqd->root_group);
5163 spin_unlock_irq(&bfqd->lock);
5164#endif
5165
Paolo Valenteaee69d72017-04-19 08:29:02 -06005166 kfree(bfqd);
5167}
5168
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005169static void bfq_init_root_group(struct bfq_group *root_group,
5170 struct bfq_data *bfqd)
5171{
5172 int i;
5173
5174#ifdef CONFIG_BFQ_GROUP_IOSCHED
5175 root_group->entity.parent = NULL;
5176 root_group->my_entity = NULL;
5177 root_group->bfqd = bfqd;
5178#endif
Arianna Avanzini36eca892017-04-12 18:23:16 +02005179 root_group->rq_pos_tree = RB_ROOT;
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005180 for (i = 0; i < BFQ_IOPRIO_CLASSES; i++)
5181 root_group->sched_data.service_tree[i] = BFQ_SERVICE_TREE_INIT;
5182 root_group->sched_data.bfq_class_idle_last_service = jiffies;
5183}
5184
Paolo Valenteaee69d72017-04-19 08:29:02 -06005185static int bfq_init_queue(struct request_queue *q, struct elevator_type *e)
5186{
5187 struct bfq_data *bfqd;
5188 struct elevator_queue *eq;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005189
5190 eq = elevator_alloc(q, e);
5191 if (!eq)
5192 return -ENOMEM;
5193
5194 bfqd = kzalloc_node(sizeof(*bfqd), GFP_KERNEL, q->node);
5195 if (!bfqd) {
5196 kobject_put(&eq->kobj);
5197 return -ENOMEM;
5198 }
5199 eq->elevator_data = bfqd;
5200
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005201 spin_lock_irq(q->queue_lock);
5202 q->elevator = eq;
5203 spin_unlock_irq(q->queue_lock);
5204
Paolo Valenteaee69d72017-04-19 08:29:02 -06005205 /*
5206 * Our fallback bfqq if bfq_find_alloc_queue() runs into OOM issues.
5207 * Grab a permanent reference to it, so that the normal code flow
5208 * will not attempt to free it.
5209 */
5210 bfq_init_bfqq(bfqd, &bfqd->oom_bfqq, NULL, 1, 0);
5211 bfqd->oom_bfqq.ref++;
5212 bfqd->oom_bfqq.new_ioprio = BFQ_DEFAULT_QUEUE_IOPRIO;
5213 bfqd->oom_bfqq.new_ioprio_class = IOPRIO_CLASS_BE;
5214 bfqd->oom_bfqq.entity.new_weight =
5215 bfq_ioprio_to_weight(bfqd->oom_bfqq.new_ioprio);
Arianna Avanzinie1b23242017-04-12 18:23:20 +02005216
5217 /* oom_bfqq does not participate to bursts */
5218 bfq_clear_bfqq_just_created(&bfqd->oom_bfqq);
5219
Paolo Valenteaee69d72017-04-19 08:29:02 -06005220 /*
5221 * Trigger weight initialization, according to ioprio, at the
5222 * oom_bfqq's first activation. The oom_bfqq's ioprio and ioprio
5223 * class won't be changed any more.
5224 */
5225 bfqd->oom_bfqq.entity.prio_changed = 1;
5226
5227 bfqd->queue = q;
5228
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005229 INIT_LIST_HEAD(&bfqd->dispatch);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005230
5231 hrtimer_init(&bfqd->idle_slice_timer, CLOCK_MONOTONIC,
5232 HRTIMER_MODE_REL);
5233 bfqd->idle_slice_timer.function = bfq_idle_slice_timer;
5234
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +02005235 bfqd->queue_weights_tree = RB_ROOT;
5236 bfqd->group_weights_tree = RB_ROOT;
5237
Paolo Valenteaee69d72017-04-19 08:29:02 -06005238 INIT_LIST_HEAD(&bfqd->active_list);
5239 INIT_LIST_HEAD(&bfqd->idle_list);
Arianna Avanzinie1b23242017-04-12 18:23:20 +02005240 INIT_HLIST_HEAD(&bfqd->burst_list);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005241
5242 bfqd->hw_tag = -1;
5243
5244 bfqd->bfq_max_budget = bfq_default_max_budget;
5245
5246 bfqd->bfq_fifo_expire[0] = bfq_fifo_expire[0];
5247 bfqd->bfq_fifo_expire[1] = bfq_fifo_expire[1];
5248 bfqd->bfq_back_max = bfq_back_max;
5249 bfqd->bfq_back_penalty = bfq_back_penalty;
5250 bfqd->bfq_slice_idle = bfq_slice_idle;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005251 bfqd->bfq_timeout = bfq_timeout;
5252
5253 bfqd->bfq_requests_within_timer = 120;
5254
Arianna Avanzinie1b23242017-04-12 18:23:20 +02005255 bfqd->bfq_large_burst_thresh = 8;
5256 bfqd->bfq_burst_interval = msecs_to_jiffies(180);
5257
Paolo Valente44e44a12017-04-12 18:23:12 +02005258 bfqd->low_latency = true;
5259
5260 /*
5261 * Trade-off between responsiveness and fairness.
5262 */
5263 bfqd->bfq_wr_coeff = 30;
Paolo Valente77b7dce2017-04-12 18:23:13 +02005264 bfqd->bfq_wr_rt_max_time = msecs_to_jiffies(300);
Paolo Valente44e44a12017-04-12 18:23:12 +02005265 bfqd->bfq_wr_max_time = 0;
5266 bfqd->bfq_wr_min_idle_time = msecs_to_jiffies(2000);
5267 bfqd->bfq_wr_min_inter_arr_async = msecs_to_jiffies(500);
Paolo Valente77b7dce2017-04-12 18:23:13 +02005268 bfqd->bfq_wr_max_softrt_rate = 7000; /*
5269 * Approximate rate required
5270 * to playback or record a
5271 * high-definition compressed
5272 * video.
5273 */
Paolo Valentecfd69712017-04-12 18:23:15 +02005274 bfqd->wr_busy_queues = 0;
Paolo Valente44e44a12017-04-12 18:23:12 +02005275
5276 /*
5277 * Begin by assuming, optimistically, that the device is a
5278 * high-speed one, and that its peak rate is equal to 2/3 of
5279 * the highest reference rate.
5280 */
5281 bfqd->RT_prod = R_fast[blk_queue_nonrot(bfqd->queue)] *
5282 T_fast[blk_queue_nonrot(bfqd->queue)];
5283 bfqd->peak_rate = R_fast[blk_queue_nonrot(bfqd->queue)] * 2 / 3;
5284 bfqd->device_speed = BFQ_BFQD_FAST;
5285
Paolo Valenteaee69d72017-04-19 08:29:02 -06005286 spin_lock_init(&bfqd->lock);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005287
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005288 /*
5289 * The invocation of the next bfq_create_group_hierarchy
5290 * function is the head of a chain of function calls
5291 * (bfq_create_group_hierarchy->blkcg_activate_policy->
5292 * blk_mq_freeze_queue) that may lead to the invocation of the
5293 * has_work hook function. For this reason,
5294 * bfq_create_group_hierarchy is invoked only after all
5295 * scheduler data has been initialized, apart from the fields
5296 * that can be initialized only after invoking
5297 * bfq_create_group_hierarchy. This, in particular, enables
5298 * has_work to correctly return false. Of course, to avoid
5299 * other inconsistencies, the blk-mq stack must then refrain
5300 * from invoking further scheduler hooks before this init
5301 * function is finished.
5302 */
5303 bfqd->root_group = bfq_create_group_hierarchy(bfqd, q->node);
5304 if (!bfqd->root_group)
5305 goto out_free;
5306 bfq_init_root_group(bfqd->root_group, bfqd);
5307 bfq_init_entity(&bfqd->oom_bfqq.entity, bfqd->root_group);
5308
Luca Micciob5dc5d42017-10-09 16:27:21 +02005309 wbt_disable_default(q);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005310 return 0;
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005311
5312out_free:
5313 kfree(bfqd);
5314 kobject_put(&eq->kobj);
5315 return -ENOMEM;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005316}
5317
5318static void bfq_slab_kill(void)
5319{
5320 kmem_cache_destroy(bfq_pool);
5321}
5322
5323static int __init bfq_slab_setup(void)
5324{
5325 bfq_pool = KMEM_CACHE(bfq_queue, 0);
5326 if (!bfq_pool)
5327 return -ENOMEM;
5328 return 0;
5329}
5330
5331static ssize_t bfq_var_show(unsigned int var, char *page)
5332{
5333 return sprintf(page, "%u\n", var);
5334}
5335
Bart Van Assche2f791362017-08-30 11:42:09 -07005336static int bfq_var_store(unsigned long *var, const char *page)
Paolo Valenteaee69d72017-04-19 08:29:02 -06005337{
5338 unsigned long new_val;
5339 int ret = kstrtoul(page, 10, &new_val);
5340
Bart Van Assche2f791362017-08-30 11:42:09 -07005341 if (ret)
5342 return ret;
5343 *var = new_val;
5344 return 0;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005345}
5346
5347#define SHOW_FUNCTION(__FUNC, __VAR, __CONV) \
5348static ssize_t __FUNC(struct elevator_queue *e, char *page) \
5349{ \
5350 struct bfq_data *bfqd = e->elevator_data; \
5351 u64 __data = __VAR; \
5352 if (__CONV == 1) \
5353 __data = jiffies_to_msecs(__data); \
5354 else if (__CONV == 2) \
5355 __data = div_u64(__data, NSEC_PER_MSEC); \
5356 return bfq_var_show(__data, (page)); \
5357}
5358SHOW_FUNCTION(bfq_fifo_expire_sync_show, bfqd->bfq_fifo_expire[1], 2);
5359SHOW_FUNCTION(bfq_fifo_expire_async_show, bfqd->bfq_fifo_expire[0], 2);
5360SHOW_FUNCTION(bfq_back_seek_max_show, bfqd->bfq_back_max, 0);
5361SHOW_FUNCTION(bfq_back_seek_penalty_show, bfqd->bfq_back_penalty, 0);
5362SHOW_FUNCTION(bfq_slice_idle_show, bfqd->bfq_slice_idle, 2);
5363SHOW_FUNCTION(bfq_max_budget_show, bfqd->bfq_user_max_budget, 0);
5364SHOW_FUNCTION(bfq_timeout_sync_show, bfqd->bfq_timeout, 1);
5365SHOW_FUNCTION(bfq_strict_guarantees_show, bfqd->strict_guarantees, 0);
Paolo Valente44e44a12017-04-12 18:23:12 +02005366SHOW_FUNCTION(bfq_low_latency_show, bfqd->low_latency, 0);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005367#undef SHOW_FUNCTION
5368
5369#define USEC_SHOW_FUNCTION(__FUNC, __VAR) \
5370static ssize_t __FUNC(struct elevator_queue *e, char *page) \
5371{ \
5372 struct bfq_data *bfqd = e->elevator_data; \
5373 u64 __data = __VAR; \
5374 __data = div_u64(__data, NSEC_PER_USEC); \
5375 return bfq_var_show(__data, (page)); \
5376}
5377USEC_SHOW_FUNCTION(bfq_slice_idle_us_show, bfqd->bfq_slice_idle);
5378#undef USEC_SHOW_FUNCTION
5379
5380#define STORE_FUNCTION(__FUNC, __PTR, MIN, MAX, __CONV) \
5381static ssize_t \
5382__FUNC(struct elevator_queue *e, const char *page, size_t count) \
5383{ \
5384 struct bfq_data *bfqd = e->elevator_data; \
Bart Van Assche1530486c2017-08-30 11:42:10 -07005385 unsigned long __data, __min = (MIN), __max = (MAX); \
Bart Van Assche2f791362017-08-30 11:42:09 -07005386 int ret; \
5387 \
5388 ret = bfq_var_store(&__data, (page)); \
5389 if (ret) \
5390 return ret; \
Bart Van Assche1530486c2017-08-30 11:42:10 -07005391 if (__data < __min) \
5392 __data = __min; \
5393 else if (__data > __max) \
5394 __data = __max; \
Paolo Valenteaee69d72017-04-19 08:29:02 -06005395 if (__CONV == 1) \
5396 *(__PTR) = msecs_to_jiffies(__data); \
5397 else if (__CONV == 2) \
5398 *(__PTR) = (u64)__data * NSEC_PER_MSEC; \
5399 else \
5400 *(__PTR) = __data; \
weiping zhang235f8da2017-08-25 01:11:33 +08005401 return count; \
Paolo Valenteaee69d72017-04-19 08:29:02 -06005402}
5403STORE_FUNCTION(bfq_fifo_expire_sync_store, &bfqd->bfq_fifo_expire[1], 1,
5404 INT_MAX, 2);
5405STORE_FUNCTION(bfq_fifo_expire_async_store, &bfqd->bfq_fifo_expire[0], 1,
5406 INT_MAX, 2);
5407STORE_FUNCTION(bfq_back_seek_max_store, &bfqd->bfq_back_max, 0, INT_MAX, 0);
5408STORE_FUNCTION(bfq_back_seek_penalty_store, &bfqd->bfq_back_penalty, 1,
5409 INT_MAX, 0);
5410STORE_FUNCTION(bfq_slice_idle_store, &bfqd->bfq_slice_idle, 0, INT_MAX, 2);
5411#undef STORE_FUNCTION
5412
5413#define USEC_STORE_FUNCTION(__FUNC, __PTR, MIN, MAX) \
5414static ssize_t __FUNC(struct elevator_queue *e, const char *page, size_t count)\
5415{ \
5416 struct bfq_data *bfqd = e->elevator_data; \
Bart Van Assche1530486c2017-08-30 11:42:10 -07005417 unsigned long __data, __min = (MIN), __max = (MAX); \
Bart Van Assche2f791362017-08-30 11:42:09 -07005418 int ret; \
5419 \
5420 ret = bfq_var_store(&__data, (page)); \
5421 if (ret) \
5422 return ret; \
Bart Van Assche1530486c2017-08-30 11:42:10 -07005423 if (__data < __min) \
5424 __data = __min; \
5425 else if (__data > __max) \
5426 __data = __max; \
Paolo Valenteaee69d72017-04-19 08:29:02 -06005427 *(__PTR) = (u64)__data * NSEC_PER_USEC; \
weiping zhang235f8da2017-08-25 01:11:33 +08005428 return count; \
Paolo Valenteaee69d72017-04-19 08:29:02 -06005429}
5430USEC_STORE_FUNCTION(bfq_slice_idle_us_store, &bfqd->bfq_slice_idle, 0,
5431 UINT_MAX);
5432#undef USEC_STORE_FUNCTION
5433
Paolo Valenteaee69d72017-04-19 08:29:02 -06005434static ssize_t bfq_max_budget_store(struct elevator_queue *e,
5435 const char *page, size_t count)
5436{
5437 struct bfq_data *bfqd = e->elevator_data;
Bart Van Assche2f791362017-08-30 11:42:09 -07005438 unsigned long __data;
5439 int ret;
weiping zhang235f8da2017-08-25 01:11:33 +08005440
Bart Van Assche2f791362017-08-30 11:42:09 -07005441 ret = bfq_var_store(&__data, (page));
5442 if (ret)
5443 return ret;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005444
5445 if (__data == 0)
Paolo Valenteab0e43e2017-04-12 18:23:10 +02005446 bfqd->bfq_max_budget = bfq_calc_max_budget(bfqd);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005447 else {
5448 if (__data > INT_MAX)
5449 __data = INT_MAX;
5450 bfqd->bfq_max_budget = __data;
5451 }
5452
5453 bfqd->bfq_user_max_budget = __data;
5454
weiping zhang235f8da2017-08-25 01:11:33 +08005455 return count;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005456}
5457
5458/*
5459 * Leaving this name to preserve name compatibility with cfq
5460 * parameters, but this timeout is used for both sync and async.
5461 */
5462static ssize_t bfq_timeout_sync_store(struct elevator_queue *e,
5463 const char *page, size_t count)
5464{
5465 struct bfq_data *bfqd = e->elevator_data;
Bart Van Assche2f791362017-08-30 11:42:09 -07005466 unsigned long __data;
5467 int ret;
weiping zhang235f8da2017-08-25 01:11:33 +08005468
Bart Van Assche2f791362017-08-30 11:42:09 -07005469 ret = bfq_var_store(&__data, (page));
5470 if (ret)
5471 return ret;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005472
5473 if (__data < 1)
5474 __data = 1;
5475 else if (__data > INT_MAX)
5476 __data = INT_MAX;
5477
5478 bfqd->bfq_timeout = msecs_to_jiffies(__data);
5479 if (bfqd->bfq_user_max_budget == 0)
Paolo Valenteab0e43e2017-04-12 18:23:10 +02005480 bfqd->bfq_max_budget = bfq_calc_max_budget(bfqd);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005481
weiping zhang235f8da2017-08-25 01:11:33 +08005482 return count;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005483}
5484
5485static ssize_t bfq_strict_guarantees_store(struct elevator_queue *e,
5486 const char *page, size_t count)
5487{
5488 struct bfq_data *bfqd = e->elevator_data;
Bart Van Assche2f791362017-08-30 11:42:09 -07005489 unsigned long __data;
5490 int ret;
weiping zhang235f8da2017-08-25 01:11:33 +08005491
Bart Van Assche2f791362017-08-30 11:42:09 -07005492 ret = bfq_var_store(&__data, (page));
5493 if (ret)
5494 return ret;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005495
5496 if (__data > 1)
5497 __data = 1;
5498 if (!bfqd->strict_guarantees && __data == 1
5499 && bfqd->bfq_slice_idle < 8 * NSEC_PER_MSEC)
5500 bfqd->bfq_slice_idle = 8 * NSEC_PER_MSEC;
5501
5502 bfqd->strict_guarantees = __data;
5503
weiping zhang235f8da2017-08-25 01:11:33 +08005504 return count;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005505}
5506
Paolo Valente44e44a12017-04-12 18:23:12 +02005507static ssize_t bfq_low_latency_store(struct elevator_queue *e,
5508 const char *page, size_t count)
5509{
5510 struct bfq_data *bfqd = e->elevator_data;
Bart Van Assche2f791362017-08-30 11:42:09 -07005511 unsigned long __data;
5512 int ret;
weiping zhang235f8da2017-08-25 01:11:33 +08005513
Bart Van Assche2f791362017-08-30 11:42:09 -07005514 ret = bfq_var_store(&__data, (page));
5515 if (ret)
5516 return ret;
Paolo Valente44e44a12017-04-12 18:23:12 +02005517
5518 if (__data > 1)
5519 __data = 1;
5520 if (__data == 0 && bfqd->low_latency != 0)
5521 bfq_end_wr(bfqd);
5522 bfqd->low_latency = __data;
5523
weiping zhang235f8da2017-08-25 01:11:33 +08005524 return count;
Paolo Valente44e44a12017-04-12 18:23:12 +02005525}
5526
Paolo Valenteaee69d72017-04-19 08:29:02 -06005527#define BFQ_ATTR(name) \
5528 __ATTR(name, 0644, bfq_##name##_show, bfq_##name##_store)
5529
5530static struct elv_fs_entry bfq_attrs[] = {
5531 BFQ_ATTR(fifo_expire_sync),
5532 BFQ_ATTR(fifo_expire_async),
5533 BFQ_ATTR(back_seek_max),
5534 BFQ_ATTR(back_seek_penalty),
5535 BFQ_ATTR(slice_idle),
5536 BFQ_ATTR(slice_idle_us),
5537 BFQ_ATTR(max_budget),
5538 BFQ_ATTR(timeout_sync),
5539 BFQ_ATTR(strict_guarantees),
Paolo Valente44e44a12017-04-12 18:23:12 +02005540 BFQ_ATTR(low_latency),
Paolo Valenteaee69d72017-04-19 08:29:02 -06005541 __ATTR_NULL
5542};
5543
5544static struct elevator_type iosched_bfq_mq = {
5545 .ops.mq = {
Paolo Valentea52a69e2018-01-13 12:05:17 +01005546 .limit_depth = bfq_limit_depth,
Christoph Hellwig5bbf4e52017-06-16 18:15:26 +02005547 .prepare_request = bfq_prepare_request,
Paolo Valentea7877392018-02-07 22:19:20 +01005548 .requeue_request = bfq_finish_requeue_request,
5549 .finish_request = bfq_finish_requeue_request,
Paolo Valenteaee69d72017-04-19 08:29:02 -06005550 .exit_icq = bfq_exit_icq,
5551 .insert_requests = bfq_insert_requests,
5552 .dispatch_request = bfq_dispatch_request,
5553 .next_request = elv_rb_latter_request,
5554 .former_request = elv_rb_former_request,
5555 .allow_merge = bfq_allow_bio_merge,
5556 .bio_merge = bfq_bio_merge,
5557 .request_merge = bfq_request_merge,
5558 .requests_merged = bfq_requests_merged,
5559 .request_merged = bfq_request_merged,
5560 .has_work = bfq_has_work,
Jens Axboef0635b82018-05-09 13:27:21 -06005561 .init_hctx = bfq_init_hctx,
Paolo Valenteaee69d72017-04-19 08:29:02 -06005562 .init_sched = bfq_init_queue,
5563 .exit_sched = bfq_exit_queue,
5564 },
5565
5566 .uses_mq = true,
5567 .icq_size = sizeof(struct bfq_io_cq),
5568 .icq_align = __alignof__(struct bfq_io_cq),
5569 .elevator_attrs = bfq_attrs,
5570 .elevator_name = "bfq",
5571 .elevator_owner = THIS_MODULE,
5572};
Ben Hutchings26b4cf22017-08-13 18:02:19 +01005573MODULE_ALIAS("bfq-iosched");
Paolo Valenteaee69d72017-04-19 08:29:02 -06005574
5575static int __init bfq_init(void)
5576{
5577 int ret;
5578
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005579#ifdef CONFIG_BFQ_GROUP_IOSCHED
5580 ret = blkcg_policy_register(&blkcg_policy_bfq);
5581 if (ret)
5582 return ret;
5583#endif
5584
Paolo Valenteaee69d72017-04-19 08:29:02 -06005585 ret = -ENOMEM;
5586 if (bfq_slab_setup())
5587 goto err_pol_unreg;
5588
Paolo Valente44e44a12017-04-12 18:23:12 +02005589 /*
5590 * Times to load large popular applications for the typical
5591 * systems installed on the reference devices (see the
5592 * comments before the definitions of the next two
5593 * arrays). Actually, we use slightly slower values, as the
5594 * estimated peak rate tends to be smaller than the actual
5595 * peak rate. The reason for this last fact is that estimates
5596 * are computed over much shorter time intervals than the long
5597 * intervals typically used for benchmarking. Why? First, to
5598 * adapt more quickly to variations. Second, because an I/O
5599 * scheduler cannot rely on a peak-rate-evaluation workload to
5600 * be run for a long time.
5601 */
5602 T_slow[0] = msecs_to_jiffies(3500); /* actually 4 sec */
5603 T_slow[1] = msecs_to_jiffies(6000); /* actually 6.5 sec */
5604 T_fast[0] = msecs_to_jiffies(7000); /* actually 8 sec */
5605 T_fast[1] = msecs_to_jiffies(2500); /* actually 3 sec */
5606
5607 /*
5608 * Thresholds that determine the switch between speed classes
5609 * (see the comments before the definition of the array
5610 * device_speed_thresh). These thresholds are biased towards
5611 * transitions to the fast class. This is safer than the
5612 * opposite bias. In fact, a wrong transition to the slow
5613 * class results in short weight-raising periods, because the
5614 * speed of the device then tends to be higher that the
5615 * reference peak rate. On the opposite end, a wrong
5616 * transition to the fast class tends to increase
5617 * weight-raising periods, because of the opposite reason.
5618 */
5619 device_speed_thresh[0] = (4 * R_slow[0]) / 3;
5620 device_speed_thresh[1] = (4 * R_slow[1]) / 3;
5621
Paolo Valenteaee69d72017-04-19 08:29:02 -06005622 ret = elv_register(&iosched_bfq_mq);
5623 if (ret)
weiping zhang37dcd652017-08-19 00:37:20 +08005624 goto slab_kill;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005625
5626 return 0;
5627
weiping zhang37dcd652017-08-19 00:37:20 +08005628slab_kill:
5629 bfq_slab_kill();
Paolo Valenteaee69d72017-04-19 08:29:02 -06005630err_pol_unreg:
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005631#ifdef CONFIG_BFQ_GROUP_IOSCHED
5632 blkcg_policy_unregister(&blkcg_policy_bfq);
5633#endif
Paolo Valenteaee69d72017-04-19 08:29:02 -06005634 return ret;
5635}
5636
5637static void __exit bfq_exit(void)
5638{
5639 elv_unregister(&iosched_bfq_mq);
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005640#ifdef CONFIG_BFQ_GROUP_IOSCHED
5641 blkcg_policy_unregister(&blkcg_policy_bfq);
5642#endif
Paolo Valenteaee69d72017-04-19 08:29:02 -06005643 bfq_slab_kill();
5644}
5645
5646module_init(bfq_init);
5647module_exit(bfq_exit);
5648
5649MODULE_AUTHOR("Paolo Valente");
5650MODULE_LICENSE("GPL");
5651MODULE_DESCRIPTION("MQ Budget Fair Queueing I/O Scheduler");