menu.c 12 KB

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