menu.c 14 KB

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