menu.c 13 KB

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