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