2 * menu.c - the menu idle governor
4 * Copyright (C) 2006-2007 Adam Belay <abelay@novell.com>
5 * Copyright (C) 2009 Intel Corporation
7 * Arjan van de Ven <arjan@linux.intel.com>
9 * This code is licenced under the GPL version 2 as described
10 * in the COPYING file that acompanies the Linux Kernel.
13 #include <linux/kernel.h>
14 #include <linux/cpuidle.h>
15 #include <linux/pm_qos.h>
16 #include <linux/time.h>
17 #include <linux/ktime.h>
18 #include <linux/hrtimer.h>
19 #include <linux/tick.h>
20 #include <linux/sched.h>
21 #include <linux/math64.h>
22 #include <linux/module.h>
26 #define RESOLUTION 1024
28 #define MAX_INTERESTING 50000
29 #define STDDEV_THRESH 400
31 /* 60 * 60 > STDDEV_THRESH * INTERVALS = 400 * 8 */
32 #define MAX_DEVIATION 60
34 static DEFINE_PER_CPU(struct hrtimer, menu_hrtimer);
35 static DEFINE_PER_CPU(int, hrtimer_status);
36 /* menu hrtimer mode */
37 enum {MENU_HRTIMER_STOP, MENU_HRTIMER_REPEAT};
40 * Concepts and ideas behind the menu governor
42 * For the menu governor, there are 3 decision factors for picking a C
44 * 1) Energy break even point
45 * 2) Performance impact
46 * 3) Latency tolerance (from pmqos infrastructure)
47 * These these three factors are treated independently.
49 * Energy break even point
50 * -----------------------
51 * C state entry and exit have an energy cost, and a certain amount of time in
52 * the C state is required to actually break even on this cost. CPUIDLE
53 * provides us this duration in the "target_residency" field. So all that we
54 * need is a good prediction of how long we'll be idle. Like the traditional
55 * menu governor, we start with the actual known "next timer event" time.
57 * Since there are other source of wakeups (interrupts for example) than
58 * the next timer event, this estimation is rather optimistic. To get a
59 * more realistic estimate, a correction factor is applied to the estimate,
60 * that is based on historic behavior. For example, if in the past the actual
61 * duration always was 50% of the next timer tick, the correction factor will
64 * menu uses a running average for this correction factor, however it uses a
65 * set of factors, not just a single factor. This stems from the realization
66 * that the ratio is dependent on the order of magnitude of the expected
67 * duration; if we expect 500 milliseconds of idle time the likelihood of
68 * getting an interrupt very early is much higher than if we expect 50 micro
69 * seconds of idle time. A second independent factor that has big impact on
70 * the actual factor is if there is (disk) IO outstanding or not.
71 * (as a special twist, we consider every sleep longer than 50 milliseconds
72 * as perfect; there are no power gains for sleeping longer than this)
74 * For these two reasons we keep an array of 12 independent factors, that gets
75 * indexed based on the magnitude of the expected duration as well as the
76 * "is IO outstanding" property.
78 * Repeatable-interval-detector
79 * ----------------------------
80 * There are some cases where "next timer" is a completely unusable predictor:
81 * Those cases where the interval is fixed, for example due to hardware
82 * interrupt mitigation, but also due to fixed transfer rate devices such as
84 * For this, we use a different predictor: We track the duration of the last 8
85 * intervals and if the stand deviation of these 8 intervals is below a
86 * threshold value, we use the average of these intervals as prediction.
88 * Limiting Performance Impact
89 * ---------------------------
90 * C states, especially those with large exit latencies, can have a real
91 * noticeable impact on workloads, which is not acceptable for most sysadmins,
92 * and in addition, less performance has a power price of its own.
94 * As a general rule of thumb, menu assumes that the following heuristic
96 * The busier the system, the less impact of C states is acceptable
98 * This rule-of-thumb is implemented using a performance-multiplier:
99 * If the exit latency times the performance multiplier is longer than
100 * the predicted duration, the C state is not considered a candidate
101 * for selection due to a too high performance impact. So the higher
102 * this multiplier is, the longer we need to be idle to pick a deep C
103 * state, and thus the less likely a busy CPU will hit such a deep
106 * Two factors are used in determing this multiplier:
107 * a value of 10 is added for each point of "per cpu load average" we have.
108 * a value of 5 points is added for each process that is waiting for
110 * (these values are experimentally determined)
112 * The load average factor gives a longer term (few seconds) input to the
113 * decision, while the iowait value gives a cpu local instantanious input.
114 * The iowait factor may look low, but realize that this is also already
115 * represented in the system load average.
123 unsigned int expected_us;
125 unsigned int exit_us;
127 u64 correction_factor[BUCKETS];
128 u32 intervals[INTERVALS];
133 #define LOAD_INT(x) ((x) >> FSHIFT)
134 #define LOAD_FRAC(x) LOAD_INT(((x) & (FIXED_1-1)) * 100)
136 static int get_loadavg(void)
138 unsigned long this = this_cpu_load();
141 return LOAD_INT(this) * 10 + LOAD_FRAC(this) / 10;
144 static inline int which_bucket(unsigned int duration)
149 * We keep two groups of stats; one with no
150 * IO pending, one without.
151 * This allows us to calculate
154 if (nr_iowait_cpu(smp_processor_id()))
163 if (duration < 10000)
165 if (duration < 100000)
171 * Return a multiplier for the exit latency that is intended
172 * to take performance requirements into account.
173 * The more performance critical we estimate the system
174 * to be, the higher this multiplier, and thus the higher
175 * the barrier to go to an expensive C state.
177 static inline int performance_multiplier(void)
181 /* for higher loadavg, we are more reluctant */
183 mult += 2 * get_loadavg();
185 /* for IO wait tasks (per cpu!) we add 5x each */
186 mult += 10 * nr_iowait_cpu(smp_processor_id());
191 static DEFINE_PER_CPU(struct menu_device, menu_devices);
193 static void menu_update(struct cpuidle_driver *drv, struct cpuidle_device *dev);
195 /* This implements DIV_ROUND_CLOSEST but avoids 64 bit division */
196 static u64 div_round64(u64 dividend, u32 divisor)
198 return div_u64(dividend + (divisor / 2), divisor);
201 /* Cancel the hrtimer if it is not triggered yet */
202 void menu_hrtimer_cancel(void)
204 int cpu = smp_processor_id();
205 struct hrtimer *hrtmr = &per_cpu(menu_hrtimer, cpu);
207 /* The timer is still not time out*/
208 if (per_cpu(hrtimer_status, cpu)) {
209 hrtimer_cancel(hrtmr);
210 per_cpu(hrtimer_status, cpu) = MENU_HRTIMER_STOP;
213 EXPORT_SYMBOL_GPL(menu_hrtimer_cancel);
215 /* Call back for hrtimer is triggered */
216 static enum hrtimer_restart menu_hrtimer_notify(struct hrtimer *hrtimer)
218 int cpu = smp_processor_id();
220 per_cpu(hrtimer_status, cpu) = MENU_HRTIMER_STOP;
222 return HRTIMER_NORESTART;
226 * Try detecting repeating patterns by keeping track of the last 8
227 * intervals, and checking if the standard deviation of that set
228 * of points is below a threshold. If it is... then use the
229 * average of these 8 points as the estimated value.
231 static u32 get_typical_interval(struct menu_device *data)
233 int i = 0, divisor = 0;
234 uint64_t max = 0, avg = 0, stddev = 0;
235 int64_t thresh = LLONG_MAX; /* Discard outliers above this value. */
236 unsigned int ret = 0;
240 /* first calculate average and standard deviation of the past */
241 max = avg = divisor = stddev = 0;
242 for (i = 0; i < INTERVALS; i++) {
243 int64_t value = data->intervals[i];
244 if (value <= thresh) {
251 do_div(avg, divisor);
253 for (i = 0; i < INTERVALS; i++) {
254 int64_t value = data->intervals[i];
255 if (value <= thresh) {
256 int64_t diff = value - avg;
257 stddev += diff * diff;
260 do_div(stddev, divisor);
261 stddev = int_sqrt(stddev);
263 * If we have outliers to the upside in our distribution, discard
264 * those by setting the threshold to exclude these outliers, then
265 * calculate the average and standard deviation again. Once we get
266 * down to the bottom 3/4 of our samples, stop excluding samples.
268 * This can deal with workloads that have long pauses interspersed
269 * with sporadic activity with a bunch of short pauses.
271 * The typical interval is obtained when standard deviation is small
272 * or standard deviation is small compared to the average interval.
274 if (((avg > stddev * 6) && (divisor * 4 >= INTERVALS * 3))
276 data->predicted_us = avg;
280 } else if ((divisor * 4) > INTERVALS * 3) {
281 /* Exclude the max interval */
290 * menu_select - selects the next idle state to enter
291 * @drv: cpuidle driver containing state data
294 static int menu_select(struct cpuidle_driver *drv, struct cpuidle_device *dev)
296 struct menu_device *data = &__get_cpu_var(menu_devices);
297 int latency_req = pm_qos_request(PM_QOS_CPU_DMA_LATENCY);
301 int repeat = 0, low_predicted = 0;
302 int cpu = smp_processor_id();
303 struct hrtimer *hrtmr = &per_cpu(menu_hrtimer, cpu);
305 if (data->needs_update) {
306 menu_update(drv, dev);
307 data->needs_update = 0;
310 data->last_state_idx = 0;
313 /* Special case when user has set very strict latency requirement */
314 if (unlikely(latency_req == 0))
317 /* determine the expected residency time, round up */
318 t = ktime_to_timespec(tick_nohz_get_sleep_length());
320 t.tv_sec * USEC_PER_SEC + t.tv_nsec / NSEC_PER_USEC;
323 data->bucket = which_bucket(data->expected_us);
325 multiplier = performance_multiplier();
328 * if the correction factor is 0 (eg first time init or cpu hotplug
329 * etc), we actually want to start out with a unity factor.
331 if (data->correction_factor[data->bucket] == 0)
332 data->correction_factor[data->bucket] = RESOLUTION * DECAY;
334 /* Make sure to round up for half microseconds */
335 data->predicted_us = div_round64(data->expected_us * data->correction_factor[data->bucket],
338 repeat = get_typical_interval(data);
341 * We want to default to C1 (hlt), not to busy polling
342 * unless the timer is happening really really soon.
344 if (data->expected_us > 5 &&
345 !drv->states[CPUIDLE_DRIVER_STATE_START].disabled &&
346 dev->states_usage[CPUIDLE_DRIVER_STATE_START].disable == 0)
347 data->last_state_idx = CPUIDLE_DRIVER_STATE_START;
350 * Find the idle state with the lowest power while satisfying
353 for (i = CPUIDLE_DRIVER_STATE_START; i < drv->state_count; i++) {
354 struct cpuidle_state *s = &drv->states[i];
355 struct cpuidle_state_usage *su = &dev->states_usage[i];
357 if (s->disabled || su->disable)
359 if (s->target_residency > data->predicted_us) {
363 if (s->exit_latency > latency_req)
365 if (s->exit_latency * multiplier > data->predicted_us)
368 data->last_state_idx = i;
369 data->exit_us = s->exit_latency;
372 /* not deepest C-state chosen for low predicted residency */
374 unsigned int timer_us = 0;
377 * Set a timer to detect whether this sleep is much
378 * longer than repeat mode predicted. If the timer
379 * triggers, the code will evaluate whether to put
380 * the CPU into a deeper C-state.
381 * The timer is cancelled on CPU wakeup.
383 timer_us = 2 * (data->predicted_us + MAX_DEVIATION);
385 if (repeat && (4 * timer_us < data->expected_us)) {
386 RCU_NONIDLE(hrtimer_start(hrtmr,
387 ns_to_ktime(1000 * timer_us),
388 HRTIMER_MODE_REL_PINNED));
389 /* In repeat case, menu hrtimer is started */
390 per_cpu(hrtimer_status, cpu) = MENU_HRTIMER_REPEAT;
394 return data->last_state_idx;
398 * menu_reflect - records that data structures need update
400 * @index: the index of actual entered state
402 * NOTE: it's important to be fast here because this operation will add to
403 * the overall exit latency.
405 static void menu_reflect(struct cpuidle_device *dev, int index)
407 struct menu_device *data = &__get_cpu_var(menu_devices);
408 data->last_state_idx = index;
410 data->needs_update = 1;
414 * menu_update - attempts to guess what happened after entry
415 * @drv: cpuidle driver containing state data
418 static void menu_update(struct cpuidle_driver *drv, struct cpuidle_device *dev)
420 struct menu_device *data = &__get_cpu_var(menu_devices);
421 int last_idx = data->last_state_idx;
422 unsigned int last_idle_us = cpuidle_get_last_residency(dev);
423 struct cpuidle_state *target = &drv->states[last_idx];
424 unsigned int measured_us;
428 * Ugh, this idle state doesn't support residency measurements, so we
429 * are basically lost in the dark. As a compromise, assume we slept
430 * for the whole expected time.
432 if (unlikely(!(target->flags & CPUIDLE_FLAG_TIME_VALID)))
433 last_idle_us = data->expected_us;
436 measured_us = last_idle_us;
439 * We correct for the exit latency; we are assuming here that the
440 * exit latency happens after the event that we're interested in.
442 if (measured_us > data->exit_us)
443 measured_us -= data->exit_us;
446 /* update our correction ratio */
448 new_factor = data->correction_factor[data->bucket]
449 * (DECAY - 1) / DECAY;
451 if (data->expected_us > 0 && measured_us < MAX_INTERESTING)
452 new_factor += RESOLUTION * measured_us / data->expected_us;
455 * we were idle so long that we count it as a perfect
458 new_factor += RESOLUTION;
461 * We don't want 0 as factor; we always want at least
462 * a tiny bit of estimated time.
467 data->correction_factor[data->bucket] = new_factor;
469 /* update the repeating-pattern data */
470 data->intervals[data->interval_ptr++] = last_idle_us;
471 if (data->interval_ptr >= INTERVALS)
472 data->interval_ptr = 0;
476 * menu_enable_device - scans a CPU's states and does setup
477 * @drv: cpuidle driver
480 static int menu_enable_device(struct cpuidle_driver *drv,
481 struct cpuidle_device *dev)
483 struct menu_device *data = &per_cpu(menu_devices, dev->cpu);
484 struct hrtimer *t = &per_cpu(menu_hrtimer, dev->cpu);
485 hrtimer_init(t, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
486 t->function = menu_hrtimer_notify;
488 memset(data, 0, sizeof(struct menu_device));
493 static struct cpuidle_governor menu_governor = {
496 .enable = menu_enable_device,
497 .select = menu_select,
498 .reflect = menu_reflect,
499 .owner = THIS_MODULE,
503 * init_menu - initializes the governor
505 static int __init init_menu(void)
507 return cpuidle_register_governor(&menu_governor);
511 * exit_menu - exits the governor
513 static void __exit exit_menu(void)
515 cpuidle_unregister_governor(&menu_governor);
518 MODULE_LICENSE("GPL");
519 module_init(init_menu);
520 module_exit(exit_menu);