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