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