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