xref: /openbmc/linux/drivers/cpuidle/governors/menu.c (revision 4d75f5c664195b970e1cd2fd25b65b5eff257a0a)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * menu.c - the menu idle governor
4  *
5  * Copyright (C) 2006-2007 Adam Belay <abelay@novell.com>
6  * Copyright (C) 2009 Intel Corporation
7  * Author:
8  *        Arjan van de Ven <arjan@linux.intel.com>
9  */
10 
11 #include <linux/kernel.h>
12 #include <linux/cpuidle.h>
13 #include <linux/time.h>
14 #include <linux/ktime.h>
15 #include <linux/hrtimer.h>
16 #include <linux/tick.h>
17 #include <linux/sched.h>
18 #include <linux/sched/loadavg.h>
19 #include <linux/sched/stat.h>
20 #include <linux/math64.h>
21 
22 #include "gov.h"
23 
24 #define BUCKETS 12
25 #define INTERVAL_SHIFT 3
26 #define INTERVALS (1UL << INTERVAL_SHIFT)
27 #define RESOLUTION 1024
28 #define DECAY 8
29 #define MAX_INTERESTING (50000 * NSEC_PER_USEC)
30 
31 /*
32  * Concepts and ideas behind the menu governor
33  *
34  * For the menu governor, there are 3 decision factors for picking a C
35  * state:
36  * 1) Energy break even point
37  * 2) Performance impact
38  * 3) Latency tolerance (from pmqos infrastructure)
39  * These three factors are treated independently.
40  *
41  * Energy break even point
42  * -----------------------
43  * C state entry and exit have an energy cost, and a certain amount of time in
44  * the  C state is required to actually break even on this cost. CPUIDLE
45  * provides us this duration in the "target_residency" field. So all that we
46  * need is a good prediction of how long we'll be idle. Like the traditional
47  * menu governor, we start with the actual known "next timer event" time.
48  *
49  * Since there are other source of wakeups (interrupts for example) than
50  * the next timer event, this estimation is rather optimistic. To get a
51  * more realistic estimate, a correction factor is applied to the estimate,
52  * that is based on historic behavior. For example, if in the past the actual
53  * duration always was 50% of the next timer tick, the correction factor will
54  * be 0.5.
55  *
56  * menu uses a running average for this correction factor, however it uses a
57  * set of factors, not just a single factor. This stems from the realization
58  * that the ratio is dependent on the order of magnitude of the expected
59  * duration; if we expect 500 milliseconds of idle time the likelihood of
60  * getting an interrupt very early is much higher than if we expect 50 micro
61  * seconds of idle time. A second independent factor that has big impact on
62  * the actual factor is if there is (disk) IO outstanding or not.
63  * (as a special twist, we consider every sleep longer than 50 milliseconds
64  * as perfect; there are no power gains for sleeping longer than this)
65  *
66  * For these two reasons we keep an array of 12 independent factors, that gets
67  * indexed based on the magnitude of the expected duration as well as the
68  * "is IO outstanding" property.
69  *
70  * Repeatable-interval-detector
71  * ----------------------------
72  * There are some cases where "next timer" is a completely unusable predictor:
73  * Those cases where the interval is fixed, for example due to hardware
74  * interrupt mitigation, but also due to fixed transfer rate devices such as
75  * mice.
76  * For this, we use a different predictor: We track the duration of the last 8
77  * intervals and if the stand deviation of these 8 intervals is below a
78  * threshold value, we use the average of these intervals as prediction.
79  *
80  * Limiting Performance Impact
81  * ---------------------------
82  * C states, especially those with large exit latencies, can have a real
83  * noticeable impact on workloads, which is not acceptable for most sysadmins,
84  * and in addition, less performance has a power price of its own.
85  *
86  * As a general rule of thumb, menu assumes that the following heuristic
87  * holds:
88  *     The busier the system, the less impact of C states is acceptable
89  *
90  * This rule-of-thumb is implemented using a performance-multiplier:
91  * If the exit latency times the performance multiplier is longer than
92  * the predicted duration, the C state is not considered a candidate
93  * for selection due to a too high performance impact. So the higher
94  * this multiplier is, the longer we need to be idle to pick a deep C
95  * state, and thus the less likely a busy CPU will hit such a deep
96  * C state.
97  *
98  * Two factors are used in determing this multiplier:
99  * a value of 10 is added for each point of "per cpu load average" we have.
100  * a value of 5 points is added for each process that is waiting for
101  * IO on this CPU.
102  * (these values are experimentally determined)
103  *
104  * The load average factor gives a longer term (few seconds) input to the
105  * decision, while the iowait value gives a cpu local instantanious input.
106  * The iowait factor may look low, but realize that this is also already
107  * represented in the system load average.
108  *
109  */
110 
111 struct menu_device {
112 	int             needs_update;
113 	int             tick_wakeup;
114 
115 	u64		next_timer_ns;
116 	unsigned int	bucket;
117 	unsigned int	correction_factor[BUCKETS];
118 	unsigned int	intervals[INTERVALS];
119 	int		interval_ptr;
120 };
121 
which_bucket(u64 duration_ns,unsigned int nr_iowaiters)122 static inline int which_bucket(u64 duration_ns, unsigned int nr_iowaiters)
123 {
124 	int bucket = 0;
125 
126 	/*
127 	 * We keep two groups of stats; one with no
128 	 * IO pending, one without.
129 	 * This allows us to calculate
130 	 * E(duration)|iowait
131 	 */
132 	if (nr_iowaiters)
133 		bucket = BUCKETS/2;
134 
135 	if (duration_ns < 10ULL * NSEC_PER_USEC)
136 		return bucket;
137 	if (duration_ns < 100ULL * NSEC_PER_USEC)
138 		return bucket + 1;
139 	if (duration_ns < 1000ULL * NSEC_PER_USEC)
140 		return bucket + 2;
141 	if (duration_ns < 10000ULL * NSEC_PER_USEC)
142 		return bucket + 3;
143 	if (duration_ns < 100000ULL * NSEC_PER_USEC)
144 		return bucket + 4;
145 	return bucket + 5;
146 }
147 
148 /*
149  * Return a multiplier for the exit latency that is intended
150  * to take performance requirements into account.
151  * The more performance critical we estimate the system
152  * to be, the higher this multiplier, and thus the higher
153  * the barrier to go to an expensive C state.
154  */
performance_multiplier(unsigned int nr_iowaiters)155 static inline int performance_multiplier(unsigned int nr_iowaiters)
156 {
157 	/* for IO wait tasks (per cpu!) we add 10x each */
158 	return 1 + 10 * nr_iowaiters;
159 }
160 
161 static DEFINE_PER_CPU(struct menu_device, menu_devices);
162 
163 static void menu_update(struct cpuidle_driver *drv, struct cpuidle_device *dev);
164 
165 /*
166  * Try detecting repeating patterns by keeping track of the last 8
167  * intervals, and checking if the standard deviation of that set
168  * of points is below a threshold. If it is... then use the
169  * average of these 8 points as the estimated value.
170  */
get_typical_interval(struct menu_device * data)171 static unsigned int get_typical_interval(struct menu_device *data)
172 {
173 	int i, divisor;
174 	unsigned int min, max, thresh, avg;
175 	uint64_t sum, variance;
176 
177 	thresh = INT_MAX; /* Discard outliers above this value */
178 
179 again:
180 
181 	/* First calculate the average of past intervals */
182 	min = UINT_MAX;
183 	max = 0;
184 	sum = 0;
185 	divisor = 0;
186 	for (i = 0; i < INTERVALS; i++) {
187 		unsigned int value = data->intervals[i];
188 		if (value <= thresh) {
189 			sum += value;
190 			divisor++;
191 			if (value > max)
192 				max = value;
193 
194 			if (value < min)
195 				min = value;
196 		}
197 	}
198 
199 	if (!max)
200 		return UINT_MAX;
201 
202 	if (divisor == INTERVALS)
203 		avg = sum >> INTERVAL_SHIFT;
204 	else
205 		avg = div_u64(sum, divisor);
206 
207 	/* Then try to determine variance */
208 	variance = 0;
209 	for (i = 0; i < INTERVALS; i++) {
210 		unsigned int value = data->intervals[i];
211 		if (value <= thresh) {
212 			int64_t diff = (int64_t)value - avg;
213 			variance += diff * diff;
214 		}
215 	}
216 	if (divisor == INTERVALS)
217 		variance >>= INTERVAL_SHIFT;
218 	else
219 		do_div(variance, divisor);
220 
221 	/*
222 	 * The typical interval is obtained when standard deviation is
223 	 * small (stddev <= 20 us, variance <= 400 us^2) or standard
224 	 * deviation is small compared to the average interval (avg >
225 	 * 6*stddev, avg^2 > 36*variance). The average is smaller than
226 	 * UINT_MAX aka U32_MAX, so computing its square does not
227 	 * overflow a u64. We simply reject this candidate average if
228 	 * the standard deviation is greater than 715 s (which is
229 	 * rather unlikely).
230 	 *
231 	 * Use this result only if there is no timer to wake us up sooner.
232 	 */
233 	if (likely(variance <= U64_MAX/36)) {
234 		if ((((u64)avg*avg > variance*36) && (divisor * 4 >= INTERVALS * 3))
235 							|| variance <= 400) {
236 			return avg;
237 		}
238 	}
239 
240 	/*
241 	 * If we have outliers to the upside in our distribution, discard
242 	 * those by setting the threshold to exclude these outliers, then
243 	 * calculate the average and standard deviation again. Once we get
244 	 * down to the bottom 3/4 of our samples, stop excluding samples.
245 	 *
246 	 * This can deal with workloads that have long pauses interspersed
247 	 * with sporadic activity with a bunch of short pauses.
248 	 */
249 	if (divisor * 4 <= INTERVALS * 3) {
250 		/*
251 		 * If there are sufficiently many data points still under
252 		 * consideration after the outliers have been eliminated,
253 		 * returning without a prediction would be a mistake because it
254 		 * is likely that the next interval will not exceed the current
255 		 * maximum, so return the latter in that case.
256 		 */
257 		if (divisor >= INTERVALS / 2)
258 			return max;
259 
260 		return UINT_MAX;
261 	}
262 
263 	thresh = max - 1;
264 	goto again;
265 }
266 
267 /**
268  * menu_select - selects the next idle state to enter
269  * @drv: cpuidle driver containing state data
270  * @dev: the CPU
271  * @stop_tick: indication on whether or not to stop the tick
272  */
menu_select(struct cpuidle_driver * drv,struct cpuidle_device * dev,bool * stop_tick)273 static int menu_select(struct cpuidle_driver *drv, struct cpuidle_device *dev,
274 		       bool *stop_tick)
275 {
276 	struct menu_device *data = this_cpu_ptr(&menu_devices);
277 	s64 latency_req = cpuidle_governor_latency_req(dev->cpu);
278 	u64 predicted_ns;
279 	u64 interactivity_req;
280 	unsigned int nr_iowaiters;
281 	ktime_t delta, delta_tick;
282 	int i, idx;
283 
284 	if (data->needs_update) {
285 		menu_update(drv, dev);
286 		data->needs_update = 0;
287 	}
288 
289 	nr_iowaiters = nr_iowait_cpu(dev->cpu);
290 
291 	/* Find the shortest expected idle interval. */
292 	predicted_ns = get_typical_interval(data) * NSEC_PER_USEC;
293 	if (predicted_ns > RESIDENCY_THRESHOLD_NS) {
294 		unsigned int timer_us;
295 
296 		/* Determine the time till the closest timer. */
297 		delta = tick_nohz_get_sleep_length(&delta_tick);
298 		if (unlikely(delta < 0)) {
299 			delta = 0;
300 			delta_tick = 0;
301 		}
302 
303 		data->next_timer_ns = delta;
304 		data->bucket = which_bucket(data->next_timer_ns, nr_iowaiters);
305 
306 		/* Round up the result for half microseconds. */
307 		timer_us = div_u64((RESOLUTION * DECAY * NSEC_PER_USEC) / 2 +
308 					data->next_timer_ns *
309 						data->correction_factor[data->bucket],
310 				   RESOLUTION * DECAY * NSEC_PER_USEC);
311 		/* Use the lowest expected idle interval to pick the idle state. */
312 		predicted_ns = min((u64)timer_us * NSEC_PER_USEC, predicted_ns);
313 	} else {
314 		/*
315 		 * Because the next timer event is not going to be determined
316 		 * in this case, assume that without the tick the closest timer
317 		 * will be in distant future and that the closest tick will occur
318 		 * after 1/2 of the tick period.
319 		 */
320 		data->next_timer_ns = KTIME_MAX;
321 		delta_tick = TICK_NSEC / 2;
322 		data->bucket = which_bucket(KTIME_MAX, nr_iowaiters);
323 	}
324 
325 	if (unlikely(drv->state_count <= 1 || latency_req == 0) ||
326 	    ((data->next_timer_ns < drv->states[1].target_residency_ns ||
327 	      latency_req < drv->states[1].exit_latency_ns) &&
328 	     !dev->states_usage[0].disable)) {
329 		/*
330 		 * In this case state[0] will be used no matter what, so return
331 		 * it right away and keep the tick running if state[0] is a
332 		 * polling one.
333 		 */
334 		*stop_tick = !(drv->states[0].flags & CPUIDLE_FLAG_POLLING);
335 		return 0;
336 	}
337 
338 	if (tick_nohz_tick_stopped()) {
339 		/*
340 		 * If the tick is already stopped, the cost of possible short
341 		 * idle duration misprediction is much higher, because the CPU
342 		 * may be stuck in a shallow idle state for a long time as a
343 		 * result of it.  In that case say we might mispredict and use
344 		 * the known time till the closest timer event for the idle
345 		 * state selection.
346 		 */
347 		if (predicted_ns < TICK_NSEC)
348 			predicted_ns = data->next_timer_ns;
349 	} else {
350 		/*
351 		 * Use the performance multiplier and the user-configurable
352 		 * latency_req to determine the maximum exit latency.
353 		 */
354 		interactivity_req = div64_u64(predicted_ns,
355 					      performance_multiplier(nr_iowaiters));
356 		if (latency_req > interactivity_req)
357 			latency_req = interactivity_req;
358 	}
359 
360 	/*
361 	 * Find the idle state with the lowest power while satisfying
362 	 * our constraints.
363 	 */
364 	idx = -1;
365 	for (i = 0; i < drv->state_count; i++) {
366 		struct cpuidle_state *s = &drv->states[i];
367 
368 		if (dev->states_usage[i].disable)
369 			continue;
370 
371 		if (idx == -1)
372 			idx = i; /* first enabled state */
373 
374 		if (s->target_residency_ns > predicted_ns) {
375 			/*
376 			 * Use a physical idle state, not busy polling, unless
377 			 * a timer is going to trigger soon enough.
378 			 */
379 			if ((drv->states[idx].flags & CPUIDLE_FLAG_POLLING) &&
380 			    s->exit_latency_ns <= latency_req &&
381 			    s->target_residency_ns <= data->next_timer_ns) {
382 				predicted_ns = s->target_residency_ns;
383 				idx = i;
384 				break;
385 			}
386 			if (predicted_ns < TICK_NSEC)
387 				break;
388 
389 			if (!tick_nohz_tick_stopped()) {
390 				/*
391 				 * If the state selected so far is shallow,
392 				 * waking up early won't hurt, so retain the
393 				 * tick in that case and let the governor run
394 				 * again in the next iteration of the loop.
395 				 */
396 				predicted_ns = drv->states[idx].target_residency_ns;
397 				break;
398 			}
399 
400 			/*
401 			 * If the state selected so far is shallow and this
402 			 * state's target residency matches the time till the
403 			 * closest timer event, select this one to avoid getting
404 			 * stuck in the shallow one for too long.
405 			 */
406 			if (drv->states[idx].target_residency_ns < TICK_NSEC &&
407 			    s->target_residency_ns <= delta_tick)
408 				idx = i;
409 
410 			return idx;
411 		}
412 		if (s->exit_latency_ns > latency_req)
413 			break;
414 
415 		idx = i;
416 	}
417 
418 	if (idx == -1)
419 		idx = 0; /* No states enabled. Must use 0. */
420 
421 	/*
422 	 * Don't stop the tick if the selected state is a polling one or if the
423 	 * expected idle duration is shorter than the tick period length.
424 	 */
425 	if (((drv->states[idx].flags & CPUIDLE_FLAG_POLLING) ||
426 	     predicted_ns < TICK_NSEC) && !tick_nohz_tick_stopped()) {
427 		*stop_tick = false;
428 
429 		if (idx > 0 && drv->states[idx].target_residency_ns > delta_tick) {
430 			/*
431 			 * The tick is not going to be stopped and the target
432 			 * residency of the state to be returned is not within
433 			 * the time until the next timer event including the
434 			 * tick, so try to correct that.
435 			 */
436 			for (i = idx - 1; i >= 0; i--) {
437 				if (dev->states_usage[i].disable)
438 					continue;
439 
440 				idx = i;
441 				if (drv->states[i].target_residency_ns <= delta_tick)
442 					break;
443 			}
444 		}
445 	}
446 
447 	return idx;
448 }
449 
450 /**
451  * menu_reflect - records that data structures need update
452  * @dev: the CPU
453  * @index: the index of actual entered state
454  *
455  * NOTE: it's important to be fast here because this operation will add to
456  *       the overall exit latency.
457  */
menu_reflect(struct cpuidle_device * dev,int index)458 static void menu_reflect(struct cpuidle_device *dev, int index)
459 {
460 	struct menu_device *data = this_cpu_ptr(&menu_devices);
461 
462 	dev->last_state_idx = index;
463 	data->needs_update = 1;
464 	data->tick_wakeup = tick_nohz_idle_got_tick();
465 }
466 
467 /**
468  * menu_update - attempts to guess what happened after entry
469  * @drv: cpuidle driver containing state data
470  * @dev: the CPU
471  */
menu_update(struct cpuidle_driver * drv,struct cpuidle_device * dev)472 static void menu_update(struct cpuidle_driver *drv, struct cpuidle_device *dev)
473 {
474 	struct menu_device *data = this_cpu_ptr(&menu_devices);
475 	int last_idx = dev->last_state_idx;
476 	struct cpuidle_state *target = &drv->states[last_idx];
477 	u64 measured_ns;
478 	unsigned int new_factor;
479 
480 	/*
481 	 * Try to figure out how much time passed between entry to low
482 	 * power state and occurrence of the wakeup event.
483 	 *
484 	 * If the entered idle state didn't support residency measurements,
485 	 * we use them anyway if they are short, and if long,
486 	 * truncate to the whole expected time.
487 	 *
488 	 * Any measured amount of time will include the exit latency.
489 	 * Since we are interested in when the wakeup begun, not when it
490 	 * was completed, we must subtract the exit latency. However, if
491 	 * the measured amount of time is less than the exit latency,
492 	 * assume the state was never reached and the exit latency is 0.
493 	 */
494 
495 	if (data->tick_wakeup && data->next_timer_ns > TICK_NSEC) {
496 		/*
497 		 * The nohz code said that there wouldn't be any events within
498 		 * the tick boundary (if the tick was stopped), but the idle
499 		 * duration predictor had a differing opinion.  Since the CPU
500 		 * was woken up by a tick (that wasn't stopped after all), the
501 		 * predictor was not quite right, so assume that the CPU could
502 		 * have been idle long (but not forever) to help the idle
503 		 * duration predictor do a better job next time.
504 		 */
505 		measured_ns = 9 * MAX_INTERESTING / 10;
506 	} else if ((drv->states[last_idx].flags & CPUIDLE_FLAG_POLLING) &&
507 		   dev->poll_time_limit) {
508 		/*
509 		 * The CPU exited the "polling" state due to a time limit, so
510 		 * the idle duration prediction leading to the selection of that
511 		 * state was inaccurate.  If a better prediction had been made,
512 		 * the CPU might have been woken up from idle by the next timer.
513 		 * Assume that to be the case.
514 		 */
515 		measured_ns = data->next_timer_ns;
516 	} else {
517 		/* measured value */
518 		measured_ns = dev->last_residency_ns;
519 
520 		/* Deduct exit latency */
521 		if (measured_ns > 2 * target->exit_latency_ns)
522 			measured_ns -= target->exit_latency_ns;
523 		else
524 			measured_ns /= 2;
525 	}
526 
527 	/* Make sure our coefficients do not exceed unity */
528 	if (measured_ns > data->next_timer_ns)
529 		measured_ns = data->next_timer_ns;
530 
531 	/* Update our correction ratio */
532 	new_factor = data->correction_factor[data->bucket];
533 	new_factor -= new_factor / DECAY;
534 
535 	if (data->next_timer_ns > 0 && measured_ns < MAX_INTERESTING)
536 		new_factor += div64_u64(RESOLUTION * measured_ns,
537 					data->next_timer_ns);
538 	else
539 		/*
540 		 * we were idle so long that we count it as a perfect
541 		 * prediction
542 		 */
543 		new_factor += RESOLUTION;
544 
545 	/*
546 	 * We don't want 0 as factor; we always want at least
547 	 * a tiny bit of estimated time. Fortunately, due to rounding,
548 	 * new_factor will stay nonzero regardless of measured_us values
549 	 * and the compiler can eliminate this test as long as DECAY > 1.
550 	 */
551 	if (DECAY == 1 && unlikely(new_factor == 0))
552 		new_factor = 1;
553 
554 	data->correction_factor[data->bucket] = new_factor;
555 
556 	/* update the repeating-pattern data */
557 	data->intervals[data->interval_ptr++] = ktime_to_us(measured_ns);
558 	if (data->interval_ptr >= INTERVALS)
559 		data->interval_ptr = 0;
560 }
561 
562 /**
563  * menu_enable_device - scans a CPU's states and does setup
564  * @drv: cpuidle driver
565  * @dev: the CPU
566  */
menu_enable_device(struct cpuidle_driver * drv,struct cpuidle_device * dev)567 static int menu_enable_device(struct cpuidle_driver *drv,
568 				struct cpuidle_device *dev)
569 {
570 	struct menu_device *data = &per_cpu(menu_devices, dev->cpu);
571 	int i;
572 
573 	memset(data, 0, sizeof(struct menu_device));
574 
575 	/*
576 	 * if the correction factor is 0 (eg first time init or cpu hotplug
577 	 * etc), we actually want to start out with a unity factor.
578 	 */
579 	for(i = 0; i < BUCKETS; i++)
580 		data->correction_factor[i] = RESOLUTION * DECAY;
581 
582 	return 0;
583 }
584 
585 static struct cpuidle_governor menu_governor = {
586 	.name =		"menu",
587 	.rating =	20,
588 	.enable =	menu_enable_device,
589 	.select =	menu_select,
590 	.reflect =	menu_reflect,
591 };
592 
593 /**
594  * init_menu - initializes the governor
595  */
init_menu(void)596 static int __init init_menu(void)
597 {
598 	return cpuidle_register_governor(&menu_governor);
599 }
600 
601 postcore_initcall(init_menu);
602