menu.c 16 KB

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