menu.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. #include <linux/kernel.h>
  13. #include <linux/cpuidle.h>
  14. #include <linux/pm_qos.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/math64.h>
  21. /*
  22. * Please note when changing the tuning values:
  23. * If (MAX_INTERESTING-1) * RESOLUTION > UINT_MAX, the result of
  24. * a scaling operation multiplication may overflow on 32 bit platforms.
  25. * In that case, #define RESOLUTION as ULL to get 64 bit result:
  26. * #define RESOLUTION 1024ULL
  27. *
  28. * The default values do not overflow.
  29. */
  30. #define BUCKETS 12
  31. #define INTERVAL_SHIFT 3
  32. #define INTERVALS (1UL << INTERVAL_SHIFT)
  33. #define RESOLUTION 1024
  34. #define DECAY 8
  35. #define MAX_INTERESTING 50000
  36. /*
  37. * Concepts and ideas behind the menu governor
  38. *
  39. * For the menu governor, there are 3 decision factors for picking a C
  40. * state:
  41. * 1) Energy break even point
  42. * 2) Performance impact
  43. * 3) Latency tolerance (from pmqos infrastructure)
  44. * These these three factors are treated independently.
  45. *
  46. * Energy break even point
  47. * -----------------------
  48. * C state entry and exit have an energy cost, and a certain amount of time in
  49. * the C state is required to actually break even on this cost. CPUIDLE
  50. * provides us this duration in the "target_residency" field. So all that we
  51. * need is a good prediction of how long we'll be idle. Like the traditional
  52. * menu governor, we start with the actual known "next timer event" time.
  53. *
  54. * Since there are other source of wakeups (interrupts for example) than
  55. * the next timer event, this estimation is rather optimistic. To get a
  56. * more realistic estimate, a correction factor is applied to the estimate,
  57. * that is based on historic behavior. For example, if in the past the actual
  58. * duration always was 50% of the next timer tick, the correction factor will
  59. * be 0.5.
  60. *
  61. * menu uses a running average for this correction factor, however it uses a
  62. * set of factors, not just a single factor. This stems from the realization
  63. * that the ratio is dependent on the order of magnitude of the expected
  64. * duration; if we expect 500 milliseconds of idle time the likelihood of
  65. * getting an interrupt very early is much higher than if we expect 50 micro
  66. * seconds of idle time. A second independent factor that has big impact on
  67. * the actual factor is if there is (disk) IO outstanding or not.
  68. * (as a special twist, we consider every sleep longer than 50 milliseconds
  69. * as perfect; there are no power gains for sleeping longer than this)
  70. *
  71. * For these two reasons we keep an array of 12 independent factors, that gets
  72. * indexed based on the magnitude of the expected duration as well as the
  73. * "is IO outstanding" property.
  74. *
  75. * Repeatable-interval-detector
  76. * ----------------------------
  77. * There are some cases where "next timer" is a completely unusable predictor:
  78. * Those cases where the interval is fixed, for example due to hardware
  79. * interrupt mitigation, but also due to fixed transfer rate devices such as
  80. * mice.
  81. * For this, we use a different predictor: We track the duration of the last 8
  82. * intervals and if the stand deviation of these 8 intervals is below a
  83. * threshold value, we use the average of these intervals as prediction.
  84. *
  85. * Limiting Performance Impact
  86. * ---------------------------
  87. * C states, especially those with large exit latencies, can have a real
  88. * noticeable impact on workloads, which is not acceptable for most sysadmins,
  89. * and in addition, less performance has a power price of its own.
  90. *
  91. * As a general rule of thumb, menu assumes that the following heuristic
  92. * holds:
  93. * The busier the system, the less impact of C states is acceptable
  94. *
  95. * This rule-of-thumb is implemented using a performance-multiplier:
  96. * If the exit latency times the performance multiplier is longer than
  97. * the predicted duration, the C state is not considered a candidate
  98. * for selection due to a too high performance impact. So the higher
  99. * this multiplier is, the longer we need to be idle to pick a deep C
  100. * state, and thus the less likely a busy CPU will hit such a deep
  101. * C state.
  102. *
  103. * Two factors are used in determing this multiplier:
  104. * a value of 10 is added for each point of "per cpu load average" we have.
  105. * a value of 5 points is added for each process that is waiting for
  106. * IO on this CPU.
  107. * (these values are experimentally determined)
  108. *
  109. * The load average factor gives a longer term (few seconds) input to the
  110. * decision, while the iowait value gives a cpu local instantanious input.
  111. * The iowait factor may look low, but realize that this is also already
  112. * represented in the system load average.
  113. *
  114. */
  115. struct menu_device {
  116. int last_state_idx;
  117. int needs_update;
  118. unsigned int next_timer_us;
  119. unsigned int predicted_us;
  120. unsigned int bucket;
  121. unsigned int correction_factor[BUCKETS];
  122. unsigned int intervals[INTERVALS];
  123. int interval_ptr;
  124. };
  125. #define LOAD_INT(x) ((x) >> FSHIFT)
  126. #define LOAD_FRAC(x) LOAD_INT(((x) & (FIXED_1-1)) * 100)
  127. static inline int get_loadavg(unsigned long load)
  128. {
  129. return LOAD_INT(load) * 10 + LOAD_FRAC(load) / 10;
  130. }
  131. static inline int which_bucket(unsigned int duration, unsigned long nr_iowaiters)
  132. {
  133. int bucket = 0;
  134. /*
  135. * We keep two groups of stats; one with no
  136. * IO pending, one without.
  137. * This allows us to calculate
  138. * E(duration)|iowait
  139. */
  140. if (nr_iowaiters)
  141. bucket = BUCKETS/2;
  142. if (duration < 10)
  143. return bucket;
  144. if (duration < 100)
  145. return bucket + 1;
  146. if (duration < 1000)
  147. return bucket + 2;
  148. if (duration < 10000)
  149. return bucket + 3;
  150. if (duration < 100000)
  151. return bucket + 4;
  152. return bucket + 5;
  153. }
  154. /*
  155. * Return a multiplier for the exit latency that is intended
  156. * to take performance requirements into account.
  157. * The more performance critical we estimate the system
  158. * to be, the higher this multiplier, and thus the higher
  159. * the barrier to go to an expensive C state.
  160. */
  161. static inline int performance_multiplier(unsigned long nr_iowaiters, unsigned long load)
  162. {
  163. int mult = 1;
  164. /* for higher loadavg, we are more reluctant */
  165. mult += 2 * get_loadavg(load);
  166. /* for IO wait tasks (per cpu!) we add 5x each */
  167. mult += 10 * nr_iowaiters;
  168. return mult;
  169. }
  170. static DEFINE_PER_CPU(struct menu_device, menu_devices);
  171. static void menu_update(struct cpuidle_driver *drv, struct cpuidle_device *dev);
  172. /*
  173. * Try detecting repeating patterns by keeping track of the last 8
  174. * intervals, and checking if the standard deviation of that set
  175. * of points is below a threshold. If it is... then use the
  176. * average of these 8 points as the estimated value.
  177. */
  178. static unsigned int get_typical_interval(struct menu_device *data)
  179. {
  180. int i, divisor;
  181. unsigned int max, thresh, avg;
  182. uint64_t sum, variance;
  183. thresh = UINT_MAX; /* Discard outliers above this value */
  184. again:
  185. /* First calculate the average of past intervals */
  186. max = 0;
  187. sum = 0;
  188. divisor = 0;
  189. for (i = 0; i < INTERVALS; i++) {
  190. unsigned int value = data->intervals[i];
  191. if (value <= thresh) {
  192. sum += value;
  193. divisor++;
  194. if (value > max)
  195. max = value;
  196. }
  197. }
  198. if (divisor == INTERVALS)
  199. avg = sum >> INTERVAL_SHIFT;
  200. else
  201. avg = div_u64(sum, divisor);
  202. /* Then try to determine variance */
  203. variance = 0;
  204. for (i = 0; i < INTERVALS; i++) {
  205. unsigned int value = data->intervals[i];
  206. if (value <= thresh) {
  207. int64_t diff = (int64_t)value - avg;
  208. variance += diff * diff;
  209. }
  210. }
  211. if (divisor == INTERVALS)
  212. variance >>= INTERVAL_SHIFT;
  213. else
  214. do_div(variance, divisor);
  215. /*
  216. * The typical interval is obtained when standard deviation is
  217. * small (stddev <= 20 us, variance <= 400 us^2) or standard
  218. * deviation is small compared to the average interval (avg >
  219. * 6*stddev, avg^2 > 36*variance). The average is smaller than
  220. * UINT_MAX aka U32_MAX, so computing its square does not
  221. * overflow a u64. We simply reject this candidate average if
  222. * the standard deviation is greater than 715 s (which is
  223. * rather unlikely).
  224. *
  225. * Use this result only if there is no timer to wake us up sooner.
  226. */
  227. if (likely(variance <= U64_MAX/36)) {
  228. if ((((u64)avg*avg > variance*36) && (divisor * 4 >= INTERVALS * 3))
  229. || variance <= 400) {
  230. return avg;
  231. }
  232. }
  233. /*
  234. * If we have outliers to the upside in our distribution, discard
  235. * those by setting the threshold to exclude these outliers, then
  236. * calculate the average and standard deviation again. Once we get
  237. * down to the bottom 3/4 of our samples, stop excluding samples.
  238. *
  239. * This can deal with workloads that have long pauses interspersed
  240. * with sporadic activity with a bunch of short pauses.
  241. */
  242. if ((divisor * 4) <= INTERVALS * 3)
  243. return UINT_MAX;
  244. thresh = max - 1;
  245. goto again;
  246. }
  247. /**
  248. * menu_select - selects the next idle state to enter
  249. * @drv: cpuidle driver containing state data
  250. * @dev: the CPU
  251. */
  252. static int menu_select(struct cpuidle_driver *drv, struct cpuidle_device *dev)
  253. {
  254. struct menu_device *data = this_cpu_ptr(&menu_devices);
  255. int latency_req = pm_qos_request(PM_QOS_CPU_DMA_LATENCY);
  256. int i;
  257. unsigned int interactivity_req;
  258. unsigned int expected_interval;
  259. unsigned long nr_iowaiters, cpu_load;
  260. if (data->needs_update) {
  261. menu_update(drv, dev);
  262. data->needs_update = 0;
  263. }
  264. /* Special case when user has set very strict latency requirement */
  265. if (unlikely(latency_req == 0))
  266. return 0;
  267. /* determine the expected residency time, round up */
  268. data->next_timer_us = ktime_to_us(tick_nohz_get_sleep_length());
  269. get_iowait_load(&nr_iowaiters, &cpu_load);
  270. data->bucket = which_bucket(data->next_timer_us, nr_iowaiters);
  271. /*
  272. * Force the result of multiplication to be 64 bits even if both
  273. * operands are 32 bits.
  274. * Make sure to round up for half microseconds.
  275. */
  276. data->predicted_us = DIV_ROUND_CLOSEST_ULL((uint64_t)data->next_timer_us *
  277. data->correction_factor[data->bucket],
  278. RESOLUTION * DECAY);
  279. expected_interval = get_typical_interval(data);
  280. expected_interval = min(expected_interval, data->next_timer_us);
  281. if (CPUIDLE_DRIVER_STATE_START > 0) {
  282. struct cpuidle_state *s = &drv->states[CPUIDLE_DRIVER_STATE_START];
  283. unsigned int polling_threshold;
  284. /*
  285. * We want to default to C1 (hlt), not to busy polling
  286. * unless the timer is happening really really soon, or
  287. * C1's exit latency exceeds the user configured limit.
  288. */
  289. polling_threshold = max_t(unsigned int, 20, s->target_residency);
  290. if (data->next_timer_us > polling_threshold &&
  291. latency_req > s->exit_latency && !s->disabled &&
  292. !dev->states_usage[CPUIDLE_DRIVER_STATE_START].disable)
  293. data->last_state_idx = CPUIDLE_DRIVER_STATE_START;
  294. else
  295. data->last_state_idx = CPUIDLE_DRIVER_STATE_START - 1;
  296. } else {
  297. data->last_state_idx = CPUIDLE_DRIVER_STATE_START;
  298. }
  299. /*
  300. * Use the lowest expected idle interval to pick the idle state.
  301. */
  302. data->predicted_us = min(data->predicted_us, expected_interval);
  303. /*
  304. * Use the performance multiplier and the user-configurable
  305. * latency_req to determine the maximum exit latency.
  306. */
  307. interactivity_req = data->predicted_us / performance_multiplier(nr_iowaiters, cpu_load);
  308. if (latency_req > interactivity_req)
  309. latency_req = interactivity_req;
  310. /*
  311. * Find the idle state with the lowest power while satisfying
  312. * our constraints.
  313. */
  314. for (i = data->last_state_idx + 1; i < drv->state_count; i++) {
  315. struct cpuidle_state *s = &drv->states[i];
  316. struct cpuidle_state_usage *su = &dev->states_usage[i];
  317. if (s->disabled || su->disable)
  318. continue;
  319. if (s->target_residency > data->predicted_us)
  320. continue;
  321. if (s->exit_latency > latency_req)
  322. continue;
  323. data->last_state_idx = i;
  324. }
  325. return data->last_state_idx;
  326. }
  327. /**
  328. * menu_reflect - records that data structures need update
  329. * @dev: the CPU
  330. * @index: the index of actual entered state
  331. *
  332. * NOTE: it's important to be fast here because this operation will add to
  333. * the overall exit latency.
  334. */
  335. static void menu_reflect(struct cpuidle_device *dev, int index)
  336. {
  337. struct menu_device *data = this_cpu_ptr(&menu_devices);
  338. data->last_state_idx = index;
  339. data->needs_update = 1;
  340. }
  341. /**
  342. * menu_update - attempts to guess what happened after entry
  343. * @drv: cpuidle driver containing state data
  344. * @dev: the CPU
  345. */
  346. static void menu_update(struct cpuidle_driver *drv, struct cpuidle_device *dev)
  347. {
  348. struct menu_device *data = this_cpu_ptr(&menu_devices);
  349. int last_idx = data->last_state_idx;
  350. struct cpuidle_state *target = &drv->states[last_idx];
  351. unsigned int measured_us;
  352. unsigned int new_factor;
  353. /*
  354. * Try to figure out how much time passed between entry to low
  355. * power state and occurrence of the wakeup event.
  356. *
  357. * If the entered idle state didn't support residency measurements,
  358. * we use them anyway if they are short, and if long,
  359. * truncate to the whole expected time.
  360. *
  361. * Any measured amount of time will include the exit latency.
  362. * Since we are interested in when the wakeup begun, not when it
  363. * was completed, we must subtract the exit latency. However, if
  364. * the measured amount of time is less than the exit latency,
  365. * assume the state was never reached and the exit latency is 0.
  366. */
  367. /* measured value */
  368. measured_us = cpuidle_get_last_residency(dev);
  369. /* Deduct exit latency */
  370. if (measured_us > 2 * target->exit_latency)
  371. measured_us -= target->exit_latency;
  372. else
  373. measured_us /= 2;
  374. /* Make sure our coefficients do not exceed unity */
  375. if (measured_us > data->next_timer_us)
  376. measured_us = data->next_timer_us;
  377. /* Update our correction ratio */
  378. new_factor = data->correction_factor[data->bucket];
  379. new_factor -= new_factor / DECAY;
  380. if (data->next_timer_us > 0 && measured_us < MAX_INTERESTING)
  381. new_factor += RESOLUTION * measured_us / data->next_timer_us;
  382. else
  383. /*
  384. * we were idle so long that we count it as a perfect
  385. * prediction
  386. */
  387. new_factor += RESOLUTION;
  388. /*
  389. * We don't want 0 as factor; we always want at least
  390. * a tiny bit of estimated time. Fortunately, due to rounding,
  391. * new_factor will stay nonzero regardless of measured_us values
  392. * and the compiler can eliminate this test as long as DECAY > 1.
  393. */
  394. if (DECAY == 1 && unlikely(new_factor == 0))
  395. new_factor = 1;
  396. data->correction_factor[data->bucket] = new_factor;
  397. /* update the repeating-pattern data */
  398. data->intervals[data->interval_ptr++] = measured_us;
  399. if (data->interval_ptr >= INTERVALS)
  400. data->interval_ptr = 0;
  401. }
  402. /**
  403. * menu_enable_device - scans a CPU's states and does setup
  404. * @drv: cpuidle driver
  405. * @dev: the CPU
  406. */
  407. static int menu_enable_device(struct cpuidle_driver *drv,
  408. struct cpuidle_device *dev)
  409. {
  410. struct menu_device *data = &per_cpu(menu_devices, dev->cpu);
  411. int i;
  412. memset(data, 0, sizeof(struct menu_device));
  413. /*
  414. * if the correction factor is 0 (eg first time init or cpu hotplug
  415. * etc), we actually want to start out with a unity factor.
  416. */
  417. for(i = 0; i < BUCKETS; i++)
  418. data->correction_factor[i] = RESOLUTION * DECAY;
  419. return 0;
  420. }
  421. static struct cpuidle_governor menu_governor = {
  422. .name = "menu",
  423. .rating = 20,
  424. .enable = menu_enable_device,
  425. .select = menu_select,
  426. .reflect = menu_reflect,
  427. };
  428. /**
  429. * init_menu - initializes the governor
  430. */
  431. static int __init init_menu(void)
  432. {
  433. return cpuidle_register_governor(&menu_governor);
  434. }
  435. postcore_initcall(init_menu);