blob: 02dd4c836936caab7087095a558e1d770e965511 [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
1851 /*
1852 * If next and rq belong to the same bfq_queue and next is older
1853 * than rq, then reposition rq in the fifo (by substituting next
1854 * with rq). Otherwise, if next and rq belong to different
1855 * bfq_queues, never reposition rq: in fact, we would have to
1856 * reposition it with respect to next's position in its own fifo,
1857 * which would most certainly be too expensive with respect to
1858 * the benefits.
1859 */
1860 if (bfqq == next_bfqq &&
1861 !list_empty(&rq->queuelist) && !list_empty(&next->queuelist) &&
1862 next->fifo_time < rq->fifo_time) {
1863 list_del_init(&rq->queuelist);
1864 list_replace_init(&next->queuelist, &rq->queuelist);
1865 rq->fifo_time = next->fifo_time;
1866 }
1867
1868 if (bfqq->next_rq == next)
1869 bfqq->next_rq = rq;
1870
1871 bfq_remove_request(q, next);
Luca Miccio614822f2017-11-13 07:34:08 +01001872 bfqg_stats_update_io_remove(bfqq_group(bfqq), next->cmd_flags);
Paolo Valenteaee69d72017-04-19 08:29:02 -06001873
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02001874end:
1875 bfqg_stats_update_io_merged(bfqq_group(bfqq), next->cmd_flags);
Paolo Valenteaee69d72017-04-19 08:29:02 -06001876}
1877
Paolo Valente44e44a12017-04-12 18:23:12 +02001878/* Must be called with bfqq != NULL */
1879static void bfq_bfqq_end_wr(struct bfq_queue *bfqq)
1880{
Paolo Valentecfd69712017-04-12 18:23:15 +02001881 if (bfq_bfqq_busy(bfqq))
1882 bfqq->bfqd->wr_busy_queues--;
Paolo Valente44e44a12017-04-12 18:23:12 +02001883 bfqq->wr_coeff = 1;
1884 bfqq->wr_cur_max_time = 0;
Paolo Valente77b7dce2017-04-12 18:23:13 +02001885 bfqq->last_wr_start_finish = jiffies;
Paolo Valente44e44a12017-04-12 18:23:12 +02001886 /*
1887 * Trigger a weight change on the next invocation of
1888 * __bfq_entity_update_weight_prio.
1889 */
1890 bfqq->entity.prio_changed = 1;
1891}
1892
Paolo Valenteea25da42017-04-19 08:48:24 -06001893void bfq_end_wr_async_queues(struct bfq_data *bfqd,
1894 struct bfq_group *bfqg)
Paolo Valente44e44a12017-04-12 18:23:12 +02001895{
1896 int i, j;
1897
1898 for (i = 0; i < 2; i++)
1899 for (j = 0; j < IOPRIO_BE_NR; j++)
1900 if (bfqg->async_bfqq[i][j])
1901 bfq_bfqq_end_wr(bfqg->async_bfqq[i][j]);
1902 if (bfqg->async_idle_bfqq)
1903 bfq_bfqq_end_wr(bfqg->async_idle_bfqq);
1904}
1905
1906static void bfq_end_wr(struct bfq_data *bfqd)
1907{
1908 struct bfq_queue *bfqq;
1909
1910 spin_lock_irq(&bfqd->lock);
1911
1912 list_for_each_entry(bfqq, &bfqd->active_list, bfqq_list)
1913 bfq_bfqq_end_wr(bfqq);
1914 list_for_each_entry(bfqq, &bfqd->idle_list, bfqq_list)
1915 bfq_bfqq_end_wr(bfqq);
1916 bfq_end_wr_async(bfqd);
1917
1918 spin_unlock_irq(&bfqd->lock);
1919}
1920
Arianna Avanzini36eca892017-04-12 18:23:16 +02001921static sector_t bfq_io_struct_pos(void *io_struct, bool request)
1922{
1923 if (request)
1924 return blk_rq_pos(io_struct);
1925 else
1926 return ((struct bio *)io_struct)->bi_iter.bi_sector;
1927}
1928
1929static int bfq_rq_close_to_sector(void *io_struct, bool request,
1930 sector_t sector)
1931{
1932 return abs(bfq_io_struct_pos(io_struct, request) - sector) <=
1933 BFQQ_CLOSE_THR;
1934}
1935
1936static struct bfq_queue *bfqq_find_close(struct bfq_data *bfqd,
1937 struct bfq_queue *bfqq,
1938 sector_t sector)
1939{
1940 struct rb_root *root = &bfq_bfqq_to_bfqg(bfqq)->rq_pos_tree;
1941 struct rb_node *parent, *node;
1942 struct bfq_queue *__bfqq;
1943
1944 if (RB_EMPTY_ROOT(root))
1945 return NULL;
1946
1947 /*
1948 * First, if we find a request starting at the end of the last
1949 * request, choose it.
1950 */
1951 __bfqq = bfq_rq_pos_tree_lookup(bfqd, root, sector, &parent, NULL);
1952 if (__bfqq)
1953 return __bfqq;
1954
1955 /*
1956 * If the exact sector wasn't found, the parent of the NULL leaf
1957 * will contain the closest sector (rq_pos_tree sorted by
1958 * next_request position).
1959 */
1960 __bfqq = rb_entry(parent, struct bfq_queue, pos_node);
1961 if (bfq_rq_close_to_sector(__bfqq->next_rq, true, sector))
1962 return __bfqq;
1963
1964 if (blk_rq_pos(__bfqq->next_rq) < sector)
1965 node = rb_next(&__bfqq->pos_node);
1966 else
1967 node = rb_prev(&__bfqq->pos_node);
1968 if (!node)
1969 return NULL;
1970
1971 __bfqq = rb_entry(node, struct bfq_queue, pos_node);
1972 if (bfq_rq_close_to_sector(__bfqq->next_rq, true, sector))
1973 return __bfqq;
1974
1975 return NULL;
1976}
1977
1978static struct bfq_queue *bfq_find_close_cooperator(struct bfq_data *bfqd,
1979 struct bfq_queue *cur_bfqq,
1980 sector_t sector)
1981{
1982 struct bfq_queue *bfqq;
1983
1984 /*
1985 * We shall notice if some of the queues are cooperating,
1986 * e.g., working closely on the same area of the device. In
1987 * that case, we can group them together and: 1) don't waste
1988 * time idling, and 2) serve the union of their requests in
1989 * the best possible order for throughput.
1990 */
1991 bfqq = bfqq_find_close(bfqd, cur_bfqq, sector);
1992 if (!bfqq || bfqq == cur_bfqq)
1993 return NULL;
1994
1995 return bfqq;
1996}
1997
1998static struct bfq_queue *
1999bfq_setup_merge(struct bfq_queue *bfqq, struct bfq_queue *new_bfqq)
2000{
2001 int process_refs, new_process_refs;
2002 struct bfq_queue *__bfqq;
2003
2004 /*
2005 * If there are no process references on the new_bfqq, then it is
2006 * unsafe to follow the ->new_bfqq chain as other bfqq's in the chain
2007 * may have dropped their last reference (not just their last process
2008 * reference).
2009 */
2010 if (!bfqq_process_refs(new_bfqq))
2011 return NULL;
2012
2013 /* Avoid a circular list and skip interim queue merges. */
2014 while ((__bfqq = new_bfqq->new_bfqq)) {
2015 if (__bfqq == bfqq)
2016 return NULL;
2017 new_bfqq = __bfqq;
2018 }
2019
2020 process_refs = bfqq_process_refs(bfqq);
2021 new_process_refs = bfqq_process_refs(new_bfqq);
2022 /*
2023 * If the process for the bfqq has gone away, there is no
2024 * sense in merging the queues.
2025 */
2026 if (process_refs == 0 || new_process_refs == 0)
2027 return NULL;
2028
2029 bfq_log_bfqq(bfqq->bfqd, bfqq, "scheduling merge with queue %d",
2030 new_bfqq->pid);
2031
2032 /*
2033 * Merging is just a redirection: the requests of the process
2034 * owning one of the two queues are redirected to the other queue.
2035 * The latter queue, in its turn, is set as shared if this is the
2036 * first time that the requests of some process are redirected to
2037 * it.
2038 *
Paolo Valente6fa3e8d2017-04-12 18:23:21 +02002039 * We redirect bfqq to new_bfqq and not the opposite, because
2040 * we are in the context of the process owning bfqq, thus we
2041 * have the io_cq of this process. So we can immediately
2042 * configure this io_cq to redirect the requests of the
2043 * process to new_bfqq. In contrast, the io_cq of new_bfqq is
2044 * not available any more (new_bfqq->bic == NULL).
Arianna Avanzini36eca892017-04-12 18:23:16 +02002045 *
Paolo Valente6fa3e8d2017-04-12 18:23:21 +02002046 * Anyway, even in case new_bfqq coincides with the in-service
2047 * queue, redirecting requests the in-service queue is the
2048 * best option, as we feed the in-service queue with new
2049 * requests close to the last request served and, by doing so,
2050 * are likely to increase the throughput.
Arianna Avanzini36eca892017-04-12 18:23:16 +02002051 */
2052 bfqq->new_bfqq = new_bfqq;
2053 new_bfqq->ref += process_refs;
2054 return new_bfqq;
2055}
2056
2057static bool bfq_may_be_close_cooperator(struct bfq_queue *bfqq,
2058 struct bfq_queue *new_bfqq)
2059{
Paolo Valente7b8fa3b2017-12-20 12:38:33 +01002060 if (bfq_too_late_for_merging(new_bfqq))
2061 return false;
2062
Arianna Avanzini36eca892017-04-12 18:23:16 +02002063 if (bfq_class_idle(bfqq) || bfq_class_idle(new_bfqq) ||
2064 (bfqq->ioprio_class != new_bfqq->ioprio_class))
2065 return false;
2066
2067 /*
2068 * If either of the queues has already been detected as seeky,
2069 * then merging it with the other queue is unlikely to lead to
2070 * sequential I/O.
2071 */
2072 if (BFQQ_SEEKY(bfqq) || BFQQ_SEEKY(new_bfqq))
2073 return false;
2074
2075 /*
2076 * Interleaved I/O is known to be done by (some) applications
2077 * only for reads, so it does not make sense to merge async
2078 * queues.
2079 */
2080 if (!bfq_bfqq_sync(bfqq) || !bfq_bfqq_sync(new_bfqq))
2081 return false;
2082
2083 return true;
2084}
2085
2086/*
Arianna Avanzini36eca892017-04-12 18:23:16 +02002087 * Attempt to schedule a merge of bfqq with the currently in-service
2088 * queue or with a close queue among the scheduled queues. Return
2089 * NULL if no merge was scheduled, a pointer to the shared bfq_queue
2090 * structure otherwise.
2091 *
2092 * The OOM queue is not allowed to participate to cooperation: in fact, since
2093 * the requests temporarily redirected to the OOM queue could be redirected
2094 * again to dedicated queues at any time, the state needed to correctly
2095 * handle merging with the OOM queue would be quite complex and expensive
2096 * to maintain. Besides, in such a critical condition as an out of memory,
2097 * the benefits of queue merging may be little relevant, or even negligible.
2098 *
Arianna Avanzini36eca892017-04-12 18:23:16 +02002099 * WARNING: queue merging may impair fairness among non-weight raised
2100 * queues, for at least two reasons: 1) the original weight of a
2101 * merged queue may change during the merged state, 2) even being the
2102 * weight the same, a merged queue may be bloated with many more
2103 * requests than the ones produced by its originally-associated
2104 * process.
2105 */
2106static struct bfq_queue *
2107bfq_setup_cooperator(struct bfq_data *bfqd, struct bfq_queue *bfqq,
2108 void *io_struct, bool request)
2109{
2110 struct bfq_queue *in_service_bfqq, *new_bfqq;
2111
Paolo Valente7b8fa3b2017-12-20 12:38:33 +01002112 /*
2113 * Prevent bfqq from being merged if it has been created too
2114 * long ago. The idea is that true cooperating processes, and
2115 * thus their associated bfq_queues, are supposed to be
2116 * created shortly after each other. This is the case, e.g.,
2117 * for KVM/QEMU and dump I/O threads. Basing on this
2118 * assumption, the following filtering greatly reduces the
2119 * probability that two non-cooperating processes, which just
2120 * happen to do close I/O for some short time interval, have
2121 * their queues merged by mistake.
2122 */
2123 if (bfq_too_late_for_merging(bfqq))
2124 return NULL;
2125
Arianna Avanzini36eca892017-04-12 18:23:16 +02002126 if (bfqq->new_bfqq)
2127 return bfqq->new_bfqq;
2128
Angelo Ruocco4403e4e2017-12-20 12:38:34 +01002129 if (!io_struct || unlikely(bfqq == &bfqd->oom_bfqq))
Arianna Avanzini36eca892017-04-12 18:23:16 +02002130 return NULL;
2131
2132 /* If there is only one backlogged queue, don't search. */
2133 if (bfqd->busy_queues == 1)
2134 return NULL;
2135
2136 in_service_bfqq = bfqd->in_service_queue;
2137
Angelo Ruocco4403e4e2017-12-20 12:38:34 +01002138 if (in_service_bfqq && in_service_bfqq != bfqq &&
2139 likely(in_service_bfqq != &bfqd->oom_bfqq) &&
2140 bfq_rq_close_to_sector(io_struct, request, bfqd->last_position) &&
Arianna Avanzini36eca892017-04-12 18:23:16 +02002141 bfqq->entity.parent == in_service_bfqq->entity.parent &&
2142 bfq_may_be_close_cooperator(bfqq, in_service_bfqq)) {
2143 new_bfqq = bfq_setup_merge(bfqq, in_service_bfqq);
2144 if (new_bfqq)
2145 return new_bfqq;
2146 }
2147 /*
2148 * Check whether there is a cooperator among currently scheduled
2149 * queues. The only thing we need is that the bio/request is not
2150 * NULL, as we need it to establish whether a cooperator exists.
2151 */
Arianna Avanzini36eca892017-04-12 18:23:16 +02002152 new_bfqq = bfq_find_close_cooperator(bfqd, bfqq,
2153 bfq_io_struct_pos(io_struct, request));
2154
Angelo Ruocco4403e4e2017-12-20 12:38:34 +01002155 if (new_bfqq && likely(new_bfqq != &bfqd->oom_bfqq) &&
Arianna Avanzini36eca892017-04-12 18:23:16 +02002156 bfq_may_be_close_cooperator(bfqq, new_bfqq))
2157 return bfq_setup_merge(bfqq, new_bfqq);
2158
2159 return NULL;
2160}
2161
2162static void bfq_bfqq_save_state(struct bfq_queue *bfqq)
2163{
2164 struct bfq_io_cq *bic = bfqq->bic;
2165
2166 /*
2167 * If !bfqq->bic, the queue is already shared or its requests
2168 * have already been redirected to a shared queue; both idle window
2169 * and weight raising state have already been saved. Do nothing.
2170 */
2171 if (!bic)
2172 return;
2173
2174 bic->saved_ttime = bfqq->ttime;
Paolo Valented5be3fe2017-08-04 07:35:10 +02002175 bic->saved_has_short_ttime = bfq_bfqq_has_short_ttime(bfqq);
Arianna Avanzini36eca892017-04-12 18:23:16 +02002176 bic->saved_IO_bound = bfq_bfqq_IO_bound(bfqq);
Arianna Avanzinie1b23242017-04-12 18:23:20 +02002177 bic->saved_in_large_burst = bfq_bfqq_in_large_burst(bfqq);
2178 bic->was_in_burst_list = !hlist_unhashed(&bfqq->burst_list_node);
Paolo Valente894df932017-09-21 11:04:02 +02002179 if (unlikely(bfq_bfqq_just_created(bfqq) &&
Angelo Ruocco1be6e8a2017-12-20 12:38:32 +01002180 !bfq_bfqq_in_large_burst(bfqq) &&
2181 bfqq->bfqd->low_latency)) {
Paolo Valente894df932017-09-21 11:04:02 +02002182 /*
2183 * bfqq being merged right after being created: bfqq
2184 * would have deserved interactive weight raising, but
2185 * did not make it to be set in a weight-raised state,
2186 * because of this early merge. Store directly the
2187 * weight-raising state that would have been assigned
2188 * to bfqq, so that to avoid that bfqq unjustly fails
2189 * to enjoy weight raising if split soon.
2190 */
2191 bic->saved_wr_coeff = bfqq->bfqd->bfq_wr_coeff;
2192 bic->saved_wr_cur_max_time = bfq_wr_duration(bfqq->bfqd);
2193 bic->saved_last_wr_start_finish = jiffies;
2194 } else {
2195 bic->saved_wr_coeff = bfqq->wr_coeff;
2196 bic->saved_wr_start_at_switch_to_srt =
2197 bfqq->wr_start_at_switch_to_srt;
2198 bic->saved_last_wr_start_finish = bfqq->last_wr_start_finish;
2199 bic->saved_wr_cur_max_time = bfqq->wr_cur_max_time;
2200 }
Arianna Avanzini36eca892017-04-12 18:23:16 +02002201}
2202
Arianna Avanzini36eca892017-04-12 18:23:16 +02002203static void
2204bfq_merge_bfqqs(struct bfq_data *bfqd, struct bfq_io_cq *bic,
2205 struct bfq_queue *bfqq, struct bfq_queue *new_bfqq)
2206{
2207 bfq_log_bfqq(bfqd, bfqq, "merging with queue %lu",
2208 (unsigned long)new_bfqq->pid);
2209 /* Save weight raising and idle window of the merged queues */
2210 bfq_bfqq_save_state(bfqq);
2211 bfq_bfqq_save_state(new_bfqq);
2212 if (bfq_bfqq_IO_bound(bfqq))
2213 bfq_mark_bfqq_IO_bound(new_bfqq);
2214 bfq_clear_bfqq_IO_bound(bfqq);
2215
2216 /*
2217 * If bfqq is weight-raised, then let new_bfqq inherit
2218 * weight-raising. To reduce false positives, neglect the case
2219 * where bfqq has just been created, but has not yet made it
2220 * to be weight-raised (which may happen because EQM may merge
2221 * bfqq even before bfq_add_request is executed for the first
Arianna Avanzinie1b23242017-04-12 18:23:20 +02002222 * time for bfqq). Handling this case would however be very
2223 * easy, thanks to the flag just_created.
Arianna Avanzini36eca892017-04-12 18:23:16 +02002224 */
2225 if (new_bfqq->wr_coeff == 1 && bfqq->wr_coeff > 1) {
2226 new_bfqq->wr_coeff = bfqq->wr_coeff;
2227 new_bfqq->wr_cur_max_time = bfqq->wr_cur_max_time;
2228 new_bfqq->last_wr_start_finish = bfqq->last_wr_start_finish;
2229 new_bfqq->wr_start_at_switch_to_srt =
2230 bfqq->wr_start_at_switch_to_srt;
2231 if (bfq_bfqq_busy(new_bfqq))
2232 bfqd->wr_busy_queues++;
2233 new_bfqq->entity.prio_changed = 1;
2234 }
2235
2236 if (bfqq->wr_coeff > 1) { /* bfqq has given its wr to new_bfqq */
2237 bfqq->wr_coeff = 1;
2238 bfqq->entity.prio_changed = 1;
2239 if (bfq_bfqq_busy(bfqq))
2240 bfqd->wr_busy_queues--;
2241 }
2242
2243 bfq_log_bfqq(bfqd, new_bfqq, "merge_bfqqs: wr_busy %d",
2244 bfqd->wr_busy_queues);
2245
2246 /*
Arianna Avanzini36eca892017-04-12 18:23:16 +02002247 * Merge queues (that is, let bic redirect its requests to new_bfqq)
2248 */
2249 bic_set_bfqq(bic, new_bfqq, 1);
2250 bfq_mark_bfqq_coop(new_bfqq);
2251 /*
2252 * new_bfqq now belongs to at least two bics (it is a shared queue):
2253 * set new_bfqq->bic to NULL. bfqq either:
2254 * - does not belong to any bic any more, and hence bfqq->bic must
2255 * be set to NULL, or
2256 * - is a queue whose owning bics have already been redirected to a
2257 * different queue, hence the queue is destined to not belong to
2258 * any bic soon and bfqq->bic is already NULL (therefore the next
2259 * assignment causes no harm).
2260 */
2261 new_bfqq->bic = NULL;
2262 bfqq->bic = NULL;
2263 /* release process reference to bfqq */
2264 bfq_put_queue(bfqq);
2265}
2266
Paolo Valenteaee69d72017-04-19 08:29:02 -06002267static bool bfq_allow_bio_merge(struct request_queue *q, struct request *rq,
2268 struct bio *bio)
2269{
2270 struct bfq_data *bfqd = q->elevator->elevator_data;
2271 bool is_sync = op_is_sync(bio->bi_opf);
Arianna Avanzini36eca892017-04-12 18:23:16 +02002272 struct bfq_queue *bfqq = bfqd->bio_bfqq, *new_bfqq;
Paolo Valenteaee69d72017-04-19 08:29:02 -06002273
2274 /*
2275 * Disallow merge of a sync bio into an async request.
2276 */
2277 if (is_sync && !rq_is_sync(rq))
2278 return false;
2279
2280 /*
2281 * Lookup the bfqq that this bio will be queued with. Allow
2282 * merge only if rq is queued there.
2283 */
2284 if (!bfqq)
2285 return false;
2286
Arianna Avanzini36eca892017-04-12 18:23:16 +02002287 /*
2288 * We take advantage of this function to perform an early merge
2289 * of the queues of possible cooperating processes.
2290 */
2291 new_bfqq = bfq_setup_cooperator(bfqd, bfqq, bio, false);
2292 if (new_bfqq) {
2293 /*
2294 * bic still points to bfqq, then it has not yet been
2295 * redirected to some other bfq_queue, and a queue
2296 * merge beween bfqq and new_bfqq can be safely
2297 * fulfillled, i.e., bic can be redirected to new_bfqq
2298 * and bfqq can be put.
2299 */
2300 bfq_merge_bfqqs(bfqd, bfqd->bio_bic, bfqq,
2301 new_bfqq);
2302 /*
2303 * If we get here, bio will be queued into new_queue,
2304 * so use new_bfqq to decide whether bio and rq can be
2305 * merged.
2306 */
2307 bfqq = new_bfqq;
2308
2309 /*
2310 * Change also bqfd->bio_bfqq, as
2311 * bfqd->bio_bic now points to new_bfqq, and
2312 * this function may be invoked again (and then may
2313 * use again bqfd->bio_bfqq).
2314 */
2315 bfqd->bio_bfqq = bfqq;
2316 }
2317
Paolo Valenteaee69d72017-04-19 08:29:02 -06002318 return bfqq == RQ_BFQQ(rq);
2319}
2320
Paolo Valente44e44a12017-04-12 18:23:12 +02002321/*
2322 * Set the maximum time for the in-service queue to consume its
2323 * budget. This prevents seeky processes from lowering the throughput.
2324 * In practice, a time-slice service scheme is used with seeky
2325 * processes.
2326 */
2327static void bfq_set_budget_timeout(struct bfq_data *bfqd,
2328 struct bfq_queue *bfqq)
2329{
Paolo Valente77b7dce2017-04-12 18:23:13 +02002330 unsigned int timeout_coeff;
2331
2332 if (bfqq->wr_cur_max_time == bfqd->bfq_wr_rt_max_time)
2333 timeout_coeff = 1;
2334 else
2335 timeout_coeff = bfqq->entity.weight / bfqq->entity.orig_weight;
2336
Paolo Valente44e44a12017-04-12 18:23:12 +02002337 bfqd->last_budget_start = ktime_get();
2338
2339 bfqq->budget_timeout = jiffies +
Paolo Valente77b7dce2017-04-12 18:23:13 +02002340 bfqd->bfq_timeout * timeout_coeff;
Paolo Valente44e44a12017-04-12 18:23:12 +02002341}
2342
Paolo Valenteaee69d72017-04-19 08:29:02 -06002343static void __bfq_set_in_service_queue(struct bfq_data *bfqd,
2344 struct bfq_queue *bfqq)
2345{
2346 if (bfqq) {
Paolo Valenteaee69d72017-04-19 08:29:02 -06002347 bfq_clear_bfqq_fifo_expire(bfqq);
2348
2349 bfqd->budgets_assigned = (bfqd->budgets_assigned * 7 + 256) / 8;
2350
Paolo Valente77b7dce2017-04-12 18:23:13 +02002351 if (time_is_before_jiffies(bfqq->last_wr_start_finish) &&
2352 bfqq->wr_coeff > 1 &&
2353 bfqq->wr_cur_max_time == bfqd->bfq_wr_rt_max_time &&
2354 time_is_before_jiffies(bfqq->budget_timeout)) {
2355 /*
2356 * For soft real-time queues, move the start
2357 * of the weight-raising period forward by the
2358 * time the queue has not received any
2359 * service. Otherwise, a relatively long
2360 * service delay is likely to cause the
2361 * weight-raising period of the queue to end,
2362 * because of the short duration of the
2363 * weight-raising period of a soft real-time
2364 * queue. It is worth noting that this move
2365 * is not so dangerous for the other queues,
2366 * because soft real-time queues are not
2367 * greedy.
2368 *
2369 * To not add a further variable, we use the
2370 * overloaded field budget_timeout to
2371 * determine for how long the queue has not
2372 * received service, i.e., how much time has
2373 * elapsed since the queue expired. However,
2374 * this is a little imprecise, because
2375 * budget_timeout is set to jiffies if bfqq
2376 * not only expires, but also remains with no
2377 * request.
2378 */
2379 if (time_after(bfqq->budget_timeout,
2380 bfqq->last_wr_start_finish))
2381 bfqq->last_wr_start_finish +=
2382 jiffies - bfqq->budget_timeout;
2383 else
2384 bfqq->last_wr_start_finish = jiffies;
2385 }
2386
Paolo Valente44e44a12017-04-12 18:23:12 +02002387 bfq_set_budget_timeout(bfqd, bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06002388 bfq_log_bfqq(bfqd, bfqq,
2389 "set_in_service_queue, cur-budget = %d",
2390 bfqq->entity.budget);
2391 }
2392
2393 bfqd->in_service_queue = bfqq;
2394}
2395
2396/*
2397 * Get and set a new queue for service.
2398 */
2399static struct bfq_queue *bfq_set_in_service_queue(struct bfq_data *bfqd)
2400{
2401 struct bfq_queue *bfqq = bfq_get_next_queue(bfqd);
2402
2403 __bfq_set_in_service_queue(bfqd, bfqq);
2404 return bfqq;
2405}
2406
Paolo Valenteaee69d72017-04-19 08:29:02 -06002407static void bfq_arm_slice_timer(struct bfq_data *bfqd)
2408{
2409 struct bfq_queue *bfqq = bfqd->in_service_queue;
Paolo Valenteaee69d72017-04-19 08:29:02 -06002410 u32 sl;
2411
Paolo Valenteaee69d72017-04-19 08:29:02 -06002412 bfq_mark_bfqq_wait_request(bfqq);
2413
2414 /*
2415 * We don't want to idle for seeks, but we do want to allow
2416 * fair distribution of slice time for a process doing back-to-back
2417 * seeks. So allow a little bit of time for him to submit a new rq.
2418 */
2419 sl = bfqd->bfq_slice_idle;
2420 /*
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +02002421 * Unless the queue is being weight-raised or the scenario is
2422 * asymmetric, grant only minimum idle time if the queue
2423 * is seeky. A long idling is preserved for a weight-raised
2424 * queue, or, more in general, in an asymmetric scenario,
2425 * because a long idling is needed for guaranteeing to a queue
2426 * its reserved share of the throughput (in particular, it is
2427 * needed if the queue has a higher weight than some other
2428 * queue).
Paolo Valenteaee69d72017-04-19 08:29:02 -06002429 */
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +02002430 if (BFQQ_SEEKY(bfqq) && bfqq->wr_coeff == 1 &&
2431 bfq_symmetric_scenario(bfqd))
Paolo Valenteaee69d72017-04-19 08:29:02 -06002432 sl = min_t(u64, sl, BFQ_MIN_TT);
2433
2434 bfqd->last_idling_start = ktime_get();
2435 hrtimer_start(&bfqd->idle_slice_timer, ns_to_ktime(sl),
2436 HRTIMER_MODE_REL);
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02002437 bfqg_stats_set_start_idle_time(bfqq_group(bfqq));
Paolo Valenteaee69d72017-04-19 08:29:02 -06002438}
2439
2440/*
Paolo Valenteab0e43e2017-04-12 18:23:10 +02002441 * In autotuning mode, max_budget is dynamically recomputed as the
2442 * amount of sectors transferred in timeout at the estimated peak
2443 * rate. This enables BFQ to utilize a full timeslice with a full
2444 * budget, even if the in-service queue is served at peak rate. And
2445 * this maximises throughput with sequential workloads.
2446 */
2447static unsigned long bfq_calc_max_budget(struct bfq_data *bfqd)
2448{
2449 return (u64)bfqd->peak_rate * USEC_PER_MSEC *
2450 jiffies_to_msecs(bfqd->bfq_timeout)>>BFQ_RATE_SHIFT;
2451}
2452
Paolo Valente44e44a12017-04-12 18:23:12 +02002453/*
2454 * Update parameters related to throughput and responsiveness, as a
2455 * function of the estimated peak rate. See comments on
2456 * bfq_calc_max_budget(), and on T_slow and T_fast arrays.
2457 */
2458static void update_thr_responsiveness_params(struct bfq_data *bfqd)
2459{
2460 int dev_type = blk_queue_nonrot(bfqd->queue);
2461
2462 if (bfqd->bfq_user_max_budget == 0)
2463 bfqd->bfq_max_budget =
2464 bfq_calc_max_budget(bfqd);
2465
2466 if (bfqd->device_speed == BFQ_BFQD_FAST &&
2467 bfqd->peak_rate < device_speed_thresh[dev_type]) {
2468 bfqd->device_speed = BFQ_BFQD_SLOW;
2469 bfqd->RT_prod = R_slow[dev_type] *
2470 T_slow[dev_type];
2471 } else if (bfqd->device_speed == BFQ_BFQD_SLOW &&
2472 bfqd->peak_rate > device_speed_thresh[dev_type]) {
2473 bfqd->device_speed = BFQ_BFQD_FAST;
2474 bfqd->RT_prod = R_fast[dev_type] *
2475 T_fast[dev_type];
2476 }
2477
2478 bfq_log(bfqd,
2479"dev_type %s dev_speed_class = %s (%llu sects/sec), thresh %llu setcs/sec",
2480 dev_type == 0 ? "ROT" : "NONROT",
2481 bfqd->device_speed == BFQ_BFQD_FAST ? "FAST" : "SLOW",
2482 bfqd->device_speed == BFQ_BFQD_FAST ?
2483 (USEC_PER_SEC*(u64)R_fast[dev_type])>>BFQ_RATE_SHIFT :
2484 (USEC_PER_SEC*(u64)R_slow[dev_type])>>BFQ_RATE_SHIFT,
2485 (USEC_PER_SEC*(u64)device_speed_thresh[dev_type])>>
2486 BFQ_RATE_SHIFT);
2487}
2488
Paolo Valenteab0e43e2017-04-12 18:23:10 +02002489static void bfq_reset_rate_computation(struct bfq_data *bfqd,
2490 struct request *rq)
2491{
2492 if (rq != NULL) { /* new rq dispatch now, reset accordingly */
2493 bfqd->last_dispatch = bfqd->first_dispatch = ktime_get_ns();
2494 bfqd->peak_rate_samples = 1;
2495 bfqd->sequential_samples = 0;
2496 bfqd->tot_sectors_dispatched = bfqd->last_rq_max_size =
2497 blk_rq_sectors(rq);
2498 } else /* no new rq dispatched, just reset the number of samples */
2499 bfqd->peak_rate_samples = 0; /* full re-init on next disp. */
2500
2501 bfq_log(bfqd,
2502 "reset_rate_computation at end, sample %u/%u tot_sects %llu",
2503 bfqd->peak_rate_samples, bfqd->sequential_samples,
2504 bfqd->tot_sectors_dispatched);
2505}
2506
2507static void bfq_update_rate_reset(struct bfq_data *bfqd, struct request *rq)
2508{
2509 u32 rate, weight, divisor;
2510
2511 /*
2512 * For the convergence property to hold (see comments on
2513 * bfq_update_peak_rate()) and for the assessment to be
2514 * reliable, a minimum number of samples must be present, and
2515 * a minimum amount of time must have elapsed. If not so, do
2516 * not compute new rate. Just reset parameters, to get ready
2517 * for a new evaluation attempt.
2518 */
2519 if (bfqd->peak_rate_samples < BFQ_RATE_MIN_SAMPLES ||
2520 bfqd->delta_from_first < BFQ_RATE_MIN_INTERVAL)
2521 goto reset_computation;
2522
2523 /*
2524 * If a new request completion has occurred after last
2525 * dispatch, then, to approximate the rate at which requests
2526 * have been served by the device, it is more precise to
2527 * extend the observation interval to the last completion.
2528 */
2529 bfqd->delta_from_first =
2530 max_t(u64, bfqd->delta_from_first,
2531 bfqd->last_completion - bfqd->first_dispatch);
2532
2533 /*
2534 * Rate computed in sects/usec, and not sects/nsec, for
2535 * precision issues.
2536 */
2537 rate = div64_ul(bfqd->tot_sectors_dispatched<<BFQ_RATE_SHIFT,
2538 div_u64(bfqd->delta_from_first, NSEC_PER_USEC));
2539
2540 /*
2541 * Peak rate not updated if:
2542 * - the percentage of sequential dispatches is below 3/4 of the
2543 * total, and rate is below the current estimated peak rate
2544 * - rate is unreasonably high (> 20M sectors/sec)
2545 */
2546 if ((bfqd->sequential_samples < (3 * bfqd->peak_rate_samples)>>2 &&
2547 rate <= bfqd->peak_rate) ||
2548 rate > 20<<BFQ_RATE_SHIFT)
2549 goto reset_computation;
2550
2551 /*
2552 * We have to update the peak rate, at last! To this purpose,
2553 * we use a low-pass filter. We compute the smoothing constant
2554 * of the filter as a function of the 'weight' of the new
2555 * measured rate.
2556 *
2557 * As can be seen in next formulas, we define this weight as a
2558 * quantity proportional to how sequential the workload is,
2559 * and to how long the observation time interval is.
2560 *
2561 * The weight runs from 0 to 8. The maximum value of the
2562 * weight, 8, yields the minimum value for the smoothing
2563 * constant. At this minimum value for the smoothing constant,
2564 * the measured rate contributes for half of the next value of
2565 * the estimated peak rate.
2566 *
2567 * So, the first step is to compute the weight as a function
2568 * of how sequential the workload is. Note that the weight
2569 * cannot reach 9, because bfqd->sequential_samples cannot
2570 * become equal to bfqd->peak_rate_samples, which, in its
2571 * turn, holds true because bfqd->sequential_samples is not
2572 * incremented for the first sample.
2573 */
2574 weight = (9 * bfqd->sequential_samples) / bfqd->peak_rate_samples;
2575
2576 /*
2577 * Second step: further refine the weight as a function of the
2578 * duration of the observation interval.
2579 */
2580 weight = min_t(u32, 8,
2581 div_u64(weight * bfqd->delta_from_first,
2582 BFQ_RATE_REF_INTERVAL));
2583
2584 /*
2585 * Divisor ranging from 10, for minimum weight, to 2, for
2586 * maximum weight.
2587 */
2588 divisor = 10 - weight;
2589
2590 /*
2591 * Finally, update peak rate:
2592 *
2593 * peak_rate = peak_rate * (divisor-1) / divisor + rate / divisor
2594 */
2595 bfqd->peak_rate *= divisor-1;
2596 bfqd->peak_rate /= divisor;
2597 rate /= divisor; /* smoothing constant alpha = 1/divisor */
2598
2599 bfqd->peak_rate += rate;
Paolo Valentebc56e2c2018-03-26 16:06:24 +02002600
2601 /*
2602 * For a very slow device, bfqd->peak_rate can reach 0 (see
2603 * the minimum representable values reported in the comments
2604 * on BFQ_RATE_SHIFT). Push to 1 if this happens, to avoid
2605 * divisions by zero where bfqd->peak_rate is used as a
2606 * divisor.
2607 */
2608 bfqd->peak_rate = max_t(u32, 1, bfqd->peak_rate);
2609
Paolo Valente44e44a12017-04-12 18:23:12 +02002610 update_thr_responsiveness_params(bfqd);
Paolo Valenteab0e43e2017-04-12 18:23:10 +02002611
2612reset_computation:
2613 bfq_reset_rate_computation(bfqd, rq);
2614}
2615
2616/*
2617 * Update the read/write peak rate (the main quantity used for
2618 * auto-tuning, see update_thr_responsiveness_params()).
2619 *
2620 * It is not trivial to estimate the peak rate (correctly): because of
2621 * the presence of sw and hw queues between the scheduler and the
2622 * device components that finally serve I/O requests, it is hard to
2623 * say exactly when a given dispatched request is served inside the
2624 * device, and for how long. As a consequence, it is hard to know
2625 * precisely at what rate a given set of requests is actually served
2626 * by the device.
2627 *
2628 * On the opposite end, the dispatch time of any request is trivially
2629 * available, and, from this piece of information, the "dispatch rate"
2630 * of requests can be immediately computed. So, the idea in the next
2631 * function is to use what is known, namely request dispatch times
2632 * (plus, when useful, request completion times), to estimate what is
2633 * unknown, namely in-device request service rate.
2634 *
2635 * The main issue is that, because of the above facts, the rate at
2636 * which a certain set of requests is dispatched over a certain time
2637 * interval can vary greatly with respect to the rate at which the
2638 * same requests are then served. But, since the size of any
2639 * intermediate queue is limited, and the service scheme is lossless
2640 * (no request is silently dropped), the following obvious convergence
2641 * property holds: the number of requests dispatched MUST become
2642 * closer and closer to the number of requests completed as the
2643 * observation interval grows. This is the key property used in
2644 * the next function to estimate the peak service rate as a function
2645 * of the observed dispatch rate. The function assumes to be invoked
2646 * on every request dispatch.
2647 */
2648static void bfq_update_peak_rate(struct bfq_data *bfqd, struct request *rq)
2649{
2650 u64 now_ns = ktime_get_ns();
2651
2652 if (bfqd->peak_rate_samples == 0) { /* first dispatch */
2653 bfq_log(bfqd, "update_peak_rate: goto reset, samples %d",
2654 bfqd->peak_rate_samples);
2655 bfq_reset_rate_computation(bfqd, rq);
2656 goto update_last_values; /* will add one sample */
2657 }
2658
2659 /*
2660 * Device idle for very long: the observation interval lasting
2661 * up to this dispatch cannot be a valid observation interval
2662 * for computing a new peak rate (similarly to the late-
2663 * completion event in bfq_completed_request()). Go to
2664 * update_rate_and_reset to have the following three steps
2665 * taken:
2666 * - close the observation interval at the last (previous)
2667 * request dispatch or completion
2668 * - compute rate, if possible, for that observation interval
2669 * - start a new observation interval with this dispatch
2670 */
2671 if (now_ns - bfqd->last_dispatch > 100*NSEC_PER_MSEC &&
2672 bfqd->rq_in_driver == 0)
2673 goto update_rate_and_reset;
2674
2675 /* Update sampling information */
2676 bfqd->peak_rate_samples++;
2677
2678 if ((bfqd->rq_in_driver > 0 ||
2679 now_ns - bfqd->last_completion < BFQ_MIN_TT)
2680 && get_sdist(bfqd->last_position, rq) < BFQQ_SEEK_THR)
2681 bfqd->sequential_samples++;
2682
2683 bfqd->tot_sectors_dispatched += blk_rq_sectors(rq);
2684
2685 /* Reset max observed rq size every 32 dispatches */
2686 if (likely(bfqd->peak_rate_samples % 32))
2687 bfqd->last_rq_max_size =
2688 max_t(u32, blk_rq_sectors(rq), bfqd->last_rq_max_size);
2689 else
2690 bfqd->last_rq_max_size = blk_rq_sectors(rq);
2691
2692 bfqd->delta_from_first = now_ns - bfqd->first_dispatch;
2693
2694 /* Target observation interval not yet reached, go on sampling */
2695 if (bfqd->delta_from_first < BFQ_RATE_REF_INTERVAL)
2696 goto update_last_values;
2697
2698update_rate_and_reset:
2699 bfq_update_rate_reset(bfqd, rq);
2700update_last_values:
2701 bfqd->last_position = blk_rq_pos(rq) + blk_rq_sectors(rq);
2702 bfqd->last_dispatch = now_ns;
2703}
2704
2705/*
Paolo Valenteaee69d72017-04-19 08:29:02 -06002706 * Remove request from internal lists.
2707 */
2708static void bfq_dispatch_remove(struct request_queue *q, struct request *rq)
2709{
2710 struct bfq_queue *bfqq = RQ_BFQQ(rq);
2711
2712 /*
2713 * For consistency, the next instruction should have been
2714 * executed after removing the request from the queue and
2715 * dispatching it. We execute instead this instruction before
2716 * bfq_remove_request() (and hence introduce a temporary
2717 * inconsistency), for efficiency. In fact, should this
2718 * dispatch occur for a non in-service bfqq, this anticipated
2719 * increment prevents two counters related to bfqq->dispatched
2720 * from risking to be, first, uselessly decremented, and then
2721 * incremented again when the (new) value of bfqq->dispatched
2722 * happens to be taken into account.
2723 */
2724 bfqq->dispatched++;
Paolo Valenteab0e43e2017-04-12 18:23:10 +02002725 bfq_update_peak_rate(q->elevator->elevator_data, rq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06002726
2727 bfq_remove_request(q, rq);
2728}
2729
2730static void __bfq_bfqq_expire(struct bfq_data *bfqd, struct bfq_queue *bfqq)
2731{
Arianna Avanzini36eca892017-04-12 18:23:16 +02002732 /*
2733 * If this bfqq is shared between multiple processes, check
2734 * to make sure that those processes are still issuing I/Os
2735 * within the mean seek distance. If not, it may be time to
2736 * break the queues apart again.
2737 */
2738 if (bfq_bfqq_coop(bfqq) && BFQQ_SEEKY(bfqq))
2739 bfq_mark_bfqq_split_coop(bfqq);
2740
Paolo Valente44e44a12017-04-12 18:23:12 +02002741 if (RB_EMPTY_ROOT(&bfqq->sort_list)) {
2742 if (bfqq->dispatched == 0)
2743 /*
2744 * Overloading budget_timeout field to store
2745 * the time at which the queue remains with no
2746 * backlog and no outstanding request; used by
2747 * the weight-raising mechanism.
2748 */
2749 bfqq->budget_timeout = jiffies;
2750
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02002751 bfq_del_bfqq_busy(bfqd, bfqq, true);
Arianna Avanzini36eca892017-04-12 18:23:16 +02002752 } else {
Paolo Valente80294c32017-08-31 08:46:29 +02002753 bfq_requeue_bfqq(bfqd, bfqq, true);
Arianna Avanzini36eca892017-04-12 18:23:16 +02002754 /*
2755 * Resort priority tree of potential close cooperators.
2756 */
2757 bfq_pos_tree_add_move(bfqd, bfqq);
2758 }
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02002759
2760 /*
2761 * All in-service entities must have been properly deactivated
2762 * or requeued before executing the next function, which
2763 * resets all in-service entites as no more in service.
2764 */
2765 __bfq_bfqd_reset_in_service(bfqd);
Paolo Valenteaee69d72017-04-19 08:29:02 -06002766}
2767
2768/**
2769 * __bfq_bfqq_recalc_budget - try to adapt the budget to the @bfqq behavior.
2770 * @bfqd: device data.
2771 * @bfqq: queue to update.
2772 * @reason: reason for expiration.
2773 *
2774 * Handle the feedback on @bfqq budget at queue expiration.
2775 * See the body for detailed comments.
2776 */
2777static void __bfq_bfqq_recalc_budget(struct bfq_data *bfqd,
2778 struct bfq_queue *bfqq,
2779 enum bfqq_expiration reason)
2780{
2781 struct request *next_rq;
2782 int budget, min_budget;
2783
Paolo Valenteaee69d72017-04-19 08:29:02 -06002784 min_budget = bfq_min_budget(bfqd);
2785
Paolo Valente44e44a12017-04-12 18:23:12 +02002786 if (bfqq->wr_coeff == 1)
2787 budget = bfqq->max_budget;
2788 else /*
2789 * Use a constant, low budget for weight-raised queues,
2790 * to help achieve a low latency. Keep it slightly higher
2791 * than the minimum possible budget, to cause a little
2792 * bit fewer expirations.
2793 */
2794 budget = 2 * min_budget;
2795
Paolo Valenteaee69d72017-04-19 08:29:02 -06002796 bfq_log_bfqq(bfqd, bfqq, "recalc_budg: last budg %d, budg left %d",
2797 bfqq->entity.budget, bfq_bfqq_budget_left(bfqq));
2798 bfq_log_bfqq(bfqd, bfqq, "recalc_budg: last max_budg %d, min budg %d",
2799 budget, bfq_min_budget(bfqd));
2800 bfq_log_bfqq(bfqd, bfqq, "recalc_budg: sync %d, seeky %d",
2801 bfq_bfqq_sync(bfqq), BFQQ_SEEKY(bfqd->in_service_queue));
2802
Paolo Valente44e44a12017-04-12 18:23:12 +02002803 if (bfq_bfqq_sync(bfqq) && bfqq->wr_coeff == 1) {
Paolo Valenteaee69d72017-04-19 08:29:02 -06002804 switch (reason) {
2805 /*
2806 * Caveat: in all the following cases we trade latency
2807 * for throughput.
2808 */
2809 case BFQQE_TOO_IDLE:
Paolo Valente54b60452017-04-12 18:23:09 +02002810 /*
2811 * This is the only case where we may reduce
2812 * the budget: if there is no request of the
2813 * process still waiting for completion, then
2814 * we assume (tentatively) that the timer has
2815 * expired because the batch of requests of
2816 * the process could have been served with a
2817 * smaller budget. Hence, betting that
2818 * process will behave in the same way when it
2819 * becomes backlogged again, we reduce its
2820 * next budget. As long as we guess right,
2821 * this budget cut reduces the latency
2822 * experienced by the process.
2823 *
2824 * However, if there are still outstanding
2825 * requests, then the process may have not yet
2826 * issued its next request just because it is
2827 * still waiting for the completion of some of
2828 * the still outstanding ones. So in this
2829 * subcase we do not reduce its budget, on the
2830 * contrary we increase it to possibly boost
2831 * the throughput, as discussed in the
2832 * comments to the BUDGET_TIMEOUT case.
2833 */
2834 if (bfqq->dispatched > 0) /* still outstanding reqs */
2835 budget = min(budget * 2, bfqd->bfq_max_budget);
2836 else {
2837 if (budget > 5 * min_budget)
2838 budget -= 4 * min_budget;
2839 else
2840 budget = min_budget;
2841 }
Paolo Valenteaee69d72017-04-19 08:29:02 -06002842 break;
2843 case BFQQE_BUDGET_TIMEOUT:
Paolo Valente54b60452017-04-12 18:23:09 +02002844 /*
2845 * We double the budget here because it gives
2846 * the chance to boost the throughput if this
2847 * is not a seeky process (and has bumped into
2848 * this timeout because of, e.g., ZBR).
2849 */
2850 budget = min(budget * 2, bfqd->bfq_max_budget);
Paolo Valenteaee69d72017-04-19 08:29:02 -06002851 break;
2852 case BFQQE_BUDGET_EXHAUSTED:
2853 /*
2854 * The process still has backlog, and did not
2855 * let either the budget timeout or the disk
2856 * idling timeout expire. Hence it is not
2857 * seeky, has a short thinktime and may be
2858 * happy with a higher budget too. So
2859 * definitely increase the budget of this good
2860 * candidate to boost the disk throughput.
2861 */
Paolo Valente54b60452017-04-12 18:23:09 +02002862 budget = min(budget * 4, bfqd->bfq_max_budget);
Paolo Valenteaee69d72017-04-19 08:29:02 -06002863 break;
2864 case BFQQE_NO_MORE_REQUESTS:
2865 /*
2866 * For queues that expire for this reason, it
2867 * is particularly important to keep the
2868 * budget close to the actual service they
2869 * need. Doing so reduces the timestamp
2870 * misalignment problem described in the
2871 * comments in the body of
2872 * __bfq_activate_entity. In fact, suppose
2873 * that a queue systematically expires for
2874 * BFQQE_NO_MORE_REQUESTS and presents a
2875 * new request in time to enjoy timestamp
2876 * back-shifting. The larger the budget of the
2877 * queue is with respect to the service the
2878 * queue actually requests in each service
2879 * slot, the more times the queue can be
2880 * reactivated with the same virtual finish
2881 * time. It follows that, even if this finish
2882 * time is pushed to the system virtual time
2883 * to reduce the consequent timestamp
2884 * misalignment, the queue unjustly enjoys for
2885 * many re-activations a lower finish time
2886 * than all newly activated queues.
2887 *
2888 * The service needed by bfqq is measured
2889 * quite precisely by bfqq->entity.service.
2890 * Since bfqq does not enjoy device idling,
2891 * bfqq->entity.service is equal to the number
2892 * of sectors that the process associated with
2893 * bfqq requested to read/write before waiting
2894 * for request completions, or blocking for
2895 * other reasons.
2896 */
2897 budget = max_t(int, bfqq->entity.service, min_budget);
2898 break;
2899 default:
2900 return;
2901 }
Paolo Valente44e44a12017-04-12 18:23:12 +02002902 } else if (!bfq_bfqq_sync(bfqq)) {
Paolo Valenteaee69d72017-04-19 08:29:02 -06002903 /*
2904 * Async queues get always the maximum possible
2905 * budget, as for them we do not care about latency
2906 * (in addition, their ability to dispatch is limited
2907 * by the charging factor).
2908 */
2909 budget = bfqd->bfq_max_budget;
2910 }
2911
2912 bfqq->max_budget = budget;
2913
2914 if (bfqd->budgets_assigned >= bfq_stats_min_budgets &&
2915 !bfqd->bfq_user_max_budget)
2916 bfqq->max_budget = min(bfqq->max_budget, bfqd->bfq_max_budget);
2917
2918 /*
2919 * If there is still backlog, then assign a new budget, making
2920 * sure that it is large enough for the next request. Since
2921 * the finish time of bfqq must be kept in sync with the
2922 * budget, be sure to call __bfq_bfqq_expire() *after* this
2923 * update.
2924 *
2925 * If there is no backlog, then no need to update the budget;
2926 * it will be updated on the arrival of a new request.
2927 */
2928 next_rq = bfqq->next_rq;
2929 if (next_rq)
2930 bfqq->entity.budget = max_t(unsigned long, bfqq->max_budget,
2931 bfq_serv_to_charge(next_rq, bfqq));
2932
2933 bfq_log_bfqq(bfqd, bfqq, "head sect: %u, new budget %d",
2934 next_rq ? blk_rq_sectors(next_rq) : 0,
2935 bfqq->entity.budget);
2936}
2937
Paolo Valenteaee69d72017-04-19 08:29:02 -06002938/*
Paolo Valenteab0e43e2017-04-12 18:23:10 +02002939 * Return true if the process associated with bfqq is "slow". The slow
2940 * flag is used, in addition to the budget timeout, to reduce the
2941 * amount of service provided to seeky processes, and thus reduce
2942 * their chances to lower the throughput. More details in the comments
2943 * on the function bfq_bfqq_expire().
2944 *
2945 * An important observation is in order: as discussed in the comments
2946 * on the function bfq_update_peak_rate(), with devices with internal
2947 * queues, it is hard if ever possible to know when and for how long
2948 * an I/O request is processed by the device (apart from the trivial
2949 * I/O pattern where a new request is dispatched only after the
2950 * previous one has been completed). This makes it hard to evaluate
2951 * the real rate at which the I/O requests of each bfq_queue are
2952 * served. In fact, for an I/O scheduler like BFQ, serving a
2953 * bfq_queue means just dispatching its requests during its service
2954 * slot (i.e., until the budget of the queue is exhausted, or the
2955 * queue remains idle, or, finally, a timeout fires). But, during the
2956 * service slot of a bfq_queue, around 100 ms at most, the device may
2957 * be even still processing requests of bfq_queues served in previous
2958 * service slots. On the opposite end, the requests of the in-service
2959 * bfq_queue may be completed after the service slot of the queue
2960 * finishes.
2961 *
2962 * Anyway, unless more sophisticated solutions are used
2963 * (where possible), the sum of the sizes of the requests dispatched
2964 * during the service slot of a bfq_queue is probably the only
2965 * approximation available for the service received by the bfq_queue
2966 * during its service slot. And this sum is the quantity used in this
2967 * function to evaluate the I/O speed of a process.
Paolo Valenteaee69d72017-04-19 08:29:02 -06002968 */
Paolo Valenteab0e43e2017-04-12 18:23:10 +02002969static bool bfq_bfqq_is_slow(struct bfq_data *bfqd, struct bfq_queue *bfqq,
2970 bool compensate, enum bfqq_expiration reason,
2971 unsigned long *delta_ms)
Paolo Valenteaee69d72017-04-19 08:29:02 -06002972{
Paolo Valenteab0e43e2017-04-12 18:23:10 +02002973 ktime_t delta_ktime;
2974 u32 delta_usecs;
2975 bool slow = BFQQ_SEEKY(bfqq); /* if delta too short, use seekyness */
Paolo Valenteaee69d72017-04-19 08:29:02 -06002976
Paolo Valenteab0e43e2017-04-12 18:23:10 +02002977 if (!bfq_bfqq_sync(bfqq))
Paolo Valenteaee69d72017-04-19 08:29:02 -06002978 return false;
2979
2980 if (compensate)
Paolo Valenteab0e43e2017-04-12 18:23:10 +02002981 delta_ktime = bfqd->last_idling_start;
Paolo Valenteaee69d72017-04-19 08:29:02 -06002982 else
Paolo Valenteab0e43e2017-04-12 18:23:10 +02002983 delta_ktime = ktime_get();
2984 delta_ktime = ktime_sub(delta_ktime, bfqd->last_budget_start);
2985 delta_usecs = ktime_to_us(delta_ktime);
Paolo Valenteaee69d72017-04-19 08:29:02 -06002986
2987 /* don't use too short time intervals */
Paolo Valenteab0e43e2017-04-12 18:23:10 +02002988 if (delta_usecs < 1000) {
2989 if (blk_queue_nonrot(bfqd->queue))
2990 /*
2991 * give same worst-case guarantees as idling
2992 * for seeky
2993 */
2994 *delta_ms = BFQ_MIN_TT / NSEC_PER_MSEC;
2995 else /* charge at least one seek */
2996 *delta_ms = bfq_slice_idle / NSEC_PER_MSEC;
Paolo Valenteaee69d72017-04-19 08:29:02 -06002997
Paolo Valenteab0e43e2017-04-12 18:23:10 +02002998 return slow;
Paolo Valenteaee69d72017-04-19 08:29:02 -06002999 }
3000
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003001 *delta_ms = delta_usecs / USEC_PER_MSEC;
Paolo Valenteaee69d72017-04-19 08:29:02 -06003002
3003 /*
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003004 * Use only long (> 20ms) intervals to filter out excessive
3005 * spikes in service rate estimation.
Paolo Valenteaee69d72017-04-19 08:29:02 -06003006 */
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003007 if (delta_usecs > 20000) {
3008 /*
3009 * Caveat for rotational devices: processes doing I/O
3010 * in the slower disk zones tend to be slow(er) even
3011 * if not seeky. In this respect, the estimated peak
3012 * rate is likely to be an average over the disk
3013 * surface. Accordingly, to not be too harsh with
3014 * unlucky processes, a process is deemed slow only if
3015 * its rate has been lower than half of the estimated
3016 * peak rate.
3017 */
3018 slow = bfqq->entity.service < bfqd->bfq_max_budget / 2;
3019 }
3020
3021 bfq_log_bfqq(bfqd, bfqq, "bfq_bfqq_is_slow: slow %d", slow);
3022
3023 return slow;
Paolo Valenteaee69d72017-04-19 08:29:02 -06003024}
3025
3026/*
Paolo Valente77b7dce2017-04-12 18:23:13 +02003027 * To be deemed as soft real-time, an application must meet two
3028 * requirements. First, the application must not require an average
3029 * bandwidth higher than the approximate bandwidth required to playback or
3030 * record a compressed high-definition video.
3031 * The next function is invoked on the completion of the last request of a
3032 * batch, to compute the next-start time instant, soft_rt_next_start, such
3033 * that, if the next request of the application does not arrive before
3034 * soft_rt_next_start, then the above requirement on the bandwidth is met.
3035 *
3036 * The second requirement is that the request pattern of the application is
3037 * isochronous, i.e., that, after issuing a request or a batch of requests,
3038 * the application stops issuing new requests until all its pending requests
3039 * have been completed. After that, the application may issue a new batch,
3040 * and so on.
3041 * For this reason the next function is invoked to compute
3042 * soft_rt_next_start only for applications that meet this requirement,
3043 * whereas soft_rt_next_start is set to infinity for applications that do
3044 * not.
3045 *
Paolo Valentea34b0242017-12-15 07:23:12 +01003046 * Unfortunately, even a greedy (i.e., I/O-bound) application may
3047 * happen to meet, occasionally or systematically, both the above
3048 * bandwidth and isochrony requirements. This may happen at least in
3049 * the following circumstances. First, if the CPU load is high. The
3050 * application may stop issuing requests while the CPUs are busy
3051 * serving other processes, then restart, then stop again for a while,
3052 * and so on. The other circumstances are related to the storage
3053 * device: the storage device is highly loaded or reaches a low-enough
3054 * throughput with the I/O of the application (e.g., because the I/O
3055 * is random and/or the device is slow). In all these cases, the
3056 * I/O of the application may be simply slowed down enough to meet
3057 * the bandwidth and isochrony requirements. To reduce the probability
3058 * that greedy applications are deemed as soft real-time in these
3059 * corner cases, a further rule is used in the computation of
3060 * soft_rt_next_start: the return value of this function is forced to
3061 * be higher than the maximum between the following two quantities.
Paolo Valente77b7dce2017-04-12 18:23:13 +02003062 *
Paolo Valentea34b0242017-12-15 07:23:12 +01003063 * (a) Current time plus: (1) the maximum time for which the arrival
3064 * of a request is waited for when a sync queue becomes idle,
3065 * namely bfqd->bfq_slice_idle, and (2) a few extra jiffies. We
3066 * postpone for a moment the reason for adding a few extra
3067 * jiffies; we get back to it after next item (b). Lower-bounding
3068 * the return value of this function with the current time plus
3069 * bfqd->bfq_slice_idle tends to filter out greedy applications,
3070 * because the latter issue their next request as soon as possible
3071 * after the last one has been completed. In contrast, a soft
3072 * real-time application spends some time processing data, after a
3073 * batch of its requests has been completed.
3074 *
3075 * (b) Current value of bfqq->soft_rt_next_start. As pointed out
3076 * above, greedy applications may happen to meet both the
3077 * bandwidth and isochrony requirements under heavy CPU or
3078 * storage-device load. In more detail, in these scenarios, these
3079 * applications happen, only for limited time periods, to do I/O
3080 * slowly enough to meet all the requirements described so far,
3081 * including the filtering in above item (a). These slow-speed
3082 * time intervals are usually interspersed between other time
3083 * intervals during which these applications do I/O at a very high
3084 * speed. Fortunately, exactly because of the high speed of the
3085 * I/O in the high-speed intervals, the values returned by this
3086 * function happen to be so high, near the end of any such
3087 * high-speed interval, to be likely to fall *after* the end of
3088 * the low-speed time interval that follows. These high values are
3089 * stored in bfqq->soft_rt_next_start after each invocation of
3090 * this function. As a consequence, if the last value of
3091 * bfqq->soft_rt_next_start is constantly used to lower-bound the
3092 * next value that this function may return, then, from the very
3093 * beginning of a low-speed interval, bfqq->soft_rt_next_start is
3094 * likely to be constantly kept so high that any I/O request
3095 * issued during the low-speed interval is considered as arriving
3096 * to soon for the application to be deemed as soft
3097 * real-time. Then, in the high-speed interval that follows, the
3098 * application will not be deemed as soft real-time, just because
3099 * it will do I/O at a high speed. And so on.
3100 *
3101 * Getting back to the filtering in item (a), in the following two
3102 * cases this filtering might be easily passed by a greedy
3103 * application, if the reference quantity was just
3104 * bfqd->bfq_slice_idle:
3105 * 1) HZ is so low that the duration of a jiffy is comparable to or
3106 * higher than bfqd->bfq_slice_idle. This happens, e.g., on slow
3107 * devices with HZ=100. The time granularity may be so coarse
3108 * that the approximation, in jiffies, of bfqd->bfq_slice_idle
3109 * is rather lower than the exact value.
Paolo Valente77b7dce2017-04-12 18:23:13 +02003110 * 2) jiffies, instead of increasing at a constant rate, may stop increasing
3111 * for a while, then suddenly 'jump' by several units to recover the lost
3112 * increments. This seems to happen, e.g., inside virtual machines.
Paolo Valentea34b0242017-12-15 07:23:12 +01003113 * To address this issue, in the filtering in (a) we do not use as a
3114 * reference time interval just bfqd->bfq_slice_idle, but
3115 * bfqd->bfq_slice_idle plus a few jiffies. In particular, we add the
3116 * minimum number of jiffies for which the filter seems to be quite
3117 * precise also in embedded systems and KVM/QEMU virtual machines.
Paolo Valente77b7dce2017-04-12 18:23:13 +02003118 */
3119static unsigned long bfq_bfqq_softrt_next_start(struct bfq_data *bfqd,
3120 struct bfq_queue *bfqq)
3121{
Paolo Valentea34b0242017-12-15 07:23:12 +01003122 return max3(bfqq->soft_rt_next_start,
3123 bfqq->last_idle_bklogged +
3124 HZ * bfqq->service_from_backlogged /
3125 bfqd->bfq_wr_max_softrt_rate,
3126 jiffies + nsecs_to_jiffies(bfqq->bfqd->bfq_slice_idle) + 4);
Paolo Valente77b7dce2017-04-12 18:23:13 +02003127}
3128
Paolo Valenteaee69d72017-04-19 08:29:02 -06003129/**
3130 * bfq_bfqq_expire - expire a queue.
3131 * @bfqd: device owning the queue.
3132 * @bfqq: the queue to expire.
3133 * @compensate: if true, compensate for the time spent idling.
3134 * @reason: the reason causing the expiration.
3135 *
Paolo Valentec074170e2017-04-12 18:23:11 +02003136 * If the process associated with bfqq does slow I/O (e.g., because it
3137 * issues random requests), we charge bfqq with the time it has been
3138 * in service instead of the service it has received (see
3139 * bfq_bfqq_charge_time for details on how this goal is achieved). As
3140 * a consequence, bfqq will typically get higher timestamps upon
3141 * reactivation, and hence it will be rescheduled as if it had
3142 * received more service than what it has actually received. In the
3143 * end, bfqq receives less service in proportion to how slowly its
3144 * associated process consumes its budgets (and hence how seriously it
3145 * tends to lower the throughput). In addition, this time-charging
3146 * strategy guarantees time fairness among slow processes. In
3147 * contrast, if the process associated with bfqq is not slow, we
3148 * charge bfqq exactly with the service it has received.
Paolo Valenteaee69d72017-04-19 08:29:02 -06003149 *
Paolo Valentec074170e2017-04-12 18:23:11 +02003150 * Charging time to the first type of queues and the exact service to
3151 * the other has the effect of using the WF2Q+ policy to schedule the
3152 * former on a timeslice basis, without violating service domain
3153 * guarantees among the latter.
Paolo Valenteaee69d72017-04-19 08:29:02 -06003154 */
Paolo Valenteea25da42017-04-19 08:48:24 -06003155void bfq_bfqq_expire(struct bfq_data *bfqd,
3156 struct bfq_queue *bfqq,
3157 bool compensate,
3158 enum bfqq_expiration reason)
Paolo Valenteaee69d72017-04-19 08:29:02 -06003159{
3160 bool slow;
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003161 unsigned long delta = 0;
3162 struct bfq_entity *entity = &bfqq->entity;
Paolo Valenteaee69d72017-04-19 08:29:02 -06003163 int ref;
3164
3165 /*
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003166 * Check whether the process is slow (see bfq_bfqq_is_slow).
Paolo Valenteaee69d72017-04-19 08:29:02 -06003167 */
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003168 slow = bfq_bfqq_is_slow(bfqd, bfqq, compensate, reason, &delta);
Paolo Valenteaee69d72017-04-19 08:29:02 -06003169
3170 /*
Paolo Valentec074170e2017-04-12 18:23:11 +02003171 * As above explained, charge slow (typically seeky) and
3172 * timed-out queues with the time and not the service
3173 * received, to favor sequential workloads.
3174 *
3175 * Processes doing I/O in the slower disk zones will tend to
3176 * be slow(er) even if not seeky. Therefore, since the
3177 * estimated peak rate is actually an average over the disk
3178 * surface, these processes may timeout just for bad luck. To
3179 * avoid punishing them, do not charge time to processes that
3180 * succeeded in consuming at least 2/3 of their budget. This
3181 * allows BFQ to preserve enough elasticity to still perform
3182 * bandwidth, and not time, distribution with little unlucky
3183 * or quasi-sequential processes.
Paolo Valenteaee69d72017-04-19 08:29:02 -06003184 */
Paolo Valente44e44a12017-04-12 18:23:12 +02003185 if (bfqq->wr_coeff == 1 &&
3186 (slow ||
3187 (reason == BFQQE_BUDGET_TIMEOUT &&
3188 bfq_bfqq_budget_left(bfqq) >= entity->budget / 3)))
Paolo Valentec074170e2017-04-12 18:23:11 +02003189 bfq_bfqq_charge_time(bfqd, bfqq, delta);
Paolo Valenteaee69d72017-04-19 08:29:02 -06003190
3191 if (reason == BFQQE_TOO_IDLE &&
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003192 entity->service <= 2 * entity->budget / 10)
Paolo Valenteaee69d72017-04-19 08:29:02 -06003193 bfq_clear_bfqq_IO_bound(bfqq);
3194
Paolo Valente44e44a12017-04-12 18:23:12 +02003195 if (bfqd->low_latency && bfqq->wr_coeff == 1)
3196 bfqq->last_wr_start_finish = jiffies;
3197
Paolo Valente77b7dce2017-04-12 18:23:13 +02003198 if (bfqd->low_latency && bfqd->bfq_wr_max_softrt_rate > 0 &&
3199 RB_EMPTY_ROOT(&bfqq->sort_list)) {
3200 /*
3201 * If we get here, and there are no outstanding
3202 * requests, then the request pattern is isochronous
3203 * (see the comments on the function
3204 * bfq_bfqq_softrt_next_start()). Thus we can compute
3205 * soft_rt_next_start. If, instead, the queue still
3206 * has outstanding requests, then we have to wait for
3207 * the completion of all the outstanding requests to
3208 * discover whether the request pattern is actually
3209 * isochronous.
3210 */
3211 if (bfqq->dispatched == 0)
3212 bfqq->soft_rt_next_start =
3213 bfq_bfqq_softrt_next_start(bfqd, bfqq);
3214 else {
3215 /*
3216 * The application is still waiting for the
3217 * completion of one or more requests:
3218 * prevent it from possibly being incorrectly
3219 * deemed as soft real-time by setting its
3220 * soft_rt_next_start to infinity. In fact,
3221 * without this assignment, the application
3222 * would be incorrectly deemed as soft
3223 * real-time if:
3224 * 1) it issued a new request before the
3225 * completion of all its in-flight
3226 * requests, and
3227 * 2) at that time, its soft_rt_next_start
3228 * happened to be in the past.
3229 */
3230 bfqq->soft_rt_next_start =
3231 bfq_greatest_from_now();
3232 /*
3233 * Schedule an update of soft_rt_next_start to when
3234 * the task may be discovered to be isochronous.
3235 */
3236 bfq_mark_bfqq_softrt_update(bfqq);
3237 }
3238 }
3239
Paolo Valenteaee69d72017-04-19 08:29:02 -06003240 bfq_log_bfqq(bfqd, bfqq,
Paolo Valented5be3fe2017-08-04 07:35:10 +02003241 "expire (%d, slow %d, num_disp %d, short_ttime %d)", reason,
3242 slow, bfqq->dispatched, bfq_bfqq_has_short_ttime(bfqq));
Paolo Valenteaee69d72017-04-19 08:29:02 -06003243
3244 /*
3245 * Increase, decrease or leave budget unchanged according to
3246 * reason.
3247 */
3248 __bfq_bfqq_recalc_budget(bfqd, bfqq, reason);
3249 ref = bfqq->ref;
3250 __bfq_bfqq_expire(bfqd, bfqq);
3251
3252 /* mark bfqq as waiting a request only if a bic still points to it */
3253 if (ref > 1 && !bfq_bfqq_busy(bfqq) &&
3254 reason != BFQQE_BUDGET_TIMEOUT &&
3255 reason != BFQQE_BUDGET_EXHAUSTED)
3256 bfq_mark_bfqq_non_blocking_wait_rq(bfqq);
3257}
3258
3259/*
3260 * Budget timeout is not implemented through a dedicated timer, but
3261 * just checked on request arrivals and completions, as well as on
3262 * idle timer expirations.
3263 */
3264static bool bfq_bfqq_budget_timeout(struct bfq_queue *bfqq)
3265{
Paolo Valente44e44a12017-04-12 18:23:12 +02003266 return time_is_before_eq_jiffies(bfqq->budget_timeout);
Paolo Valenteaee69d72017-04-19 08:29:02 -06003267}
3268
3269/*
3270 * If we expire a queue that is actively waiting (i.e., with the
3271 * device idled) for the arrival of a new request, then we may incur
3272 * the timestamp misalignment problem described in the body of the
3273 * function __bfq_activate_entity. Hence we return true only if this
3274 * condition does not hold, or if the queue is slow enough to deserve
3275 * only to be kicked off for preserving a high throughput.
3276 */
3277static bool bfq_may_expire_for_budg_timeout(struct bfq_queue *bfqq)
3278{
3279 bfq_log_bfqq(bfqq->bfqd, bfqq,
3280 "may_budget_timeout: wait_request %d left %d timeout %d",
3281 bfq_bfqq_wait_request(bfqq),
3282 bfq_bfqq_budget_left(bfqq) >= bfqq->entity.budget / 3,
3283 bfq_bfqq_budget_timeout(bfqq));
3284
3285 return (!bfq_bfqq_wait_request(bfqq) ||
3286 bfq_bfqq_budget_left(bfqq) >= bfqq->entity.budget / 3)
3287 &&
3288 bfq_bfqq_budget_timeout(bfqq);
3289}
3290
3291/*
3292 * For a queue that becomes empty, device idling is allowed only if
Paolo Valente44e44a12017-04-12 18:23:12 +02003293 * this function returns true for the queue. As a consequence, since
3294 * device idling plays a critical role in both throughput boosting and
3295 * service guarantees, the return value of this function plays a
3296 * critical role in both these aspects as well.
3297 *
3298 * In a nutshell, this function returns true only if idling is
3299 * beneficial for throughput or, even if detrimental for throughput,
3300 * idling is however necessary to preserve service guarantees (low
3301 * latency, desired throughput distribution, ...). In particular, on
3302 * NCQ-capable devices, this function tries to return false, so as to
3303 * help keep the drives' internal queues full, whenever this helps the
3304 * device boost the throughput without causing any service-guarantee
3305 * issue.
3306 *
3307 * In more detail, the return value of this function is obtained by,
3308 * first, computing a number of boolean variables that take into
3309 * account throughput and service-guarantee issues, and, then,
3310 * combining these variables in a logical expression. Most of the
3311 * issues taken into account are not trivial. We discuss these issues
3312 * individually while introducing the variables.
Paolo Valenteaee69d72017-04-19 08:29:02 -06003313 */
3314static bool bfq_bfqq_may_idle(struct bfq_queue *bfqq)
3315{
3316 struct bfq_data *bfqd = bfqq->bfqd;
Paolo Valenteedaf9422017-08-04 07:35:11 +02003317 bool rot_without_queueing =
3318 !blk_queue_nonrot(bfqd->queue) && !bfqd->hw_tag,
3319 bfqq_sequential_and_IO_bound,
3320 idling_boosts_thr, idling_boosts_thr_without_issues,
Arianna Avanzinie1b23242017-04-12 18:23:20 +02003321 idling_needed_for_service_guarantees,
Paolo Valentecfd69712017-04-12 18:23:15 +02003322 asymmetric_scenario;
Paolo Valenteaee69d72017-04-19 08:29:02 -06003323
3324 if (bfqd->strict_guarantees)
3325 return true;
3326
3327 /*
Paolo Valented5be3fe2017-08-04 07:35:10 +02003328 * Idling is performed only if slice_idle > 0. In addition, we
3329 * do not idle if
3330 * (a) bfqq is async
3331 * (b) bfqq is in the idle io prio class: in this case we do
3332 * not idle because we want to minimize the bandwidth that
3333 * queues in this class can steal to higher-priority queues
3334 */
3335 if (bfqd->bfq_slice_idle == 0 || !bfq_bfqq_sync(bfqq) ||
3336 bfq_class_idle(bfqq))
3337 return false;
3338
Paolo Valenteedaf9422017-08-04 07:35:11 +02003339 bfqq_sequential_and_IO_bound = !BFQQ_SEEKY(bfqq) &&
3340 bfq_bfqq_IO_bound(bfqq) && bfq_bfqq_has_short_ttime(bfqq);
3341
Paolo Valented5be3fe2017-08-04 07:35:10 +02003342 /*
Paolo Valente44e44a12017-04-12 18:23:12 +02003343 * The next variable takes into account the cases where idling
3344 * boosts the throughput.
3345 *
Paolo Valentee01eff02017-04-12 18:23:19 +02003346 * The value of the variable is computed considering, first, that
3347 * idling is virtually always beneficial for the throughput if:
Paolo Valenteedaf9422017-08-04 07:35:11 +02003348 * (a) the device is not NCQ-capable and rotational, or
3349 * (b) regardless of the presence of NCQ, the device is rotational and
3350 * the request pattern for bfqq is I/O-bound and sequential, or
3351 * (c) regardless of whether it is rotational, the device is
3352 * not NCQ-capable and the request pattern for bfqq is
3353 * I/O-bound and sequential.
Paolo Valentebf2b79e2017-04-12 18:23:18 +02003354 *
3355 * Secondly, and in contrast to the above item (b), idling an
3356 * NCQ-capable flash-based device would not boost the
Paolo Valentee01eff02017-04-12 18:23:19 +02003357 * throughput even with sequential I/O; rather it would lower
Paolo Valentebf2b79e2017-04-12 18:23:18 +02003358 * the throughput in proportion to how fast the device
3359 * is. Accordingly, the next variable is true if any of the
Paolo Valenteedaf9422017-08-04 07:35:11 +02003360 * above conditions (a), (b) or (c) is true, and, in
3361 * particular, happens to be false if bfqd is an NCQ-capable
3362 * flash-based device.
Paolo Valenteaee69d72017-04-19 08:29:02 -06003363 */
Paolo Valenteedaf9422017-08-04 07:35:11 +02003364 idling_boosts_thr = rot_without_queueing ||
3365 ((!blk_queue_nonrot(bfqd->queue) || !bfqd->hw_tag) &&
3366 bfqq_sequential_and_IO_bound);
Paolo Valenteaee69d72017-04-19 08:29:02 -06003367
3368 /*
Paolo Valentecfd69712017-04-12 18:23:15 +02003369 * The value of the next variable,
3370 * idling_boosts_thr_without_issues, is equal to that of
3371 * idling_boosts_thr, unless a special case holds. In this
3372 * special case, described below, idling may cause problems to
3373 * weight-raised queues.
3374 *
3375 * When the request pool is saturated (e.g., in the presence
3376 * of write hogs), if the processes associated with
3377 * non-weight-raised queues ask for requests at a lower rate,
3378 * then processes associated with weight-raised queues have a
3379 * higher probability to get a request from the pool
3380 * immediately (or at least soon) when they need one. Thus
3381 * they have a higher probability to actually get a fraction
3382 * of the device throughput proportional to their high
3383 * weight. This is especially true with NCQ-capable drives,
3384 * which enqueue several requests in advance, and further
3385 * reorder internally-queued requests.
3386 *
3387 * For this reason, we force to false the value of
3388 * idling_boosts_thr_without_issues if there are weight-raised
3389 * busy queues. In this case, and if bfqq is not weight-raised,
3390 * this guarantees that the device is not idled for bfqq (if,
3391 * instead, bfqq is weight-raised, then idling will be
3392 * guaranteed by another variable, see below). Combined with
3393 * the timestamping rules of BFQ (see [1] for details), this
3394 * behavior causes bfqq, and hence any sync non-weight-raised
3395 * queue, to get a lower number of requests served, and thus
3396 * to ask for a lower number of requests from the request
3397 * pool, before the busy weight-raised queues get served
3398 * again. This often mitigates starvation problems in the
3399 * presence of heavy write workloads and NCQ, thereby
3400 * guaranteeing a higher application and system responsiveness
3401 * in these hostile scenarios.
3402 */
3403 idling_boosts_thr_without_issues = idling_boosts_thr &&
3404 bfqd->wr_busy_queues == 0;
3405
3406 /*
Paolo Valentebf2b79e2017-04-12 18:23:18 +02003407 * There is then a case where idling must be performed not
3408 * for throughput concerns, but to preserve service
3409 * guarantees.
3410 *
3411 * To introduce this case, we can note that allowing the drive
3412 * to enqueue more than one request at a time, and hence
Paolo Valente44e44a12017-04-12 18:23:12 +02003413 * delegating de facto final scheduling decisions to the
Paolo Valentebf2b79e2017-04-12 18:23:18 +02003414 * drive's internal scheduler, entails loss of control on the
Paolo Valente44e44a12017-04-12 18:23:12 +02003415 * actual request service order. In particular, the critical
Paolo Valentebf2b79e2017-04-12 18:23:18 +02003416 * situation is when requests from different processes happen
Paolo Valente44e44a12017-04-12 18:23:12 +02003417 * to be present, at the same time, in the internal queue(s)
3418 * of the drive. In such a situation, the drive, by deciding
3419 * the service order of the internally-queued requests, does
3420 * determine also the actual throughput distribution among
3421 * these processes. But the drive typically has no notion or
3422 * concern about per-process throughput distribution, and
3423 * makes its decisions only on a per-request basis. Therefore,
3424 * the service distribution enforced by the drive's internal
3425 * scheduler is likely to coincide with the desired
3426 * device-throughput distribution only in a completely
Paolo Valentebf2b79e2017-04-12 18:23:18 +02003427 * symmetric scenario where:
3428 * (i) each of these processes must get the same throughput as
3429 * the others;
3430 * (ii) all these processes have the same I/O pattern
3431 (either sequential or random).
3432 * In fact, in such a scenario, the drive will tend to treat
3433 * the requests of each of these processes in about the same
3434 * way as the requests of the others, and thus to provide
3435 * each of these processes with about the same throughput
3436 * (which is exactly the desired throughput distribution). In
3437 * contrast, in any asymmetric scenario, device idling is
3438 * certainly needed to guarantee that bfqq receives its
3439 * assigned fraction of the device throughput (see [1] for
3440 * details).
Paolo Valente44e44a12017-04-12 18:23:12 +02003441 *
Paolo Valentebf2b79e2017-04-12 18:23:18 +02003442 * We address this issue by controlling, actually, only the
3443 * symmetry sub-condition (i), i.e., provided that
3444 * sub-condition (i) holds, idling is not performed,
3445 * regardless of whether sub-condition (ii) holds. In other
3446 * words, only if sub-condition (i) holds, then idling is
3447 * allowed, and the device tends to be prevented from queueing
3448 * many requests, possibly of several processes. The reason
3449 * for not controlling also sub-condition (ii) is that we
3450 * exploit preemption to preserve guarantees in case of
3451 * symmetric scenarios, even if (ii) does not hold, as
3452 * explained in the next two paragraphs.
Paolo Valente44e44a12017-04-12 18:23:12 +02003453 *
Paolo Valentebf2b79e2017-04-12 18:23:18 +02003454 * Even if a queue, say Q, is expired when it remains idle, Q
3455 * can still preempt the new in-service queue if the next
3456 * request of Q arrives soon (see the comments on
3457 * bfq_bfqq_update_budg_for_activation). If all queues and
3458 * groups have the same weight, this form of preemption,
3459 * combined with the hole-recovery heuristic described in the
3460 * comments on function bfq_bfqq_update_budg_for_activation,
3461 * are enough to preserve a correct bandwidth distribution in
3462 * the mid term, even without idling. In fact, even if not
3463 * idling allows the internal queues of the device to contain
3464 * many requests, and thus to reorder requests, we can rather
3465 * safely assume that the internal scheduler still preserves a
3466 * minimum of mid-term fairness. The motivation for using
3467 * preemption instead of idling is that, by not idling,
3468 * service guarantees are preserved without minimally
3469 * sacrificing throughput. In other words, both a high
3470 * throughput and its desired distribution are obtained.
3471 *
3472 * More precisely, this preemption-based, idleless approach
3473 * provides fairness in terms of IOPS, and not sectors per
3474 * second. This can be seen with a simple example. Suppose
3475 * that there are two queues with the same weight, but that
3476 * the first queue receives requests of 8 sectors, while the
3477 * second queue receives requests of 1024 sectors. In
3478 * addition, suppose that each of the two queues contains at
3479 * most one request at a time, which implies that each queue
3480 * always remains idle after it is served. Finally, after
3481 * remaining idle, each queue receives very quickly a new
3482 * request. It follows that the two queues are served
3483 * alternatively, preempting each other if needed. This
3484 * implies that, although both queues have the same weight,
3485 * the queue with large requests receives a service that is
3486 * 1024/8 times as high as the service received by the other
3487 * queue.
3488 *
3489 * On the other hand, device idling is performed, and thus
3490 * pure sector-domain guarantees are provided, for the
3491 * following queues, which are likely to need stronger
3492 * throughput guarantees: weight-raised queues, and queues
3493 * with a higher weight than other queues. When such queues
3494 * are active, sub-condition (i) is false, which triggers
3495 * device idling.
3496 *
3497 * According to the above considerations, the next variable is
3498 * true (only) if sub-condition (i) holds. To compute the
3499 * value of this variable, we not only use the return value of
3500 * the function bfq_symmetric_scenario(), but also check
3501 * whether bfqq is being weight-raised, because
3502 * bfq_symmetric_scenario() does not take into account also
3503 * weight-raised queues (see comments on
3504 * bfq_weights_tree_add()).
Paolo Valente44e44a12017-04-12 18:23:12 +02003505 *
3506 * As a side note, it is worth considering that the above
3507 * device-idling countermeasures may however fail in the
3508 * following unlucky scenario: if idling is (correctly)
Paolo Valentebf2b79e2017-04-12 18:23:18 +02003509 * disabled in a time period during which all symmetry
3510 * sub-conditions hold, and hence the device is allowed to
Paolo Valente44e44a12017-04-12 18:23:12 +02003511 * enqueue many requests, but at some later point in time some
3512 * sub-condition stops to hold, then it may become impossible
3513 * to let requests be served in the desired order until all
3514 * the requests already queued in the device have been served.
Paolo Valenteaee69d72017-04-19 08:29:02 -06003515 */
Paolo Valentebf2b79e2017-04-12 18:23:18 +02003516 asymmetric_scenario = bfqq->wr_coeff > 1 ||
3517 !bfq_symmetric_scenario(bfqd);
Paolo Valente44e44a12017-04-12 18:23:12 +02003518
3519 /*
Arianna Avanzinie1b23242017-04-12 18:23:20 +02003520 * Finally, there is a case where maximizing throughput is the
3521 * best choice even if it may cause unfairness toward
3522 * bfqq. Such a case is when bfqq became active in a burst of
3523 * queue activations. Queues that became active during a large
3524 * burst benefit only from throughput, as discussed in the
3525 * comments on bfq_handle_burst. Thus, if bfqq became active
3526 * in a burst and not idling the device maximizes throughput,
3527 * then the device must no be idled, because not idling the
3528 * device provides bfqq and all other queues in the burst with
3529 * maximum benefit. Combining this and the above case, we can
3530 * now establish when idling is actually needed to preserve
3531 * service guarantees.
3532 */
3533 idling_needed_for_service_guarantees =
3534 asymmetric_scenario && !bfq_bfqq_in_large_burst(bfqq);
3535
3536 /*
Paolo Valented5be3fe2017-08-04 07:35:10 +02003537 * We have now all the components we need to compute the
3538 * return value of the function, which is true only if idling
3539 * either boosts the throughput (without issues), or is
3540 * necessary to preserve service guarantees.
Paolo Valente44e44a12017-04-12 18:23:12 +02003541 */
Paolo Valented5be3fe2017-08-04 07:35:10 +02003542 return idling_boosts_thr_without_issues ||
3543 idling_needed_for_service_guarantees;
Paolo Valenteaee69d72017-04-19 08:29:02 -06003544}
3545
3546/*
3547 * If the in-service queue is empty but the function bfq_bfqq_may_idle
3548 * returns true, then:
3549 * 1) the queue must remain in service and cannot be expired, and
3550 * 2) the device must be idled to wait for the possible arrival of a new
3551 * request for the queue.
3552 * See the comments on the function bfq_bfqq_may_idle for the reasons
3553 * why performing device idling is the best choice to boost the throughput
3554 * and preserve service guarantees when bfq_bfqq_may_idle itself
3555 * returns true.
3556 */
3557static bool bfq_bfqq_must_idle(struct bfq_queue *bfqq)
3558{
Paolo Valented5be3fe2017-08-04 07:35:10 +02003559 return RB_EMPTY_ROOT(&bfqq->sort_list) && bfq_bfqq_may_idle(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06003560}
3561
3562/*
3563 * Select a queue for service. If we have a current queue in service,
3564 * check whether to continue servicing it, or retrieve and set a new one.
3565 */
3566static struct bfq_queue *bfq_select_queue(struct bfq_data *bfqd)
3567{
3568 struct bfq_queue *bfqq;
3569 struct request *next_rq;
3570 enum bfqq_expiration reason = BFQQE_BUDGET_TIMEOUT;
3571
3572 bfqq = bfqd->in_service_queue;
3573 if (!bfqq)
3574 goto new_queue;
3575
3576 bfq_log_bfqq(bfqd, bfqq, "select_queue: already in-service queue");
3577
3578 if (bfq_may_expire_for_budg_timeout(bfqq) &&
3579 !bfq_bfqq_wait_request(bfqq) &&
3580 !bfq_bfqq_must_idle(bfqq))
3581 goto expire;
3582
3583check_queue:
3584 /*
3585 * This loop is rarely executed more than once. Even when it
3586 * happens, it is much more convenient to re-execute this loop
3587 * than to return NULL and trigger a new dispatch to get a
3588 * request served.
3589 */
3590 next_rq = bfqq->next_rq;
3591 /*
3592 * If bfqq has requests queued and it has enough budget left to
3593 * serve them, keep the queue, otherwise expire it.
3594 */
3595 if (next_rq) {
3596 if (bfq_serv_to_charge(next_rq, bfqq) >
3597 bfq_bfqq_budget_left(bfqq)) {
3598 /*
3599 * Expire the queue for budget exhaustion,
3600 * which makes sure that the next budget is
3601 * enough to serve the next request, even if
3602 * it comes from the fifo expired path.
3603 */
3604 reason = BFQQE_BUDGET_EXHAUSTED;
3605 goto expire;
3606 } else {
3607 /*
3608 * The idle timer may be pending because we may
3609 * not disable disk idling even when a new request
3610 * arrives.
3611 */
3612 if (bfq_bfqq_wait_request(bfqq)) {
3613 /*
3614 * If we get here: 1) at least a new request
3615 * has arrived but we have not disabled the
3616 * timer because the request was too small,
3617 * 2) then the block layer has unplugged
3618 * the device, causing the dispatch to be
3619 * invoked.
3620 *
3621 * Since the device is unplugged, now the
3622 * requests are probably large enough to
3623 * provide a reasonable throughput.
3624 * So we disable idling.
3625 */
3626 bfq_clear_bfqq_wait_request(bfqq);
3627 hrtimer_try_to_cancel(&bfqd->idle_slice_timer);
3628 }
3629 goto keep_queue;
3630 }
3631 }
3632
3633 /*
3634 * No requests pending. However, if the in-service queue is idling
3635 * for a new request, or has requests waiting for a completion and
3636 * may idle after their completion, then keep it anyway.
3637 */
3638 if (bfq_bfqq_wait_request(bfqq) ||
3639 (bfqq->dispatched != 0 && bfq_bfqq_may_idle(bfqq))) {
3640 bfqq = NULL;
3641 goto keep_queue;
3642 }
3643
3644 reason = BFQQE_NO_MORE_REQUESTS;
3645expire:
3646 bfq_bfqq_expire(bfqd, bfqq, false, reason);
3647new_queue:
3648 bfqq = bfq_set_in_service_queue(bfqd);
3649 if (bfqq) {
3650 bfq_log_bfqq(bfqd, bfqq, "select_queue: checking new queue");
3651 goto check_queue;
3652 }
3653keep_queue:
3654 if (bfqq)
3655 bfq_log_bfqq(bfqd, bfqq, "select_queue: returned this queue");
3656 else
3657 bfq_log(bfqd, "select_queue: no queue returned");
3658
3659 return bfqq;
3660}
3661
Paolo Valente44e44a12017-04-12 18:23:12 +02003662static void bfq_update_wr_data(struct bfq_data *bfqd, struct bfq_queue *bfqq)
3663{
3664 struct bfq_entity *entity = &bfqq->entity;
3665
3666 if (bfqq->wr_coeff > 1) { /* queue is being weight-raised */
3667 bfq_log_bfqq(bfqd, bfqq,
3668 "raising period dur %u/%u msec, old coeff %u, w %d(%d)",
3669 jiffies_to_msecs(jiffies - bfqq->last_wr_start_finish),
3670 jiffies_to_msecs(bfqq->wr_cur_max_time),
3671 bfqq->wr_coeff,
3672 bfqq->entity.weight, bfqq->entity.orig_weight);
3673
3674 if (entity->prio_changed)
3675 bfq_log_bfqq(bfqd, bfqq, "WARN: pending prio change");
3676
3677 /*
Arianna Avanzinie1b23242017-04-12 18:23:20 +02003678 * If the queue was activated in a burst, or too much
3679 * time has elapsed from the beginning of this
3680 * weight-raising period, then end weight raising.
Paolo Valente44e44a12017-04-12 18:23:12 +02003681 */
Arianna Avanzinie1b23242017-04-12 18:23:20 +02003682 if (bfq_bfqq_in_large_burst(bfqq))
3683 bfq_bfqq_end_wr(bfqq);
3684 else if (time_is_before_jiffies(bfqq->last_wr_start_finish +
3685 bfqq->wr_cur_max_time)) {
Paolo Valente77b7dce2017-04-12 18:23:13 +02003686 if (bfqq->wr_cur_max_time != bfqd->bfq_wr_rt_max_time ||
3687 time_is_before_jiffies(bfqq->wr_start_at_switch_to_srt +
Arianna Avanzinie1b23242017-04-12 18:23:20 +02003688 bfq_wr_duration(bfqd)))
Paolo Valente77b7dce2017-04-12 18:23:13 +02003689 bfq_bfqq_end_wr(bfqq);
3690 else {
Paolo Valente3e2bdd62017-09-21 11:04:01 +02003691 switch_back_to_interactive_wr(bfqq, bfqd);
Paolo Valente77b7dce2017-04-12 18:23:13 +02003692 bfqq->entity.prio_changed = 1;
3693 }
Paolo Valente44e44a12017-04-12 18:23:12 +02003694 }
Paolo Valente8a8747d2018-01-13 12:05:18 +01003695 if (bfqq->wr_coeff > 1 &&
3696 bfqq->wr_cur_max_time != bfqd->bfq_wr_rt_max_time &&
3697 bfqq->service_from_wr > max_service_from_wr) {
3698 /* see comments on max_service_from_wr */
3699 bfq_bfqq_end_wr(bfqq);
3700 }
Paolo Valente44e44a12017-04-12 18:23:12 +02003701 }
Paolo Valente431b17f2017-07-03 10:00:10 +02003702 /*
3703 * To improve latency (for this or other queues), immediately
3704 * update weight both if it must be raised and if it must be
3705 * lowered. Since, entity may be on some active tree here, and
3706 * might have a pending change of its ioprio class, invoke
3707 * next function with the last parameter unset (see the
3708 * comments on the function).
3709 */
Paolo Valente44e44a12017-04-12 18:23:12 +02003710 if ((entity->weight > entity->orig_weight) != (bfqq->wr_coeff > 1))
Paolo Valente431b17f2017-07-03 10:00:10 +02003711 __bfq_entity_update_weight_prio(bfq_entity_service_tree(entity),
3712 entity, false);
Paolo Valente44e44a12017-04-12 18:23:12 +02003713}
3714
Paolo Valenteaee69d72017-04-19 08:29:02 -06003715/*
3716 * Dispatch next request from bfqq.
3717 */
3718static struct request *bfq_dispatch_rq_from_bfqq(struct bfq_data *bfqd,
3719 struct bfq_queue *bfqq)
3720{
3721 struct request *rq = bfqq->next_rq;
3722 unsigned long service_to_charge;
3723
3724 service_to_charge = bfq_serv_to_charge(rq, bfqq);
3725
3726 bfq_bfqq_served(bfqq, service_to_charge);
3727
3728 bfq_dispatch_remove(bfqd->queue, rq);
3729
Paolo Valente44e44a12017-04-12 18:23:12 +02003730 /*
3731 * If weight raising has to terminate for bfqq, then next
3732 * function causes an immediate update of bfqq's weight,
3733 * without waiting for next activation. As a consequence, on
3734 * expiration, bfqq will be timestamped as if has never been
3735 * weight-raised during this service slot, even if it has
3736 * received part or even most of the service as a
3737 * weight-raised queue. This inflates bfqq's timestamps, which
3738 * is beneficial, as bfqq is then more willing to leave the
3739 * device immediately to possible other weight-raised queues.
3740 */
3741 bfq_update_wr_data(bfqd, bfqq);
3742
Paolo Valenteaee69d72017-04-19 08:29:02 -06003743 /*
3744 * Expire bfqq, pretending that its budget expired, if bfqq
3745 * belongs to CLASS_IDLE and other queues are waiting for
3746 * service.
3747 */
3748 if (bfqd->busy_queues > 1 && bfq_class_idle(bfqq))
3749 goto expire;
3750
3751 return rq;
3752
3753expire:
3754 bfq_bfqq_expire(bfqd, bfqq, false, BFQQE_BUDGET_EXHAUSTED);
3755 return rq;
3756}
3757
3758static bool bfq_has_work(struct blk_mq_hw_ctx *hctx)
3759{
3760 struct bfq_data *bfqd = hctx->queue->elevator->elevator_data;
3761
3762 /*
3763 * Avoiding lock: a race on bfqd->busy_queues should cause at
3764 * most a call to dispatch for nothing
3765 */
3766 return !list_empty_careful(&bfqd->dispatch) ||
3767 bfqd->busy_queues > 0;
3768}
3769
3770static struct request *__bfq_dispatch_request(struct blk_mq_hw_ctx *hctx)
3771{
3772 struct bfq_data *bfqd = hctx->queue->elevator->elevator_data;
3773 struct request *rq = NULL;
3774 struct bfq_queue *bfqq = NULL;
3775
3776 if (!list_empty(&bfqd->dispatch)) {
3777 rq = list_first_entry(&bfqd->dispatch, struct request,
3778 queuelist);
3779 list_del_init(&rq->queuelist);
3780
3781 bfqq = RQ_BFQQ(rq);
3782
3783 if (bfqq) {
3784 /*
3785 * Increment counters here, because this
3786 * dispatch does not follow the standard
3787 * dispatch flow (where counters are
3788 * incremented)
3789 */
3790 bfqq->dispatched++;
3791
3792 goto inc_in_driver_start_rq;
3793 }
3794
3795 /*
Paolo Valentea7877392018-02-07 22:19:20 +01003796 * We exploit the bfq_finish_requeue_request hook to
3797 * decrement rq_in_driver, but
3798 * bfq_finish_requeue_request will not be invoked on
3799 * this request. So, to avoid unbalance, just start
3800 * this request, without incrementing rq_in_driver. As
3801 * a negative consequence, rq_in_driver is deceptively
3802 * lower than it should be while this request is in
3803 * service. This may cause bfq_schedule_dispatch to be
3804 * invoked uselessly.
Paolo Valenteaee69d72017-04-19 08:29:02 -06003805 *
3806 * As for implementing an exact solution, the
Paolo Valentea7877392018-02-07 22:19:20 +01003807 * bfq_finish_requeue_request hook, if defined, is
3808 * probably invoked also on this request. So, by
3809 * exploiting this hook, we could 1) increment
3810 * rq_in_driver here, and 2) decrement it in
3811 * bfq_finish_requeue_request. Such a solution would
3812 * let the value of the counter be always accurate,
3813 * but it would entail using an extra interface
3814 * function. This cost seems higher than the benefit,
3815 * being the frequency of non-elevator-private
Paolo Valenteaee69d72017-04-19 08:29:02 -06003816 * requests very low.
3817 */
3818 goto start_rq;
3819 }
3820
3821 bfq_log(bfqd, "dispatch requests: %d busy queues", bfqd->busy_queues);
3822
3823 if (bfqd->busy_queues == 0)
3824 goto exit;
3825
3826 /*
3827 * Force device to serve one request at a time if
3828 * strict_guarantees is true. Forcing this service scheme is
3829 * currently the ONLY way to guarantee that the request
3830 * service order enforced by the scheduler is respected by a
3831 * queueing device. Otherwise the device is free even to make
3832 * some unlucky request wait for as long as the device
3833 * wishes.
3834 *
3835 * Of course, serving one request at at time may cause loss of
3836 * throughput.
3837 */
3838 if (bfqd->strict_guarantees && bfqd->rq_in_driver > 0)
3839 goto exit;
3840
3841 bfqq = bfq_select_queue(bfqd);
3842 if (!bfqq)
3843 goto exit;
3844
3845 rq = bfq_dispatch_rq_from_bfqq(bfqd, bfqq);
3846
3847 if (rq) {
3848inc_in_driver_start_rq:
3849 bfqd->rq_in_driver++;
3850start_rq:
3851 rq->rq_flags |= RQF_STARTED;
3852 }
3853exit:
3854 return rq;
3855}
3856
Paolo Valente9b25bd02017-12-04 11:42:05 +01003857#if defined(CONFIG_BFQ_GROUP_IOSCHED) && defined(CONFIG_DEBUG_BLK_CGROUP)
3858static void bfq_update_dispatch_stats(struct request_queue *q,
3859 struct request *rq,
3860 struct bfq_queue *in_serv_queue,
3861 bool idle_timer_disabled)
Paolo Valenteaee69d72017-04-19 08:29:02 -06003862{
Paolo Valente9b25bd02017-12-04 11:42:05 +01003863 struct bfq_queue *bfqq = rq ? RQ_BFQQ(rq) : NULL;
Paolo Valenteaee69d72017-04-19 08:29:02 -06003864
Paolo Valente24bfd192017-11-13 07:34:09 +01003865 if (!idle_timer_disabled && !bfqq)
Paolo Valente9b25bd02017-12-04 11:42:05 +01003866 return;
Paolo Valente24bfd192017-11-13 07:34:09 +01003867
3868 /*
3869 * rq and bfqq are guaranteed to exist until this function
3870 * ends, for the following reasons. First, rq can be
3871 * dispatched to the device, and then can be completed and
3872 * freed, only after this function ends. Second, rq cannot be
3873 * merged (and thus freed because of a merge) any longer,
3874 * because it has already started. Thus rq cannot be freed
3875 * before this function ends, and, since rq has a reference to
3876 * bfqq, the same guarantee holds for bfqq too.
3877 *
3878 * In addition, the following queue lock guarantees that
3879 * bfqq_group(bfqq) exists as well.
3880 */
Paolo Valente9b25bd02017-12-04 11:42:05 +01003881 spin_lock_irq(q->queue_lock);
Paolo Valente24bfd192017-11-13 07:34:09 +01003882 if (idle_timer_disabled)
3883 /*
3884 * Since the idle timer has been disabled,
3885 * in_serv_queue contained some request when
3886 * __bfq_dispatch_request was invoked above, which
3887 * implies that rq was picked exactly from
3888 * in_serv_queue. Thus in_serv_queue == bfqq, and is
3889 * therefore guaranteed to exist because of the above
3890 * arguments.
3891 */
3892 bfqg_stats_update_idle_time(bfqq_group(in_serv_queue));
3893 if (bfqq) {
3894 struct bfq_group *bfqg = bfqq_group(bfqq);
3895
3896 bfqg_stats_update_avg_queue_size(bfqg);
3897 bfqg_stats_set_start_empty_time(bfqg);
3898 bfqg_stats_update_io_remove(bfqg, rq->cmd_flags);
3899 }
Paolo Valente9b25bd02017-12-04 11:42:05 +01003900 spin_unlock_irq(q->queue_lock);
3901}
3902#else
3903static inline void bfq_update_dispatch_stats(struct request_queue *q,
3904 struct request *rq,
3905 struct bfq_queue *in_serv_queue,
3906 bool idle_timer_disabled) {}
Paolo Valente24bfd192017-11-13 07:34:09 +01003907#endif
3908
Paolo Valente9b25bd02017-12-04 11:42:05 +01003909static struct request *bfq_dispatch_request(struct blk_mq_hw_ctx *hctx)
3910{
3911 struct bfq_data *bfqd = hctx->queue->elevator->elevator_data;
3912 struct request *rq;
3913 struct bfq_queue *in_serv_queue;
3914 bool waiting_rq, idle_timer_disabled;
3915
3916 spin_lock_irq(&bfqd->lock);
3917
3918 in_serv_queue = bfqd->in_service_queue;
3919 waiting_rq = in_serv_queue && bfq_bfqq_wait_request(in_serv_queue);
3920
3921 rq = __bfq_dispatch_request(hctx);
3922
3923 idle_timer_disabled =
3924 waiting_rq && !bfq_bfqq_wait_request(in_serv_queue);
3925
3926 spin_unlock_irq(&bfqd->lock);
3927
3928 bfq_update_dispatch_stats(hctx->queue, rq, in_serv_queue,
3929 idle_timer_disabled);
3930
Paolo Valenteaee69d72017-04-19 08:29:02 -06003931 return rq;
3932}
3933
3934/*
3935 * Task holds one reference to the queue, dropped when task exits. Each rq
3936 * in-flight on this queue also holds a reference, dropped when rq is freed.
3937 *
3938 * Scheduler lock must be held here. Recall not to use bfqq after calling
3939 * this function on it.
3940 */
Paolo Valenteea25da42017-04-19 08:48:24 -06003941void bfq_put_queue(struct bfq_queue *bfqq)
Paolo Valenteaee69d72017-04-19 08:29:02 -06003942{
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02003943#ifdef CONFIG_BFQ_GROUP_IOSCHED
3944 struct bfq_group *bfqg = bfqq_group(bfqq);
3945#endif
3946
Paolo Valenteaee69d72017-04-19 08:29:02 -06003947 if (bfqq->bfqd)
3948 bfq_log_bfqq(bfqq->bfqd, bfqq, "put_queue: %p %d",
3949 bfqq, bfqq->ref);
3950
3951 bfqq->ref--;
3952 if (bfqq->ref)
3953 return;
3954
Paolo Valente99fead82017-10-09 13:11:23 +02003955 if (!hlist_unhashed(&bfqq->burst_list_node)) {
Arianna Avanzinie1b23242017-04-12 18:23:20 +02003956 hlist_del_init(&bfqq->burst_list_node);
Paolo Valente99fead82017-10-09 13:11:23 +02003957 /*
3958 * Decrement also burst size after the removal, if the
3959 * process associated with bfqq is exiting, and thus
3960 * does not contribute to the burst any longer. This
3961 * decrement helps filter out false positives of large
3962 * bursts, when some short-lived process (often due to
3963 * the execution of commands by some service) happens
3964 * to start and exit while a complex application is
3965 * starting, and thus spawning several processes that
3966 * do I/O (and that *must not* be treated as a large
3967 * burst, see comments on bfq_handle_burst).
3968 *
3969 * In particular, the decrement is performed only if:
3970 * 1) bfqq is not a merged queue, because, if it is,
3971 * then this free of bfqq is not triggered by the exit
3972 * of the process bfqq is associated with, but exactly
3973 * by the fact that bfqq has just been merged.
3974 * 2) burst_size is greater than 0, to handle
3975 * unbalanced decrements. Unbalanced decrements may
3976 * happen in te following case: bfqq is inserted into
3977 * the current burst list--without incrementing
3978 * bust_size--because of a split, but the current
3979 * burst list is not the burst list bfqq belonged to
3980 * (see comments on the case of a split in
3981 * bfq_set_request).
3982 */
3983 if (bfqq->bic && bfqq->bfqd->burst_size > 0)
3984 bfqq->bfqd->burst_size--;
Paolo Valente7cb04002017-09-21 11:04:03 +02003985 }
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02003986
Paolo Valenteaee69d72017-04-19 08:29:02 -06003987 kmem_cache_free(bfq_pool, bfqq);
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02003988#ifdef CONFIG_BFQ_GROUP_IOSCHED
Paolo Valente8f9bebc2017-06-05 10:11:15 +02003989 bfqg_and_blkg_put(bfqg);
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02003990#endif
Paolo Valenteaee69d72017-04-19 08:29:02 -06003991}
3992
Arianna Avanzini36eca892017-04-12 18:23:16 +02003993static void bfq_put_cooperator(struct bfq_queue *bfqq)
3994{
3995 struct bfq_queue *__bfqq, *next;
3996
3997 /*
3998 * If this queue was scheduled to merge with another queue, be
3999 * sure to drop the reference taken on that queue (and others in
4000 * the merge chain). See bfq_setup_merge and bfq_merge_bfqqs.
4001 */
4002 __bfqq = bfqq->new_bfqq;
4003 while (__bfqq) {
4004 if (__bfqq == bfqq)
4005 break;
4006 next = __bfqq->new_bfqq;
4007 bfq_put_queue(__bfqq);
4008 __bfqq = next;
4009 }
4010}
4011
Paolo Valenteaee69d72017-04-19 08:29:02 -06004012static void bfq_exit_bfqq(struct bfq_data *bfqd, struct bfq_queue *bfqq)
4013{
4014 if (bfqq == bfqd->in_service_queue) {
4015 __bfq_bfqq_expire(bfqd, bfqq);
4016 bfq_schedule_dispatch(bfqd);
4017 }
4018
4019 bfq_log_bfqq(bfqd, bfqq, "exit_bfqq: %p, %d", bfqq, bfqq->ref);
4020
Arianna Avanzini36eca892017-04-12 18:23:16 +02004021 bfq_put_cooperator(bfqq);
4022
Paolo Valenteaee69d72017-04-19 08:29:02 -06004023 bfq_put_queue(bfqq); /* release process reference */
4024}
4025
4026static void bfq_exit_icq_bfqq(struct bfq_io_cq *bic, bool is_sync)
4027{
4028 struct bfq_queue *bfqq = bic_to_bfqq(bic, is_sync);
4029 struct bfq_data *bfqd;
4030
4031 if (bfqq)
4032 bfqd = bfqq->bfqd; /* NULL if scheduler already exited */
4033
4034 if (bfqq && bfqd) {
4035 unsigned long flags;
4036
4037 spin_lock_irqsave(&bfqd->lock, flags);
4038 bfq_exit_bfqq(bfqd, bfqq);
4039 bic_set_bfqq(bic, NULL, is_sync);
Paolo Valente6fa3e8d2017-04-12 18:23:21 +02004040 spin_unlock_irqrestore(&bfqd->lock, flags);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004041 }
4042}
4043
4044static void bfq_exit_icq(struct io_cq *icq)
4045{
4046 struct bfq_io_cq *bic = icq_to_bic(icq);
4047
4048 bfq_exit_icq_bfqq(bic, true);
4049 bfq_exit_icq_bfqq(bic, false);
4050}
4051
4052/*
4053 * Update the entity prio values; note that the new values will not
4054 * be used until the next (re)activation.
4055 */
4056static void
4057bfq_set_next_ioprio_data(struct bfq_queue *bfqq, struct bfq_io_cq *bic)
4058{
4059 struct task_struct *tsk = current;
4060 int ioprio_class;
4061 struct bfq_data *bfqd = bfqq->bfqd;
4062
4063 if (!bfqd)
4064 return;
4065
4066 ioprio_class = IOPRIO_PRIO_CLASS(bic->ioprio);
4067 switch (ioprio_class) {
4068 default:
4069 dev_err(bfqq->bfqd->queue->backing_dev_info->dev,
4070 "bfq: bad prio class %d\n", ioprio_class);
Bart Van Asschefa393d12017-08-30 11:42:07 -07004071 /* fall through */
Paolo Valenteaee69d72017-04-19 08:29:02 -06004072 case IOPRIO_CLASS_NONE:
4073 /*
4074 * No prio set, inherit CPU scheduling settings.
4075 */
4076 bfqq->new_ioprio = task_nice_ioprio(tsk);
4077 bfqq->new_ioprio_class = task_nice_ioclass(tsk);
4078 break;
4079 case IOPRIO_CLASS_RT:
4080 bfqq->new_ioprio = IOPRIO_PRIO_DATA(bic->ioprio);
4081 bfqq->new_ioprio_class = IOPRIO_CLASS_RT;
4082 break;
4083 case IOPRIO_CLASS_BE:
4084 bfqq->new_ioprio = IOPRIO_PRIO_DATA(bic->ioprio);
4085 bfqq->new_ioprio_class = IOPRIO_CLASS_BE;
4086 break;
4087 case IOPRIO_CLASS_IDLE:
4088 bfqq->new_ioprio_class = IOPRIO_CLASS_IDLE;
4089 bfqq->new_ioprio = 7;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004090 break;
4091 }
4092
4093 if (bfqq->new_ioprio >= IOPRIO_BE_NR) {
4094 pr_crit("bfq_set_next_ioprio_data: new_ioprio %d\n",
4095 bfqq->new_ioprio);
4096 bfqq->new_ioprio = IOPRIO_BE_NR;
4097 }
4098
4099 bfqq->entity.new_weight = bfq_ioprio_to_weight(bfqq->new_ioprio);
4100 bfqq->entity.prio_changed = 1;
4101}
4102
Paolo Valenteea25da42017-04-19 08:48:24 -06004103static struct bfq_queue *bfq_get_queue(struct bfq_data *bfqd,
4104 struct bio *bio, bool is_sync,
4105 struct bfq_io_cq *bic);
4106
Paolo Valenteaee69d72017-04-19 08:29:02 -06004107static void bfq_check_ioprio_change(struct bfq_io_cq *bic, struct bio *bio)
4108{
4109 struct bfq_data *bfqd = bic_to_bfqd(bic);
4110 struct bfq_queue *bfqq;
4111 int ioprio = bic->icq.ioc->ioprio;
4112
4113 /*
4114 * This condition may trigger on a newly created bic, be sure to
4115 * drop the lock before returning.
4116 */
4117 if (unlikely(!bfqd) || likely(bic->ioprio == ioprio))
4118 return;
4119
4120 bic->ioprio = ioprio;
4121
4122 bfqq = bic_to_bfqq(bic, false);
4123 if (bfqq) {
4124 /* release process reference on this queue */
4125 bfq_put_queue(bfqq);
4126 bfqq = bfq_get_queue(bfqd, bio, BLK_RW_ASYNC, bic);
4127 bic_set_bfqq(bic, bfqq, false);
4128 }
4129
4130 bfqq = bic_to_bfqq(bic, true);
4131 if (bfqq)
4132 bfq_set_next_ioprio_data(bfqq, bic);
4133}
4134
4135static void bfq_init_bfqq(struct bfq_data *bfqd, struct bfq_queue *bfqq,
4136 struct bfq_io_cq *bic, pid_t pid, int is_sync)
4137{
4138 RB_CLEAR_NODE(&bfqq->entity.rb_node);
4139 INIT_LIST_HEAD(&bfqq->fifo);
Arianna Avanzinie1b23242017-04-12 18:23:20 +02004140 INIT_HLIST_NODE(&bfqq->burst_list_node);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004141
4142 bfqq->ref = 0;
4143 bfqq->bfqd = bfqd;
4144
4145 if (bic)
4146 bfq_set_next_ioprio_data(bfqq, bic);
4147
4148 if (is_sync) {
Paolo Valented5be3fe2017-08-04 07:35:10 +02004149 /*
4150 * No need to mark as has_short_ttime if in
4151 * idle_class, because no device idling is performed
4152 * for queues in idle class
4153 */
Paolo Valenteaee69d72017-04-19 08:29:02 -06004154 if (!bfq_class_idle(bfqq))
Paolo Valented5be3fe2017-08-04 07:35:10 +02004155 /* tentatively mark as has_short_ttime */
4156 bfq_mark_bfqq_has_short_ttime(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004157 bfq_mark_bfqq_sync(bfqq);
Arianna Avanzinie1b23242017-04-12 18:23:20 +02004158 bfq_mark_bfqq_just_created(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004159 } else
4160 bfq_clear_bfqq_sync(bfqq);
4161
4162 /* set end request to minus infinity from now */
4163 bfqq->ttime.last_end_request = ktime_get_ns() + 1;
4164
4165 bfq_mark_bfqq_IO_bound(bfqq);
4166
4167 bfqq->pid = pid;
4168
4169 /* Tentative initial value to trade off between thr and lat */
Paolo Valente54b60452017-04-12 18:23:09 +02004170 bfqq->max_budget = (2 * bfq_max_budget(bfqd)) / 3;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004171 bfqq->budget_timeout = bfq_smallest_from_now();
Paolo Valenteaee69d72017-04-19 08:29:02 -06004172
Paolo Valente44e44a12017-04-12 18:23:12 +02004173 bfqq->wr_coeff = 1;
Arianna Avanzini36eca892017-04-12 18:23:16 +02004174 bfqq->last_wr_start_finish = jiffies;
Paolo Valente77b7dce2017-04-12 18:23:13 +02004175 bfqq->wr_start_at_switch_to_srt = bfq_smallest_from_now();
Arianna Avanzini36eca892017-04-12 18:23:16 +02004176 bfqq->split_time = bfq_smallest_from_now();
Paolo Valente77b7dce2017-04-12 18:23:13 +02004177
4178 /*
Paolo Valentea34b0242017-12-15 07:23:12 +01004179 * To not forget the possibly high bandwidth consumed by a
4180 * process/queue in the recent past,
4181 * bfq_bfqq_softrt_next_start() returns a value at least equal
4182 * to the current value of bfqq->soft_rt_next_start (see
4183 * comments on bfq_bfqq_softrt_next_start). Set
4184 * soft_rt_next_start to now, to mean that bfqq has consumed
4185 * no bandwidth so far.
Paolo Valente77b7dce2017-04-12 18:23:13 +02004186 */
Paolo Valentea34b0242017-12-15 07:23:12 +01004187 bfqq->soft_rt_next_start = jiffies;
Paolo Valente44e44a12017-04-12 18:23:12 +02004188
Paolo Valenteaee69d72017-04-19 08:29:02 -06004189 /* first request is almost certainly seeky */
4190 bfqq->seek_history = 1;
4191}
4192
4193static struct bfq_queue **bfq_async_queue_prio(struct bfq_data *bfqd,
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004194 struct bfq_group *bfqg,
Paolo Valenteaee69d72017-04-19 08:29:02 -06004195 int ioprio_class, int ioprio)
4196{
4197 switch (ioprio_class) {
4198 case IOPRIO_CLASS_RT:
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004199 return &bfqg->async_bfqq[0][ioprio];
Paolo Valenteaee69d72017-04-19 08:29:02 -06004200 case IOPRIO_CLASS_NONE:
4201 ioprio = IOPRIO_NORM;
4202 /* fall through */
4203 case IOPRIO_CLASS_BE:
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004204 return &bfqg->async_bfqq[1][ioprio];
Paolo Valenteaee69d72017-04-19 08:29:02 -06004205 case IOPRIO_CLASS_IDLE:
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004206 return &bfqg->async_idle_bfqq;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004207 default:
4208 return NULL;
4209 }
4210}
4211
4212static struct bfq_queue *bfq_get_queue(struct bfq_data *bfqd,
4213 struct bio *bio, bool is_sync,
4214 struct bfq_io_cq *bic)
4215{
4216 const int ioprio = IOPRIO_PRIO_DATA(bic->ioprio);
4217 const int ioprio_class = IOPRIO_PRIO_CLASS(bic->ioprio);
4218 struct bfq_queue **async_bfqq = NULL;
4219 struct bfq_queue *bfqq;
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004220 struct bfq_group *bfqg;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004221
4222 rcu_read_lock();
4223
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004224 bfqg = bfq_find_set_group(bfqd, bio_blkcg(bio));
4225 if (!bfqg) {
4226 bfqq = &bfqd->oom_bfqq;
4227 goto out;
4228 }
4229
Paolo Valenteaee69d72017-04-19 08:29:02 -06004230 if (!is_sync) {
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004231 async_bfqq = bfq_async_queue_prio(bfqd, bfqg, ioprio_class,
Paolo Valenteaee69d72017-04-19 08:29:02 -06004232 ioprio);
4233 bfqq = *async_bfqq;
4234 if (bfqq)
4235 goto out;
4236 }
4237
4238 bfqq = kmem_cache_alloc_node(bfq_pool,
4239 GFP_NOWAIT | __GFP_ZERO | __GFP_NOWARN,
4240 bfqd->queue->node);
4241
4242 if (bfqq) {
4243 bfq_init_bfqq(bfqd, bfqq, bic, current->pid,
4244 is_sync);
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004245 bfq_init_entity(&bfqq->entity, bfqg);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004246 bfq_log_bfqq(bfqd, bfqq, "allocated");
4247 } else {
4248 bfqq = &bfqd->oom_bfqq;
4249 bfq_log_bfqq(bfqd, bfqq, "using oom bfqq");
4250 goto out;
4251 }
4252
4253 /*
4254 * Pin the queue now that it's allocated, scheduler exit will
4255 * prune it.
4256 */
4257 if (async_bfqq) {
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004258 bfqq->ref++; /*
4259 * Extra group reference, w.r.t. sync
4260 * queue. This extra reference is removed
4261 * only if bfqq->bfqg disappears, to
4262 * guarantee that this queue is not freed
4263 * until its group goes away.
4264 */
4265 bfq_log_bfqq(bfqd, bfqq, "get_queue, bfqq not in async: %p, %d",
Paolo Valenteaee69d72017-04-19 08:29:02 -06004266 bfqq, bfqq->ref);
4267 *async_bfqq = bfqq;
4268 }
4269
4270out:
4271 bfqq->ref++; /* get a process reference to this queue */
4272 bfq_log_bfqq(bfqd, bfqq, "get_queue, at end: %p, %d", bfqq, bfqq->ref);
4273 rcu_read_unlock();
4274 return bfqq;
4275}
4276
4277static void bfq_update_io_thinktime(struct bfq_data *bfqd,
4278 struct bfq_queue *bfqq)
4279{
4280 struct bfq_ttime *ttime = &bfqq->ttime;
4281 u64 elapsed = ktime_get_ns() - bfqq->ttime.last_end_request;
4282
4283 elapsed = min_t(u64, elapsed, 2ULL * bfqd->bfq_slice_idle);
4284
4285 ttime->ttime_samples = (7*bfqq->ttime.ttime_samples + 256) / 8;
4286 ttime->ttime_total = div_u64(7*ttime->ttime_total + 256*elapsed, 8);
4287 ttime->ttime_mean = div64_ul(ttime->ttime_total + 128,
4288 ttime->ttime_samples);
4289}
4290
4291static void
4292bfq_update_io_seektime(struct bfq_data *bfqd, struct bfq_queue *bfqq,
4293 struct request *rq)
4294{
Paolo Valenteaee69d72017-04-19 08:29:02 -06004295 bfqq->seek_history <<= 1;
Paolo Valenteab0e43e2017-04-12 18:23:10 +02004296 bfqq->seek_history |=
4297 get_sdist(bfqq->last_request_pos, rq) > BFQQ_SEEK_THR &&
Paolo Valenteaee69d72017-04-19 08:29:02 -06004298 (!blk_queue_nonrot(bfqd->queue) ||
4299 blk_rq_sectors(rq) < BFQQ_SECT_THR_NONROT);
4300}
4301
Paolo Valented5be3fe2017-08-04 07:35:10 +02004302static void bfq_update_has_short_ttime(struct bfq_data *bfqd,
4303 struct bfq_queue *bfqq,
4304 struct bfq_io_cq *bic)
Paolo Valenteaee69d72017-04-19 08:29:02 -06004305{
Paolo Valented5be3fe2017-08-04 07:35:10 +02004306 bool has_short_ttime = true;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004307
Paolo Valented5be3fe2017-08-04 07:35:10 +02004308 /*
4309 * No need to update has_short_ttime if bfqq is async or in
4310 * idle io prio class, or if bfq_slice_idle is zero, because
4311 * no device idling is performed for bfqq in this case.
4312 */
4313 if (!bfq_bfqq_sync(bfqq) || bfq_class_idle(bfqq) ||
4314 bfqd->bfq_slice_idle == 0)
Paolo Valenteaee69d72017-04-19 08:29:02 -06004315 return;
4316
Arianna Avanzini36eca892017-04-12 18:23:16 +02004317 /* Idle window just restored, statistics are meaningless. */
4318 if (time_is_after_eq_jiffies(bfqq->split_time +
4319 bfqd->bfq_wr_min_idle_time))
4320 return;
4321
Paolo Valented5be3fe2017-08-04 07:35:10 +02004322 /* Think time is infinite if no process is linked to
4323 * bfqq. Otherwise check average think time to
4324 * decide whether to mark as has_short_ttime
4325 */
Paolo Valenteaee69d72017-04-19 08:29:02 -06004326 if (atomic_read(&bic->icq.ioc->active_ref) == 0 ||
Paolo Valented5be3fe2017-08-04 07:35:10 +02004327 (bfq_sample_valid(bfqq->ttime.ttime_samples) &&
4328 bfqq->ttime.ttime_mean > bfqd->bfq_slice_idle))
4329 has_short_ttime = false;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004330
Paolo Valented5be3fe2017-08-04 07:35:10 +02004331 bfq_log_bfqq(bfqd, bfqq, "update_has_short_ttime: has_short_ttime %d",
4332 has_short_ttime);
4333
4334 if (has_short_ttime)
4335 bfq_mark_bfqq_has_short_ttime(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004336 else
Paolo Valented5be3fe2017-08-04 07:35:10 +02004337 bfq_clear_bfqq_has_short_ttime(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004338}
4339
4340/*
4341 * Called when a new fs request (rq) is added to bfqq. Check if there's
4342 * something we should do about it.
4343 */
4344static void bfq_rq_enqueued(struct bfq_data *bfqd, struct bfq_queue *bfqq,
4345 struct request *rq)
4346{
4347 struct bfq_io_cq *bic = RQ_BIC(rq);
4348
4349 if (rq->cmd_flags & REQ_META)
4350 bfqq->meta_pending++;
4351
4352 bfq_update_io_thinktime(bfqd, bfqq);
Paolo Valented5be3fe2017-08-04 07:35:10 +02004353 bfq_update_has_short_ttime(bfqd, bfqq, bic);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004354 bfq_update_io_seektime(bfqd, bfqq, rq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004355
4356 bfq_log_bfqq(bfqd, bfqq,
Paolo Valented5be3fe2017-08-04 07:35:10 +02004357 "rq_enqueued: has_short_ttime=%d (seeky %d)",
4358 bfq_bfqq_has_short_ttime(bfqq), BFQQ_SEEKY(bfqq));
Paolo Valenteaee69d72017-04-19 08:29:02 -06004359
4360 bfqq->last_request_pos = blk_rq_pos(rq) + blk_rq_sectors(rq);
4361
4362 if (bfqq == bfqd->in_service_queue && bfq_bfqq_wait_request(bfqq)) {
4363 bool small_req = bfqq->queued[rq_is_sync(rq)] == 1 &&
4364 blk_rq_sectors(rq) < 32;
4365 bool budget_timeout = bfq_bfqq_budget_timeout(bfqq);
4366
4367 /*
4368 * There is just this request queued: if the request
4369 * is small and the queue is not to be expired, then
4370 * just exit.
4371 *
4372 * In this way, if the device is being idled to wait
4373 * for a new request from the in-service queue, we
4374 * avoid unplugging the device and committing the
4375 * device to serve just a small request. On the
4376 * contrary, we wait for the block layer to decide
4377 * when to unplug the device: hopefully, new requests
4378 * will be merged to this one quickly, then the device
4379 * will be unplugged and larger requests will be
4380 * dispatched.
4381 */
4382 if (small_req && !budget_timeout)
4383 return;
4384
4385 /*
4386 * A large enough request arrived, or the queue is to
4387 * be expired: in both cases disk idling is to be
4388 * stopped, so clear wait_request flag and reset
4389 * timer.
4390 */
4391 bfq_clear_bfqq_wait_request(bfqq);
4392 hrtimer_try_to_cancel(&bfqd->idle_slice_timer);
4393
4394 /*
4395 * The queue is not empty, because a new request just
4396 * arrived. Hence we can safely expire the queue, in
4397 * case of budget timeout, without risking that the
4398 * timestamps of the queue are not updated correctly.
4399 * See [1] for more details.
4400 */
4401 if (budget_timeout)
4402 bfq_bfqq_expire(bfqd, bfqq, false,
4403 BFQQE_BUDGET_TIMEOUT);
4404 }
4405}
4406
Paolo Valente24bfd192017-11-13 07:34:09 +01004407/* returns true if it causes the idle timer to be disabled */
4408static bool __bfq_insert_request(struct bfq_data *bfqd, struct request *rq)
Paolo Valenteaee69d72017-04-19 08:29:02 -06004409{
Arianna Avanzini36eca892017-04-12 18:23:16 +02004410 struct bfq_queue *bfqq = RQ_BFQQ(rq),
4411 *new_bfqq = bfq_setup_cooperator(bfqd, bfqq, rq, true);
Paolo Valente24bfd192017-11-13 07:34:09 +01004412 bool waiting, idle_timer_disabled = false;
Arianna Avanzini36eca892017-04-12 18:23:16 +02004413
4414 if (new_bfqq) {
4415 if (bic_to_bfqq(RQ_BIC(rq), 1) != bfqq)
4416 new_bfqq = bic_to_bfqq(RQ_BIC(rq), 1);
4417 /*
4418 * Release the request's reference to the old bfqq
4419 * and make sure one is taken to the shared queue.
4420 */
4421 new_bfqq->allocated++;
4422 bfqq->allocated--;
4423 new_bfqq->ref++;
4424 /*
4425 * If the bic associated with the process
4426 * issuing this request still points to bfqq
4427 * (and thus has not been already redirected
4428 * to new_bfqq or even some other bfq_queue),
4429 * then complete the merge and redirect it to
4430 * new_bfqq.
4431 */
4432 if (bic_to_bfqq(RQ_BIC(rq), 1) == bfqq)
4433 bfq_merge_bfqqs(bfqd, RQ_BIC(rq),
4434 bfqq, new_bfqq);
Paolo Valente894df932017-09-21 11:04:02 +02004435
4436 bfq_clear_bfqq_just_created(bfqq);
Arianna Avanzini36eca892017-04-12 18:23:16 +02004437 /*
4438 * rq is about to be enqueued into new_bfqq,
4439 * release rq reference on bfqq
4440 */
4441 bfq_put_queue(bfqq);
4442 rq->elv.priv[1] = new_bfqq;
4443 bfqq = new_bfqq;
4444 }
Paolo Valenteaee69d72017-04-19 08:29:02 -06004445
Paolo Valente24bfd192017-11-13 07:34:09 +01004446 waiting = bfqq && bfq_bfqq_wait_request(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004447 bfq_add_request(rq);
Paolo Valente24bfd192017-11-13 07:34:09 +01004448 idle_timer_disabled = waiting && !bfq_bfqq_wait_request(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004449
4450 rq->fifo_time = ktime_get_ns() + bfqd->bfq_fifo_expire[rq_is_sync(rq)];
4451 list_add_tail(&rq->queuelist, &bfqq->fifo);
4452
4453 bfq_rq_enqueued(bfqd, bfqq, rq);
Paolo Valente24bfd192017-11-13 07:34:09 +01004454
4455 return idle_timer_disabled;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004456}
4457
Paolo Valente9b25bd02017-12-04 11:42:05 +01004458#if defined(CONFIG_BFQ_GROUP_IOSCHED) && defined(CONFIG_DEBUG_BLK_CGROUP)
4459static void bfq_update_insert_stats(struct request_queue *q,
4460 struct bfq_queue *bfqq,
4461 bool idle_timer_disabled,
4462 unsigned int cmd_flags)
4463{
4464 if (!bfqq)
4465 return;
4466
4467 /*
4468 * bfqq still exists, because it can disappear only after
4469 * either it is merged with another queue, or the process it
4470 * is associated with exits. But both actions must be taken by
4471 * the same process currently executing this flow of
4472 * instructions.
4473 *
4474 * In addition, the following queue lock guarantees that
4475 * bfqq_group(bfqq) exists as well.
4476 */
4477 spin_lock_irq(q->queue_lock);
4478 bfqg_stats_update_io_add(bfqq_group(bfqq), bfqq, cmd_flags);
4479 if (idle_timer_disabled)
4480 bfqg_stats_update_idle_time(bfqq_group(bfqq));
4481 spin_unlock_irq(q->queue_lock);
4482}
4483#else
4484static inline void bfq_update_insert_stats(struct request_queue *q,
4485 struct bfq_queue *bfqq,
4486 bool idle_timer_disabled,
4487 unsigned int cmd_flags) {}
4488#endif
4489
Paolo Valenteaee69d72017-04-19 08:29:02 -06004490static void bfq_insert_request(struct blk_mq_hw_ctx *hctx, struct request *rq,
4491 bool at_head)
4492{
4493 struct request_queue *q = hctx->queue;
4494 struct bfq_data *bfqd = q->elevator->elevator_data;
Paolo Valente18e5a572018-05-04 19:17:01 +02004495 struct bfq_queue *bfqq;
Paolo Valente24bfd192017-11-13 07:34:09 +01004496 bool idle_timer_disabled = false;
4497 unsigned int cmd_flags;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004498
4499 spin_lock_irq(&bfqd->lock);
4500 if (blk_mq_sched_try_insert_merge(q, rq)) {
4501 spin_unlock_irq(&bfqd->lock);
4502 return;
4503 }
4504
4505 spin_unlock_irq(&bfqd->lock);
4506
4507 blk_mq_sched_request_inserted(rq);
4508
4509 spin_lock_irq(&bfqd->lock);
Paolo Valente18e5a572018-05-04 19:17:01 +02004510 bfqq = bfq_init_rq(rq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004511 if (at_head || blk_rq_is_passthrough(rq)) {
4512 if (at_head)
4513 list_add(&rq->queuelist, &bfqd->dispatch);
4514 else
4515 list_add_tail(&rq->queuelist, &bfqd->dispatch);
Paolo Valente18e5a572018-05-04 19:17:01 +02004516 } else { /* bfqq is assumed to be non null here */
Paolo Valente24bfd192017-11-13 07:34:09 +01004517 idle_timer_disabled = __bfq_insert_request(bfqd, rq);
Luca Miccio614822f2017-11-13 07:34:08 +01004518 /*
4519 * Update bfqq, because, if a queue merge has occurred
4520 * in __bfq_insert_request, then rq has been
4521 * redirected into a new queue.
4522 */
4523 bfqq = RQ_BFQQ(rq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004524
4525 if (rq_mergeable(rq)) {
4526 elv_rqhash_add(q, rq);
4527 if (!q->last_merge)
4528 q->last_merge = rq;
4529 }
4530 }
4531
Paolo Valente24bfd192017-11-13 07:34:09 +01004532 /*
4533 * Cache cmd_flags before releasing scheduler lock, because rq
4534 * may disappear afterwards (for example, because of a request
4535 * merge).
4536 */
4537 cmd_flags = rq->cmd_flags;
Paolo Valente9b25bd02017-12-04 11:42:05 +01004538
Paolo Valente6fa3e8d2017-04-12 18:23:21 +02004539 spin_unlock_irq(&bfqd->lock);
Paolo Valente24bfd192017-11-13 07:34:09 +01004540
Paolo Valente9b25bd02017-12-04 11:42:05 +01004541 bfq_update_insert_stats(q, bfqq, idle_timer_disabled,
4542 cmd_flags);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004543}
4544
4545static void bfq_insert_requests(struct blk_mq_hw_ctx *hctx,
4546 struct list_head *list, bool at_head)
4547{
4548 while (!list_empty(list)) {
4549 struct request *rq;
4550
4551 rq = list_first_entry(list, struct request, queuelist);
4552 list_del_init(&rq->queuelist);
4553 bfq_insert_request(hctx, rq, at_head);
4554 }
4555}
4556
4557static void bfq_update_hw_tag(struct bfq_data *bfqd)
4558{
4559 bfqd->max_rq_in_driver = max_t(int, bfqd->max_rq_in_driver,
4560 bfqd->rq_in_driver);
4561
4562 if (bfqd->hw_tag == 1)
4563 return;
4564
4565 /*
4566 * This sample is valid if the number of outstanding requests
4567 * is large enough to allow a queueing behavior. Note that the
4568 * sum is not exact, as it's not taking into account deactivated
4569 * requests.
4570 */
4571 if (bfqd->rq_in_driver + bfqd->queued < BFQ_HW_QUEUE_THRESHOLD)
4572 return;
4573
4574 if (bfqd->hw_tag_samples++ < BFQ_HW_QUEUE_SAMPLES)
4575 return;
4576
4577 bfqd->hw_tag = bfqd->max_rq_in_driver > BFQ_HW_QUEUE_THRESHOLD;
4578 bfqd->max_rq_in_driver = 0;
4579 bfqd->hw_tag_samples = 0;
4580}
4581
4582static void bfq_completed_request(struct bfq_queue *bfqq, struct bfq_data *bfqd)
4583{
Paolo Valenteab0e43e2017-04-12 18:23:10 +02004584 u64 now_ns;
4585 u32 delta_us;
4586
Paolo Valenteaee69d72017-04-19 08:29:02 -06004587 bfq_update_hw_tag(bfqd);
4588
4589 bfqd->rq_in_driver--;
4590 bfqq->dispatched--;
4591
Paolo Valente44e44a12017-04-12 18:23:12 +02004592 if (!bfqq->dispatched && !bfq_bfqq_busy(bfqq)) {
4593 /*
4594 * Set budget_timeout (which we overload to store the
4595 * time at which the queue remains with no backlog and
4596 * no outstanding request; used by the weight-raising
4597 * mechanism).
4598 */
4599 bfqq->budget_timeout = jiffies;
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +02004600
4601 bfq_weights_tree_remove(bfqd, &bfqq->entity,
4602 &bfqd->queue_weights_tree);
Paolo Valente44e44a12017-04-12 18:23:12 +02004603 }
4604
Paolo Valenteab0e43e2017-04-12 18:23:10 +02004605 now_ns = ktime_get_ns();
4606
4607 bfqq->ttime.last_end_request = now_ns;
4608
4609 /*
4610 * Using us instead of ns, to get a reasonable precision in
4611 * computing rate in next check.
4612 */
4613 delta_us = div_u64(now_ns - bfqd->last_completion, NSEC_PER_USEC);
4614
4615 /*
4616 * If the request took rather long to complete, and, according
4617 * to the maximum request size recorded, this completion latency
4618 * implies that the request was certainly served at a very low
4619 * rate (less than 1M sectors/sec), then the whole observation
4620 * interval that lasts up to this time instant cannot be a
4621 * valid time interval for computing a new peak rate. Invoke
4622 * bfq_update_rate_reset to have the following three steps
4623 * taken:
4624 * - close the observation interval at the last (previous)
4625 * request dispatch or completion
4626 * - compute rate, if possible, for that observation interval
4627 * - reset to zero samples, which will trigger a proper
4628 * re-initialization of the observation interval on next
4629 * dispatch
4630 */
4631 if (delta_us > BFQ_MIN_TT/NSEC_PER_USEC &&
4632 (bfqd->last_rq_max_size<<BFQ_RATE_SHIFT)/delta_us <
4633 1UL<<(BFQ_RATE_SHIFT - 10))
4634 bfq_update_rate_reset(bfqd, NULL);
4635 bfqd->last_completion = now_ns;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004636
4637 /*
Paolo Valente77b7dce2017-04-12 18:23:13 +02004638 * If we are waiting to discover whether the request pattern
4639 * of the task associated with the queue is actually
4640 * isochronous, and both requisites for this condition to hold
4641 * are now satisfied, then compute soft_rt_next_start (see the
4642 * comments on the function bfq_bfqq_softrt_next_start()). We
4643 * schedule this delayed check when bfqq expires, if it still
4644 * has in-flight requests.
4645 */
4646 if (bfq_bfqq_softrt_update(bfqq) && bfqq->dispatched == 0 &&
4647 RB_EMPTY_ROOT(&bfqq->sort_list))
4648 bfqq->soft_rt_next_start =
4649 bfq_bfqq_softrt_next_start(bfqd, bfqq);
4650
4651 /*
Paolo Valenteaee69d72017-04-19 08:29:02 -06004652 * If this is the in-service queue, check if it needs to be expired,
4653 * or if we want to idle in case it has no pending requests.
4654 */
4655 if (bfqd->in_service_queue == bfqq) {
Paolo Valente44e44a12017-04-12 18:23:12 +02004656 if (bfqq->dispatched == 0 && bfq_bfqq_must_idle(bfqq)) {
Paolo Valenteaee69d72017-04-19 08:29:02 -06004657 bfq_arm_slice_timer(bfqd);
4658 return;
4659 } else if (bfq_may_expire_for_budg_timeout(bfqq))
4660 bfq_bfqq_expire(bfqd, bfqq, false,
4661 BFQQE_BUDGET_TIMEOUT);
4662 else if (RB_EMPTY_ROOT(&bfqq->sort_list) &&
4663 (bfqq->dispatched == 0 ||
4664 !bfq_bfqq_may_idle(bfqq)))
4665 bfq_bfqq_expire(bfqd, bfqq, false,
4666 BFQQE_NO_MORE_REQUESTS);
4667 }
Hou Tao3f7cb4f2017-07-11 21:58:15 +08004668
4669 if (!bfqd->rq_in_driver)
4670 bfq_schedule_dispatch(bfqd);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004671}
4672
Paolo Valentea7877392018-02-07 22:19:20 +01004673static void bfq_finish_requeue_request_body(struct bfq_queue *bfqq)
Paolo Valenteaee69d72017-04-19 08:29:02 -06004674{
4675 bfqq->allocated--;
4676
4677 bfq_put_queue(bfqq);
4678}
4679
Paolo Valentea7877392018-02-07 22:19:20 +01004680/*
4681 * Handle either a requeue or a finish for rq. The things to do are
4682 * the same in both cases: all references to rq are to be dropped. In
4683 * particular, rq is considered completed from the point of view of
4684 * the scheduler.
4685 */
4686static void bfq_finish_requeue_request(struct request *rq)
Paolo Valenteaee69d72017-04-19 08:29:02 -06004687{
Paolo Valentea7877392018-02-07 22:19:20 +01004688 struct bfq_queue *bfqq = RQ_BFQQ(rq);
Christoph Hellwig5bbf4e52017-06-16 18:15:26 +02004689 struct bfq_data *bfqd;
4690
Paolo Valentea7877392018-02-07 22:19:20 +01004691 /*
4692 * Requeue and finish hooks are invoked in blk-mq without
4693 * checking whether the involved request is actually still
4694 * referenced in the scheduler. To handle this fact, the
4695 * following two checks make this function exit in case of
4696 * spurious invocations, for which there is nothing to do.
4697 *
4698 * First, check whether rq has nothing to do with an elevator.
4699 */
4700 if (unlikely(!(rq->rq_flags & RQF_ELVPRIV)))
Christoph Hellwig5bbf4e52017-06-16 18:15:26 +02004701 return;
4702
Paolo Valentea7877392018-02-07 22:19:20 +01004703 /*
4704 * rq either is not associated with any icq, or is an already
4705 * requeued request that has not (yet) been re-inserted into
4706 * a bfq_queue.
4707 */
4708 if (!rq->elv.icq || !bfqq)
4709 return;
4710
Christoph Hellwig5bbf4e52017-06-16 18:15:26 +02004711 bfqd = bfqq->bfqd;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004712
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004713 if (rq->rq_flags & RQF_STARTED)
4714 bfqg_stats_update_completion(bfqq_group(bfqq),
Omar Sandoval522a7772018-05-09 02:08:53 -07004715 rq->start_time_ns,
4716 rq->io_start_time_ns,
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004717 rq->cmd_flags);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004718
4719 if (likely(rq->rq_flags & RQF_STARTED)) {
4720 unsigned long flags;
4721
4722 spin_lock_irqsave(&bfqd->lock, flags);
4723
4724 bfq_completed_request(bfqq, bfqd);
Paolo Valentea7877392018-02-07 22:19:20 +01004725 bfq_finish_requeue_request_body(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004726
Paolo Valente6fa3e8d2017-04-12 18:23:21 +02004727 spin_unlock_irqrestore(&bfqd->lock, flags);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004728 } else {
4729 /*
4730 * Request rq may be still/already in the scheduler,
Paolo Valentea7877392018-02-07 22:19:20 +01004731 * in which case we need to remove it (this should
4732 * never happen in case of requeue). And we cannot
Paolo Valenteaee69d72017-04-19 08:29:02 -06004733 * defer such a check and removal, to avoid
4734 * inconsistencies in the time interval from the end
4735 * of this function to the start of the deferred work.
4736 * This situation seems to occur only in process
4737 * context, as a consequence of a merge. In the
4738 * current version of the code, this implies that the
4739 * lock is held.
4740 */
4741
Luca Miccio614822f2017-11-13 07:34:08 +01004742 if (!RB_EMPTY_NODE(&rq->rb_node)) {
Christoph Hellwig7b9e9362017-06-16 18:15:21 +02004743 bfq_remove_request(rq->q, rq);
Luca Miccio614822f2017-11-13 07:34:08 +01004744 bfqg_stats_update_io_remove(bfqq_group(bfqq),
4745 rq->cmd_flags);
4746 }
Paolo Valentea7877392018-02-07 22:19:20 +01004747 bfq_finish_requeue_request_body(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004748 }
4749
Paolo Valentea7877392018-02-07 22:19:20 +01004750 /*
4751 * Reset private fields. In case of a requeue, this allows
4752 * this function to correctly do nothing if it is spuriously
4753 * invoked again on this same request (see the check at the
4754 * beginning of the function). Probably, a better general
4755 * design would be to prevent blk-mq from invoking the requeue
4756 * or finish hooks of an elevator, for a request that is not
4757 * referred by that elevator.
4758 *
4759 * Resetting the following fields would break the
4760 * request-insertion logic if rq is re-inserted into a bfq
4761 * internal queue, without a re-preparation. Here we assume
4762 * that re-insertions of requeued requests, without
4763 * re-preparation, can happen only for pass_through or at_head
4764 * requests (which are not re-inserted into bfq internal
4765 * queues).
4766 */
Paolo Valenteaee69d72017-04-19 08:29:02 -06004767 rq->elv.priv[0] = NULL;
4768 rq->elv.priv[1] = NULL;
4769}
4770
4771/*
Arianna Avanzini36eca892017-04-12 18:23:16 +02004772 * Returns NULL if a new bfqq should be allocated, or the old bfqq if this
4773 * was the last process referring to that bfqq.
4774 */
4775static struct bfq_queue *
4776bfq_split_bfqq(struct bfq_io_cq *bic, struct bfq_queue *bfqq)
4777{
4778 bfq_log_bfqq(bfqq->bfqd, bfqq, "splitting queue");
4779
4780 if (bfqq_process_refs(bfqq) == 1) {
4781 bfqq->pid = current->pid;
4782 bfq_clear_bfqq_coop(bfqq);
4783 bfq_clear_bfqq_split_coop(bfqq);
4784 return bfqq;
4785 }
4786
4787 bic_set_bfqq(bic, NULL, 1);
4788
4789 bfq_put_cooperator(bfqq);
4790
4791 bfq_put_queue(bfqq);
4792 return NULL;
4793}
4794
4795static struct bfq_queue *bfq_get_bfqq_handle_split(struct bfq_data *bfqd,
4796 struct bfq_io_cq *bic,
4797 struct bio *bio,
4798 bool split, bool is_sync,
4799 bool *new_queue)
4800{
4801 struct bfq_queue *bfqq = bic_to_bfqq(bic, is_sync);
4802
4803 if (likely(bfqq && bfqq != &bfqd->oom_bfqq))
4804 return bfqq;
4805
4806 if (new_queue)
4807 *new_queue = true;
4808
4809 if (bfqq)
4810 bfq_put_queue(bfqq);
4811 bfqq = bfq_get_queue(bfqd, bio, is_sync, bic);
4812
4813 bic_set_bfqq(bic, bfqq, is_sync);
Arianna Avanzinie1b23242017-04-12 18:23:20 +02004814 if (split && is_sync) {
4815 if ((bic->was_in_burst_list && bfqd->large_burst) ||
4816 bic->saved_in_large_burst)
4817 bfq_mark_bfqq_in_large_burst(bfqq);
4818 else {
4819 bfq_clear_bfqq_in_large_burst(bfqq);
4820 if (bic->was_in_burst_list)
Paolo Valente99fead82017-10-09 13:11:23 +02004821 /*
4822 * If bfqq was in the current
4823 * burst list before being
4824 * merged, then we have to add
4825 * it back. And we do not need
4826 * to increase burst_size, as
4827 * we did not decrement
4828 * burst_size when we removed
4829 * bfqq from the burst list as
4830 * a consequence of a merge
4831 * (see comments in
4832 * bfq_put_queue). In this
4833 * respect, it would be rather
4834 * costly to know whether the
4835 * current burst list is still
4836 * the same burst list from
4837 * which bfqq was removed on
4838 * the merge. To avoid this
4839 * cost, if bfqq was in a
4840 * burst list, then we add
4841 * bfqq to the current burst
4842 * list without any further
4843 * check. This can cause
4844 * inappropriate insertions,
4845 * but rarely enough to not
4846 * harm the detection of large
4847 * bursts significantly.
4848 */
Arianna Avanzinie1b23242017-04-12 18:23:20 +02004849 hlist_add_head(&bfqq->burst_list_node,
4850 &bfqd->burst_list);
4851 }
Arianna Avanzini36eca892017-04-12 18:23:16 +02004852 bfqq->split_time = jiffies;
Arianna Avanzinie1b23242017-04-12 18:23:20 +02004853 }
Arianna Avanzini36eca892017-04-12 18:23:16 +02004854
4855 return bfqq;
4856}
4857
4858/*
Paolo Valente18e5a572018-05-04 19:17:01 +02004859 * Only reset private fields. The actual request preparation will be
4860 * performed by bfq_init_rq, when rq is either inserted or merged. See
4861 * comments on bfq_init_rq for the reason behind this delayed
4862 * preparation.
Paolo Valenteaee69d72017-04-19 08:29:02 -06004863 */
Christoph Hellwig5bbf4e52017-06-16 18:15:26 +02004864static void bfq_prepare_request(struct request *rq, struct bio *bio)
Paolo Valenteaee69d72017-04-19 08:29:02 -06004865{
Paolo Valente18e5a572018-05-04 19:17:01 +02004866 /*
4867 * Regardless of whether we have an icq attached, we have to
4868 * clear the scheduler pointers, as they might point to
4869 * previously allocated bic/bfqq structs.
4870 */
4871 rq->elv.priv[0] = rq->elv.priv[1] = NULL;
4872}
4873
4874/*
4875 * If needed, init rq, allocate bfq data structures associated with
4876 * rq, and increment reference counters in the destination bfq_queue
4877 * for rq. Return the destination bfq_queue for rq, or NULL is rq is
4878 * not associated with any bfq_queue.
4879 *
4880 * This function is invoked by the functions that perform rq insertion
4881 * or merging. One may have expected the above preparation operations
4882 * to be performed in bfq_prepare_request, and not delayed to when rq
4883 * is inserted or merged. The rationale behind this delayed
4884 * preparation is that, after the prepare_request hook is invoked for
4885 * rq, rq may still be transformed into a request with no icq, i.e., a
4886 * request not associated with any queue. No bfq hook is invoked to
4887 * signal this tranformation. As a consequence, should these
4888 * preparation operations be performed when the prepare_request hook
4889 * is invoked, and should rq be transformed one moment later, bfq
4890 * would end up in an inconsistent state, because it would have
4891 * incremented some queue counters for an rq destined to
4892 * transformation, without any chance to correctly lower these
4893 * counters back. In contrast, no transformation can still happen for
4894 * rq after rq has been inserted or merged. So, it is safe to execute
4895 * these preparation operations when rq is finally inserted or merged.
4896 */
4897static struct bfq_queue *bfq_init_rq(struct request *rq)
4898{
Christoph Hellwig5bbf4e52017-06-16 18:15:26 +02004899 struct request_queue *q = rq->q;
Paolo Valente18e5a572018-05-04 19:17:01 +02004900 struct bio *bio = rq->bio;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004901 struct bfq_data *bfqd = q->elevator->elevator_data;
Christoph Hellwig9f210732017-06-16 18:15:24 +02004902 struct bfq_io_cq *bic;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004903 const int is_sync = rq_is_sync(rq);
4904 struct bfq_queue *bfqq;
Arianna Avanzini36eca892017-04-12 18:23:16 +02004905 bool new_queue = false;
Paolo Valente13c931b2017-06-27 12:30:47 -06004906 bool bfqq_already_existing = false, split = false;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004907
Paolo Valente18e5a572018-05-04 19:17:01 +02004908 if (unlikely(!rq->elv.icq))
4909 return NULL;
4910
Jens Axboe72961c42018-04-17 17:08:52 -06004911 /*
Paolo Valente18e5a572018-05-04 19:17:01 +02004912 * Assuming that elv.priv[1] is set only if everything is set
4913 * for this rq. This holds true, because this function is
4914 * invoked only for insertion or merging, and, after such
4915 * events, a request cannot be manipulated any longer before
4916 * being removed from bfq.
Jens Axboe72961c42018-04-17 17:08:52 -06004917 */
Paolo Valente18e5a572018-05-04 19:17:01 +02004918 if (rq->elv.priv[1])
4919 return rq->elv.priv[1];
Jens Axboe72961c42018-04-17 17:08:52 -06004920
Christoph Hellwig9f210732017-06-16 18:15:24 +02004921 bic = icq_to_bic(rq->elv.icq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004922
Colin Ian King8c9ff1a2017-04-20 15:07:18 +01004923 bfq_check_ioprio_change(bic, bio);
4924
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004925 bfq_bic_update_cgroup(bic, bio);
4926
Arianna Avanzini36eca892017-04-12 18:23:16 +02004927 bfqq = bfq_get_bfqq_handle_split(bfqd, bic, bio, false, is_sync,
4928 &new_queue);
4929
4930 if (likely(!new_queue)) {
4931 /* If the queue was seeky for too long, break it apart. */
4932 if (bfq_bfqq_coop(bfqq) && bfq_bfqq_split_coop(bfqq)) {
4933 bfq_log_bfqq(bfqd, bfqq, "breaking apart bfqq");
Arianna Avanzinie1b23242017-04-12 18:23:20 +02004934
4935 /* Update bic before losing reference to bfqq */
4936 if (bfq_bfqq_in_large_burst(bfqq))
4937 bic->saved_in_large_burst = true;
4938
Arianna Avanzini36eca892017-04-12 18:23:16 +02004939 bfqq = bfq_split_bfqq(bic, bfqq);
Paolo Valente6fa3e8d2017-04-12 18:23:21 +02004940 split = true;
Arianna Avanzini36eca892017-04-12 18:23:16 +02004941
4942 if (!bfqq)
4943 bfqq = bfq_get_bfqq_handle_split(bfqd, bic, bio,
4944 true, is_sync,
4945 NULL);
Paolo Valente13c931b2017-06-27 12:30:47 -06004946 else
4947 bfqq_already_existing = true;
Arianna Avanzini36eca892017-04-12 18:23:16 +02004948 }
Paolo Valenteaee69d72017-04-19 08:29:02 -06004949 }
4950
4951 bfqq->allocated++;
4952 bfqq->ref++;
4953 bfq_log_bfqq(bfqd, bfqq, "get_request %p: bfqq %p, %d",
4954 rq, bfqq, bfqq->ref);
4955
4956 rq->elv.priv[0] = bic;
4957 rq->elv.priv[1] = bfqq;
4958
Arianna Avanzini36eca892017-04-12 18:23:16 +02004959 /*
4960 * If a bfq_queue has only one process reference, it is owned
4961 * by only this bic: we can then set bfqq->bic = bic. in
4962 * addition, if the queue has also just been split, we have to
4963 * resume its state.
4964 */
4965 if (likely(bfqq != &bfqd->oom_bfqq) && bfqq_process_refs(bfqq) == 1) {
4966 bfqq->bic = bic;
Paolo Valente6fa3e8d2017-04-12 18:23:21 +02004967 if (split) {
Arianna Avanzini36eca892017-04-12 18:23:16 +02004968 /*
4969 * The queue has just been split from a shared
4970 * queue: restore the idle window and the
4971 * possible weight raising period.
4972 */
Paolo Valente13c931b2017-06-27 12:30:47 -06004973 bfq_bfqq_resume_state(bfqq, bfqd, bic,
4974 bfqq_already_existing);
Arianna Avanzini36eca892017-04-12 18:23:16 +02004975 }
4976 }
4977
Arianna Avanzinie1b23242017-04-12 18:23:20 +02004978 if (unlikely(bfq_bfqq_just_created(bfqq)))
4979 bfq_handle_burst(bfqd, bfqq);
4980
Paolo Valente18e5a572018-05-04 19:17:01 +02004981 return bfqq;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004982}
4983
4984static void bfq_idle_slice_timer_body(struct bfq_queue *bfqq)
4985{
4986 struct bfq_data *bfqd = bfqq->bfqd;
4987 enum bfqq_expiration reason;
4988 unsigned long flags;
4989
4990 spin_lock_irqsave(&bfqd->lock, flags);
4991 bfq_clear_bfqq_wait_request(bfqq);
4992
4993 if (bfqq != bfqd->in_service_queue) {
4994 spin_unlock_irqrestore(&bfqd->lock, flags);
4995 return;
4996 }
4997
4998 if (bfq_bfqq_budget_timeout(bfqq))
4999 /*
5000 * Also here the queue can be safely expired
5001 * for budget timeout without wasting
5002 * guarantees
5003 */
5004 reason = BFQQE_BUDGET_TIMEOUT;
5005 else if (bfqq->queued[0] == 0 && bfqq->queued[1] == 0)
5006 /*
5007 * The queue may not be empty upon timer expiration,
5008 * because we may not disable the timer when the
5009 * first request of the in-service queue arrives
5010 * during disk idling.
5011 */
5012 reason = BFQQE_TOO_IDLE;
5013 else
5014 goto schedule_dispatch;
5015
5016 bfq_bfqq_expire(bfqd, bfqq, true, reason);
5017
5018schedule_dispatch:
Paolo Valente6fa3e8d2017-04-12 18:23:21 +02005019 spin_unlock_irqrestore(&bfqd->lock, flags);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005020 bfq_schedule_dispatch(bfqd);
5021}
5022
5023/*
5024 * Handler of the expiration of the timer running if the in-service queue
5025 * is idling inside its time slice.
5026 */
5027static enum hrtimer_restart bfq_idle_slice_timer(struct hrtimer *timer)
5028{
5029 struct bfq_data *bfqd = container_of(timer, struct bfq_data,
5030 idle_slice_timer);
5031 struct bfq_queue *bfqq = bfqd->in_service_queue;
5032
5033 /*
5034 * Theoretical race here: the in-service queue can be NULL or
5035 * different from the queue that was idling if a new request
5036 * arrives for the current queue and there is a full dispatch
5037 * cycle that changes the in-service queue. This can hardly
5038 * happen, but in the worst case we just expire a queue too
5039 * early.
5040 */
5041 if (bfqq)
5042 bfq_idle_slice_timer_body(bfqq);
5043
5044 return HRTIMER_NORESTART;
5045}
5046
5047static void __bfq_put_async_bfqq(struct bfq_data *bfqd,
5048 struct bfq_queue **bfqq_ptr)
5049{
5050 struct bfq_queue *bfqq = *bfqq_ptr;
5051
5052 bfq_log(bfqd, "put_async_bfqq: %p", bfqq);
5053 if (bfqq) {
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005054 bfq_bfqq_move(bfqd, bfqq, bfqd->root_group);
5055
Paolo Valenteaee69d72017-04-19 08:29:02 -06005056 bfq_log_bfqq(bfqd, bfqq, "put_async_bfqq: putting %p, %d",
5057 bfqq, bfqq->ref);
5058 bfq_put_queue(bfqq);
5059 *bfqq_ptr = NULL;
5060 }
5061}
5062
5063/*
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005064 * Release all the bfqg references to its async queues. If we are
5065 * deallocating the group these queues may still contain requests, so
5066 * we reparent them to the root cgroup (i.e., the only one that will
5067 * exist for sure until all the requests on a device are gone).
Paolo Valenteaee69d72017-04-19 08:29:02 -06005068 */
Paolo Valenteea25da42017-04-19 08:48:24 -06005069void bfq_put_async_queues(struct bfq_data *bfqd, struct bfq_group *bfqg)
Paolo Valenteaee69d72017-04-19 08:29:02 -06005070{
5071 int i, j;
5072
5073 for (i = 0; i < 2; i++)
5074 for (j = 0; j < IOPRIO_BE_NR; j++)
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005075 __bfq_put_async_bfqq(bfqd, &bfqg->async_bfqq[i][j]);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005076
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005077 __bfq_put_async_bfqq(bfqd, &bfqg->async_idle_bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005078}
5079
Jens Axboef0635b82018-05-09 13:27:21 -06005080/*
5081 * See the comments on bfq_limit_depth for the purpose of
Jens Axboe483b7bf2018-05-09 15:26:55 -06005082 * the depths set in the function. Return minimum shallow depth we'll use.
Jens Axboef0635b82018-05-09 13:27:21 -06005083 */
Jens Axboe483b7bf2018-05-09 15:26:55 -06005084static unsigned int bfq_update_depths(struct bfq_data *bfqd,
5085 struct sbitmap_queue *bt)
Jens Axboef0635b82018-05-09 13:27:21 -06005086{
Jens Axboe483b7bf2018-05-09 15:26:55 -06005087 unsigned int i, j, min_shallow = UINT_MAX;
5088
Jens Axboef0635b82018-05-09 13:27:21 -06005089 /*
5090 * In-word depths if no bfq_queue is being weight-raised:
5091 * leaving 25% of tags only for sync reads.
5092 *
5093 * In next formulas, right-shift the value
Jens Axboebd7d4ef2018-05-09 15:25:22 -06005094 * (1U<<bt->sb.shift), instead of computing directly
5095 * (1U<<(bt->sb.shift - something)), to be robust against
5096 * any possible value of bt->sb.shift, without having to
Jens Axboef0635b82018-05-09 13:27:21 -06005097 * limit 'something'.
5098 */
5099 /* no more than 50% of tags for async I/O */
Jens Axboebd7d4ef2018-05-09 15:25:22 -06005100 bfqd->word_depths[0][0] = max((1U << bt->sb.shift) >> 1, 1U);
Jens Axboef0635b82018-05-09 13:27:21 -06005101 /*
5102 * no more than 75% of tags for sync writes (25% extra tags
5103 * w.r.t. async I/O, to prevent async I/O from starving sync
5104 * writes)
5105 */
Jens Axboebd7d4ef2018-05-09 15:25:22 -06005106 bfqd->word_depths[0][1] = max(((1U << bt->sb.shift) * 3) >> 2, 1U);
Jens Axboef0635b82018-05-09 13:27:21 -06005107
5108 /*
5109 * In-word depths in case some bfq_queue is being weight-
5110 * raised: leaving ~63% of tags for sync reads. This is the
5111 * highest percentage for which, in our tests, application
5112 * start-up times didn't suffer from any regression due to tag
5113 * shortage.
5114 */
5115 /* no more than ~18% of tags for async I/O */
Jens Axboebd7d4ef2018-05-09 15:25:22 -06005116 bfqd->word_depths[1][0] = max(((1U << bt->sb.shift) * 3) >> 4, 1U);
Jens Axboef0635b82018-05-09 13:27:21 -06005117 /* no more than ~37% of tags for sync writes (~20% extra tags) */
Jens Axboebd7d4ef2018-05-09 15:25:22 -06005118 bfqd->word_depths[1][1] = max(((1U << bt->sb.shift) * 6) >> 4, 1U);
Jens Axboe483b7bf2018-05-09 15:26:55 -06005119
5120 for (i = 0; i < 2; i++)
5121 for (j = 0; j < 2; j++)
5122 min_shallow = min(min_shallow, bfqd->word_depths[i][j]);
5123
5124 return min_shallow;
Jens Axboef0635b82018-05-09 13:27:21 -06005125}
5126
5127static int bfq_init_hctx(struct blk_mq_hw_ctx *hctx, unsigned int index)
5128{
5129 struct bfq_data *bfqd = hctx->queue->elevator->elevator_data;
5130 struct blk_mq_tags *tags = hctx->sched_tags;
Jens Axboe483b7bf2018-05-09 15:26:55 -06005131 unsigned int min_shallow;
Jens Axboef0635b82018-05-09 13:27:21 -06005132
Jens Axboe483b7bf2018-05-09 15:26:55 -06005133 min_shallow = bfq_update_depths(bfqd, &tags->bitmap_tags);
5134 sbitmap_queue_min_shallow_depth(&tags->bitmap_tags, min_shallow);
Jens Axboef0635b82018-05-09 13:27:21 -06005135 return 0;
5136}
5137
Paolo Valenteaee69d72017-04-19 08:29:02 -06005138static void bfq_exit_queue(struct elevator_queue *e)
5139{
5140 struct bfq_data *bfqd = e->elevator_data;
5141 struct bfq_queue *bfqq, *n;
5142
5143 hrtimer_cancel(&bfqd->idle_slice_timer);
5144
5145 spin_lock_irq(&bfqd->lock);
5146 list_for_each_entry_safe(bfqq, n, &bfqd->idle_list, bfqq_list)
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005147 bfq_deactivate_bfqq(bfqd, bfqq, false, false);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005148 spin_unlock_irq(&bfqd->lock);
5149
5150 hrtimer_cancel(&bfqd->idle_slice_timer);
5151
Jens Axboe8abef102018-01-09 12:20:51 -07005152#ifdef CONFIG_BFQ_GROUP_IOSCHED
Paolo Valente0d52af52018-01-09 10:27:59 +01005153 /* release oom-queue reference to root group */
5154 bfqg_and_blkg_put(bfqd->root_group);
5155
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005156 blkcg_deactivate_policy(bfqd->queue, &blkcg_policy_bfq);
5157#else
5158 spin_lock_irq(&bfqd->lock);
5159 bfq_put_async_queues(bfqd, bfqd->root_group);
5160 kfree(bfqd->root_group);
5161 spin_unlock_irq(&bfqd->lock);
5162#endif
5163
Paolo Valenteaee69d72017-04-19 08:29:02 -06005164 kfree(bfqd);
5165}
5166
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005167static void bfq_init_root_group(struct bfq_group *root_group,
5168 struct bfq_data *bfqd)
5169{
5170 int i;
5171
5172#ifdef CONFIG_BFQ_GROUP_IOSCHED
5173 root_group->entity.parent = NULL;
5174 root_group->my_entity = NULL;
5175 root_group->bfqd = bfqd;
5176#endif
Arianna Avanzini36eca892017-04-12 18:23:16 +02005177 root_group->rq_pos_tree = RB_ROOT;
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005178 for (i = 0; i < BFQ_IOPRIO_CLASSES; i++)
5179 root_group->sched_data.service_tree[i] = BFQ_SERVICE_TREE_INIT;
5180 root_group->sched_data.bfq_class_idle_last_service = jiffies;
5181}
5182
Paolo Valenteaee69d72017-04-19 08:29:02 -06005183static int bfq_init_queue(struct request_queue *q, struct elevator_type *e)
5184{
5185 struct bfq_data *bfqd;
5186 struct elevator_queue *eq;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005187
5188 eq = elevator_alloc(q, e);
5189 if (!eq)
5190 return -ENOMEM;
5191
5192 bfqd = kzalloc_node(sizeof(*bfqd), GFP_KERNEL, q->node);
5193 if (!bfqd) {
5194 kobject_put(&eq->kobj);
5195 return -ENOMEM;
5196 }
5197 eq->elevator_data = bfqd;
5198
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005199 spin_lock_irq(q->queue_lock);
5200 q->elevator = eq;
5201 spin_unlock_irq(q->queue_lock);
5202
Paolo Valenteaee69d72017-04-19 08:29:02 -06005203 /*
5204 * Our fallback bfqq if bfq_find_alloc_queue() runs into OOM issues.
5205 * Grab a permanent reference to it, so that the normal code flow
5206 * will not attempt to free it.
5207 */
5208 bfq_init_bfqq(bfqd, &bfqd->oom_bfqq, NULL, 1, 0);
5209 bfqd->oom_bfqq.ref++;
5210 bfqd->oom_bfqq.new_ioprio = BFQ_DEFAULT_QUEUE_IOPRIO;
5211 bfqd->oom_bfqq.new_ioprio_class = IOPRIO_CLASS_BE;
5212 bfqd->oom_bfqq.entity.new_weight =
5213 bfq_ioprio_to_weight(bfqd->oom_bfqq.new_ioprio);
Arianna Avanzinie1b23242017-04-12 18:23:20 +02005214
5215 /* oom_bfqq does not participate to bursts */
5216 bfq_clear_bfqq_just_created(&bfqd->oom_bfqq);
5217
Paolo Valenteaee69d72017-04-19 08:29:02 -06005218 /*
5219 * Trigger weight initialization, according to ioprio, at the
5220 * oom_bfqq's first activation. The oom_bfqq's ioprio and ioprio
5221 * class won't be changed any more.
5222 */
5223 bfqd->oom_bfqq.entity.prio_changed = 1;
5224
5225 bfqd->queue = q;
5226
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005227 INIT_LIST_HEAD(&bfqd->dispatch);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005228
5229 hrtimer_init(&bfqd->idle_slice_timer, CLOCK_MONOTONIC,
5230 HRTIMER_MODE_REL);
5231 bfqd->idle_slice_timer.function = bfq_idle_slice_timer;
5232
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +02005233 bfqd->queue_weights_tree = RB_ROOT;
5234 bfqd->group_weights_tree = RB_ROOT;
5235
Paolo Valenteaee69d72017-04-19 08:29:02 -06005236 INIT_LIST_HEAD(&bfqd->active_list);
5237 INIT_LIST_HEAD(&bfqd->idle_list);
Arianna Avanzinie1b23242017-04-12 18:23:20 +02005238 INIT_HLIST_HEAD(&bfqd->burst_list);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005239
5240 bfqd->hw_tag = -1;
5241
5242 bfqd->bfq_max_budget = bfq_default_max_budget;
5243
5244 bfqd->bfq_fifo_expire[0] = bfq_fifo_expire[0];
5245 bfqd->bfq_fifo_expire[1] = bfq_fifo_expire[1];
5246 bfqd->bfq_back_max = bfq_back_max;
5247 bfqd->bfq_back_penalty = bfq_back_penalty;
5248 bfqd->bfq_slice_idle = bfq_slice_idle;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005249 bfqd->bfq_timeout = bfq_timeout;
5250
5251 bfqd->bfq_requests_within_timer = 120;
5252
Arianna Avanzinie1b23242017-04-12 18:23:20 +02005253 bfqd->bfq_large_burst_thresh = 8;
5254 bfqd->bfq_burst_interval = msecs_to_jiffies(180);
5255
Paolo Valente44e44a12017-04-12 18:23:12 +02005256 bfqd->low_latency = true;
5257
5258 /*
5259 * Trade-off between responsiveness and fairness.
5260 */
5261 bfqd->bfq_wr_coeff = 30;
Paolo Valente77b7dce2017-04-12 18:23:13 +02005262 bfqd->bfq_wr_rt_max_time = msecs_to_jiffies(300);
Paolo Valente44e44a12017-04-12 18:23:12 +02005263 bfqd->bfq_wr_max_time = 0;
5264 bfqd->bfq_wr_min_idle_time = msecs_to_jiffies(2000);
5265 bfqd->bfq_wr_min_inter_arr_async = msecs_to_jiffies(500);
Paolo Valente77b7dce2017-04-12 18:23:13 +02005266 bfqd->bfq_wr_max_softrt_rate = 7000; /*
5267 * Approximate rate required
5268 * to playback or record a
5269 * high-definition compressed
5270 * video.
5271 */
Paolo Valentecfd69712017-04-12 18:23:15 +02005272 bfqd->wr_busy_queues = 0;
Paolo Valente44e44a12017-04-12 18:23:12 +02005273
5274 /*
5275 * Begin by assuming, optimistically, that the device is a
5276 * high-speed one, and that its peak rate is equal to 2/3 of
5277 * the highest reference rate.
5278 */
5279 bfqd->RT_prod = R_fast[blk_queue_nonrot(bfqd->queue)] *
5280 T_fast[blk_queue_nonrot(bfqd->queue)];
5281 bfqd->peak_rate = R_fast[blk_queue_nonrot(bfqd->queue)] * 2 / 3;
5282 bfqd->device_speed = BFQ_BFQD_FAST;
5283
Paolo Valenteaee69d72017-04-19 08:29:02 -06005284 spin_lock_init(&bfqd->lock);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005285
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005286 /*
5287 * The invocation of the next bfq_create_group_hierarchy
5288 * function is the head of a chain of function calls
5289 * (bfq_create_group_hierarchy->blkcg_activate_policy->
5290 * blk_mq_freeze_queue) that may lead to the invocation of the
5291 * has_work hook function. For this reason,
5292 * bfq_create_group_hierarchy is invoked only after all
5293 * scheduler data has been initialized, apart from the fields
5294 * that can be initialized only after invoking
5295 * bfq_create_group_hierarchy. This, in particular, enables
5296 * has_work to correctly return false. Of course, to avoid
5297 * other inconsistencies, the blk-mq stack must then refrain
5298 * from invoking further scheduler hooks before this init
5299 * function is finished.
5300 */
5301 bfqd->root_group = bfq_create_group_hierarchy(bfqd, q->node);
5302 if (!bfqd->root_group)
5303 goto out_free;
5304 bfq_init_root_group(bfqd->root_group, bfqd);
5305 bfq_init_entity(&bfqd->oom_bfqq.entity, bfqd->root_group);
5306
Luca Micciob5dc5d42017-10-09 16:27:21 +02005307 wbt_disable_default(q);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005308 return 0;
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005309
5310out_free:
5311 kfree(bfqd);
5312 kobject_put(&eq->kobj);
5313 return -ENOMEM;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005314}
5315
5316static void bfq_slab_kill(void)
5317{
5318 kmem_cache_destroy(bfq_pool);
5319}
5320
5321static int __init bfq_slab_setup(void)
5322{
5323 bfq_pool = KMEM_CACHE(bfq_queue, 0);
5324 if (!bfq_pool)
5325 return -ENOMEM;
5326 return 0;
5327}
5328
5329static ssize_t bfq_var_show(unsigned int var, char *page)
5330{
5331 return sprintf(page, "%u\n", var);
5332}
5333
Bart Van Assche2f791362017-08-30 11:42:09 -07005334static int bfq_var_store(unsigned long *var, const char *page)
Paolo Valenteaee69d72017-04-19 08:29:02 -06005335{
5336 unsigned long new_val;
5337 int ret = kstrtoul(page, 10, &new_val);
5338
Bart Van Assche2f791362017-08-30 11:42:09 -07005339 if (ret)
5340 return ret;
5341 *var = new_val;
5342 return 0;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005343}
5344
5345#define SHOW_FUNCTION(__FUNC, __VAR, __CONV) \
5346static ssize_t __FUNC(struct elevator_queue *e, char *page) \
5347{ \
5348 struct bfq_data *bfqd = e->elevator_data; \
5349 u64 __data = __VAR; \
5350 if (__CONV == 1) \
5351 __data = jiffies_to_msecs(__data); \
5352 else if (__CONV == 2) \
5353 __data = div_u64(__data, NSEC_PER_MSEC); \
5354 return bfq_var_show(__data, (page)); \
5355}
5356SHOW_FUNCTION(bfq_fifo_expire_sync_show, bfqd->bfq_fifo_expire[1], 2);
5357SHOW_FUNCTION(bfq_fifo_expire_async_show, bfqd->bfq_fifo_expire[0], 2);
5358SHOW_FUNCTION(bfq_back_seek_max_show, bfqd->bfq_back_max, 0);
5359SHOW_FUNCTION(bfq_back_seek_penalty_show, bfqd->bfq_back_penalty, 0);
5360SHOW_FUNCTION(bfq_slice_idle_show, bfqd->bfq_slice_idle, 2);
5361SHOW_FUNCTION(bfq_max_budget_show, bfqd->bfq_user_max_budget, 0);
5362SHOW_FUNCTION(bfq_timeout_sync_show, bfqd->bfq_timeout, 1);
5363SHOW_FUNCTION(bfq_strict_guarantees_show, bfqd->strict_guarantees, 0);
Paolo Valente44e44a12017-04-12 18:23:12 +02005364SHOW_FUNCTION(bfq_low_latency_show, bfqd->low_latency, 0);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005365#undef SHOW_FUNCTION
5366
5367#define USEC_SHOW_FUNCTION(__FUNC, __VAR) \
5368static ssize_t __FUNC(struct elevator_queue *e, char *page) \
5369{ \
5370 struct bfq_data *bfqd = e->elevator_data; \
5371 u64 __data = __VAR; \
5372 __data = div_u64(__data, NSEC_PER_USEC); \
5373 return bfq_var_show(__data, (page)); \
5374}
5375USEC_SHOW_FUNCTION(bfq_slice_idle_us_show, bfqd->bfq_slice_idle);
5376#undef USEC_SHOW_FUNCTION
5377
5378#define STORE_FUNCTION(__FUNC, __PTR, MIN, MAX, __CONV) \
5379static ssize_t \
5380__FUNC(struct elevator_queue *e, const char *page, size_t count) \
5381{ \
5382 struct bfq_data *bfqd = e->elevator_data; \
Bart Van Assche1530486c2017-08-30 11:42:10 -07005383 unsigned long __data, __min = (MIN), __max = (MAX); \
Bart Van Assche2f791362017-08-30 11:42:09 -07005384 int ret; \
5385 \
5386 ret = bfq_var_store(&__data, (page)); \
5387 if (ret) \
5388 return ret; \
Bart Van Assche1530486c2017-08-30 11:42:10 -07005389 if (__data < __min) \
5390 __data = __min; \
5391 else if (__data > __max) \
5392 __data = __max; \
Paolo Valenteaee69d72017-04-19 08:29:02 -06005393 if (__CONV == 1) \
5394 *(__PTR) = msecs_to_jiffies(__data); \
5395 else if (__CONV == 2) \
5396 *(__PTR) = (u64)__data * NSEC_PER_MSEC; \
5397 else \
5398 *(__PTR) = __data; \
weiping zhang235f8da2017-08-25 01:11:33 +08005399 return count; \
Paolo Valenteaee69d72017-04-19 08:29:02 -06005400}
5401STORE_FUNCTION(bfq_fifo_expire_sync_store, &bfqd->bfq_fifo_expire[1], 1,
5402 INT_MAX, 2);
5403STORE_FUNCTION(bfq_fifo_expire_async_store, &bfqd->bfq_fifo_expire[0], 1,
5404 INT_MAX, 2);
5405STORE_FUNCTION(bfq_back_seek_max_store, &bfqd->bfq_back_max, 0, INT_MAX, 0);
5406STORE_FUNCTION(bfq_back_seek_penalty_store, &bfqd->bfq_back_penalty, 1,
5407 INT_MAX, 0);
5408STORE_FUNCTION(bfq_slice_idle_store, &bfqd->bfq_slice_idle, 0, INT_MAX, 2);
5409#undef STORE_FUNCTION
5410
5411#define USEC_STORE_FUNCTION(__FUNC, __PTR, MIN, MAX) \
5412static ssize_t __FUNC(struct elevator_queue *e, const char *page, size_t count)\
5413{ \
5414 struct bfq_data *bfqd = e->elevator_data; \
Bart Van Assche1530486c2017-08-30 11:42:10 -07005415 unsigned long __data, __min = (MIN), __max = (MAX); \
Bart Van Assche2f791362017-08-30 11:42:09 -07005416 int ret; \
5417 \
5418 ret = bfq_var_store(&__data, (page)); \
5419 if (ret) \
5420 return ret; \
Bart Van Assche1530486c2017-08-30 11:42:10 -07005421 if (__data < __min) \
5422 __data = __min; \
5423 else if (__data > __max) \
5424 __data = __max; \
Paolo Valenteaee69d72017-04-19 08:29:02 -06005425 *(__PTR) = (u64)__data * NSEC_PER_USEC; \
weiping zhang235f8da2017-08-25 01:11:33 +08005426 return count; \
Paolo Valenteaee69d72017-04-19 08:29:02 -06005427}
5428USEC_STORE_FUNCTION(bfq_slice_idle_us_store, &bfqd->bfq_slice_idle, 0,
5429 UINT_MAX);
5430#undef USEC_STORE_FUNCTION
5431
Paolo Valenteaee69d72017-04-19 08:29:02 -06005432static ssize_t bfq_max_budget_store(struct elevator_queue *e,
5433 const char *page, size_t count)
5434{
5435 struct bfq_data *bfqd = e->elevator_data;
Bart Van Assche2f791362017-08-30 11:42:09 -07005436 unsigned long __data;
5437 int ret;
weiping zhang235f8da2017-08-25 01:11:33 +08005438
Bart Van Assche2f791362017-08-30 11:42:09 -07005439 ret = bfq_var_store(&__data, (page));
5440 if (ret)
5441 return ret;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005442
5443 if (__data == 0)
Paolo Valenteab0e43e2017-04-12 18:23:10 +02005444 bfqd->bfq_max_budget = bfq_calc_max_budget(bfqd);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005445 else {
5446 if (__data > INT_MAX)
5447 __data = INT_MAX;
5448 bfqd->bfq_max_budget = __data;
5449 }
5450
5451 bfqd->bfq_user_max_budget = __data;
5452
weiping zhang235f8da2017-08-25 01:11:33 +08005453 return count;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005454}
5455
5456/*
5457 * Leaving this name to preserve name compatibility with cfq
5458 * parameters, but this timeout is used for both sync and async.
5459 */
5460static ssize_t bfq_timeout_sync_store(struct elevator_queue *e,
5461 const char *page, size_t count)
5462{
5463 struct bfq_data *bfqd = e->elevator_data;
Bart Van Assche2f791362017-08-30 11:42:09 -07005464 unsigned long __data;
5465 int ret;
weiping zhang235f8da2017-08-25 01:11:33 +08005466
Bart Van Assche2f791362017-08-30 11:42:09 -07005467 ret = bfq_var_store(&__data, (page));
5468 if (ret)
5469 return ret;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005470
5471 if (__data < 1)
5472 __data = 1;
5473 else if (__data > INT_MAX)
5474 __data = INT_MAX;
5475
5476 bfqd->bfq_timeout = msecs_to_jiffies(__data);
5477 if (bfqd->bfq_user_max_budget == 0)
Paolo Valenteab0e43e2017-04-12 18:23:10 +02005478 bfqd->bfq_max_budget = bfq_calc_max_budget(bfqd);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005479
weiping zhang235f8da2017-08-25 01:11:33 +08005480 return count;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005481}
5482
5483static ssize_t bfq_strict_guarantees_store(struct elevator_queue *e,
5484 const char *page, size_t count)
5485{
5486 struct bfq_data *bfqd = e->elevator_data;
Bart Van Assche2f791362017-08-30 11:42:09 -07005487 unsigned long __data;
5488 int ret;
weiping zhang235f8da2017-08-25 01:11:33 +08005489
Bart Van Assche2f791362017-08-30 11:42:09 -07005490 ret = bfq_var_store(&__data, (page));
5491 if (ret)
5492 return ret;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005493
5494 if (__data > 1)
5495 __data = 1;
5496 if (!bfqd->strict_guarantees && __data == 1
5497 && bfqd->bfq_slice_idle < 8 * NSEC_PER_MSEC)
5498 bfqd->bfq_slice_idle = 8 * NSEC_PER_MSEC;
5499
5500 bfqd->strict_guarantees = __data;
5501
weiping zhang235f8da2017-08-25 01:11:33 +08005502 return count;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005503}
5504
Paolo Valente44e44a12017-04-12 18:23:12 +02005505static ssize_t bfq_low_latency_store(struct elevator_queue *e,
5506 const char *page, size_t count)
5507{
5508 struct bfq_data *bfqd = e->elevator_data;
Bart Van Assche2f791362017-08-30 11:42:09 -07005509 unsigned long __data;
5510 int ret;
weiping zhang235f8da2017-08-25 01:11:33 +08005511
Bart Van Assche2f791362017-08-30 11:42:09 -07005512 ret = bfq_var_store(&__data, (page));
5513 if (ret)
5514 return ret;
Paolo Valente44e44a12017-04-12 18:23:12 +02005515
5516 if (__data > 1)
5517 __data = 1;
5518 if (__data == 0 && bfqd->low_latency != 0)
5519 bfq_end_wr(bfqd);
5520 bfqd->low_latency = __data;
5521
weiping zhang235f8da2017-08-25 01:11:33 +08005522 return count;
Paolo Valente44e44a12017-04-12 18:23:12 +02005523}
5524
Paolo Valenteaee69d72017-04-19 08:29:02 -06005525#define BFQ_ATTR(name) \
5526 __ATTR(name, 0644, bfq_##name##_show, bfq_##name##_store)
5527
5528static struct elv_fs_entry bfq_attrs[] = {
5529 BFQ_ATTR(fifo_expire_sync),
5530 BFQ_ATTR(fifo_expire_async),
5531 BFQ_ATTR(back_seek_max),
5532 BFQ_ATTR(back_seek_penalty),
5533 BFQ_ATTR(slice_idle),
5534 BFQ_ATTR(slice_idle_us),
5535 BFQ_ATTR(max_budget),
5536 BFQ_ATTR(timeout_sync),
5537 BFQ_ATTR(strict_guarantees),
Paolo Valente44e44a12017-04-12 18:23:12 +02005538 BFQ_ATTR(low_latency),
Paolo Valenteaee69d72017-04-19 08:29:02 -06005539 __ATTR_NULL
5540};
5541
5542static struct elevator_type iosched_bfq_mq = {
5543 .ops.mq = {
Paolo Valentea52a69e2018-01-13 12:05:17 +01005544 .limit_depth = bfq_limit_depth,
Christoph Hellwig5bbf4e52017-06-16 18:15:26 +02005545 .prepare_request = bfq_prepare_request,
Paolo Valentea7877392018-02-07 22:19:20 +01005546 .requeue_request = bfq_finish_requeue_request,
5547 .finish_request = bfq_finish_requeue_request,
Paolo Valenteaee69d72017-04-19 08:29:02 -06005548 .exit_icq = bfq_exit_icq,
5549 .insert_requests = bfq_insert_requests,
5550 .dispatch_request = bfq_dispatch_request,
5551 .next_request = elv_rb_latter_request,
5552 .former_request = elv_rb_former_request,
5553 .allow_merge = bfq_allow_bio_merge,
5554 .bio_merge = bfq_bio_merge,
5555 .request_merge = bfq_request_merge,
5556 .requests_merged = bfq_requests_merged,
5557 .request_merged = bfq_request_merged,
5558 .has_work = bfq_has_work,
Jens Axboef0635b82018-05-09 13:27:21 -06005559 .init_hctx = bfq_init_hctx,
Paolo Valenteaee69d72017-04-19 08:29:02 -06005560 .init_sched = bfq_init_queue,
5561 .exit_sched = bfq_exit_queue,
5562 },
5563
5564 .uses_mq = true,
5565 .icq_size = sizeof(struct bfq_io_cq),
5566 .icq_align = __alignof__(struct bfq_io_cq),
5567 .elevator_attrs = bfq_attrs,
5568 .elevator_name = "bfq",
5569 .elevator_owner = THIS_MODULE,
5570};
Ben Hutchings26b4cf22017-08-13 18:02:19 +01005571MODULE_ALIAS("bfq-iosched");
Paolo Valenteaee69d72017-04-19 08:29:02 -06005572
5573static int __init bfq_init(void)
5574{
5575 int ret;
5576
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005577#ifdef CONFIG_BFQ_GROUP_IOSCHED
5578 ret = blkcg_policy_register(&blkcg_policy_bfq);
5579 if (ret)
5580 return ret;
5581#endif
5582
Paolo Valenteaee69d72017-04-19 08:29:02 -06005583 ret = -ENOMEM;
5584 if (bfq_slab_setup())
5585 goto err_pol_unreg;
5586
Paolo Valente44e44a12017-04-12 18:23:12 +02005587 /*
5588 * Times to load large popular applications for the typical
5589 * systems installed on the reference devices (see the
5590 * comments before the definitions of the next two
5591 * arrays). Actually, we use slightly slower values, as the
5592 * estimated peak rate tends to be smaller than the actual
5593 * peak rate. The reason for this last fact is that estimates
5594 * are computed over much shorter time intervals than the long
5595 * intervals typically used for benchmarking. Why? First, to
5596 * adapt more quickly to variations. Second, because an I/O
5597 * scheduler cannot rely on a peak-rate-evaluation workload to
5598 * be run for a long time.
5599 */
5600 T_slow[0] = msecs_to_jiffies(3500); /* actually 4 sec */
5601 T_slow[1] = msecs_to_jiffies(6000); /* actually 6.5 sec */
5602 T_fast[0] = msecs_to_jiffies(7000); /* actually 8 sec */
5603 T_fast[1] = msecs_to_jiffies(2500); /* actually 3 sec */
5604
5605 /*
5606 * Thresholds that determine the switch between speed classes
5607 * (see the comments before the definition of the array
5608 * device_speed_thresh). These thresholds are biased towards
5609 * transitions to the fast class. This is safer than the
5610 * opposite bias. In fact, a wrong transition to the slow
5611 * class results in short weight-raising periods, because the
5612 * speed of the device then tends to be higher that the
5613 * reference peak rate. On the opposite end, a wrong
5614 * transition to the fast class tends to increase
5615 * weight-raising periods, because of the opposite reason.
5616 */
5617 device_speed_thresh[0] = (4 * R_slow[0]) / 3;
5618 device_speed_thresh[1] = (4 * R_slow[1]) / 3;
5619
Paolo Valenteaee69d72017-04-19 08:29:02 -06005620 ret = elv_register(&iosched_bfq_mq);
5621 if (ret)
weiping zhang37dcd652017-08-19 00:37:20 +08005622 goto slab_kill;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005623
5624 return 0;
5625
weiping zhang37dcd652017-08-19 00:37:20 +08005626slab_kill:
5627 bfq_slab_kill();
Paolo Valenteaee69d72017-04-19 08:29:02 -06005628err_pol_unreg:
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005629#ifdef CONFIG_BFQ_GROUP_IOSCHED
5630 blkcg_policy_unregister(&blkcg_policy_bfq);
5631#endif
Paolo Valenteaee69d72017-04-19 08:29:02 -06005632 return ret;
5633}
5634
5635static void __exit bfq_exit(void)
5636{
5637 elv_unregister(&iosched_bfq_mq);
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005638#ifdef CONFIG_BFQ_GROUP_IOSCHED
5639 blkcg_policy_unregister(&blkcg_policy_bfq);
5640#endif
Paolo Valenteaee69d72017-04-19 08:29:02 -06005641 bfq_slab_kill();
5642}
5643
5644module_init(bfq_init);
5645module_exit(bfq_exit);
5646
5647MODULE_AUTHOR("Paolo Valente");
5648MODULE_LICENSE("GPL");
5649MODULE_DESCRIPTION("MQ Budget Fair Queueing I/O Scheduler");