menu.c 16 KB

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