menu.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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/time.h>
  15. #include <linux/ktime.h>
  16. #include <linux/hrtimer.h>
  17. #include <linux/tick.h>
  18. #include <linux/sched.h>
  19. #include <linux/sched/loadavg.h>
  20. #include <linux/sched/stat.h>
  21. #include <linux/math64.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 INTERVAL_SHIFT 3
  33. #define INTERVALS (1UL << INTERVAL_SHIFT)
  34. #define RESOLUTION 1024
  35. #define DECAY 8
  36. #define MAX_INTERESTING 50000
  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. int tick_wakeup;
  120. unsigned int next_timer_us;
  121. unsigned int predicted_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 inline int get_loadavg(unsigned long load)
  130. {
  131. return LOAD_INT(load) * 10 + LOAD_FRAC(load) / 10;
  132. }
  133. static inline int which_bucket(unsigned int duration, unsigned long nr_iowaiters)
  134. {
  135. int bucket = 0;
  136. /*
  137. * We keep two groups of stats; one with no
  138. * IO pending, one without.
  139. * This allows us to calculate
  140. * E(duration)|iowait
  141. */
  142. if (nr_iowaiters)
  143. bucket = BUCKETS/2;
  144. if (duration < 10)
  145. return bucket;
  146. if (duration < 100)
  147. return bucket + 1;
  148. if (duration < 1000)
  149. return bucket + 2;
  150. if (duration < 10000)
  151. return bucket + 3;
  152. if (duration < 100000)
  153. return bucket + 4;
  154. return bucket + 5;
  155. }
  156. /*
  157. * Return a multiplier for the exit latency that is intended
  158. * to take performance requirements into account.
  159. * The more performance critical we estimate the system
  160. * to be, the higher this multiplier, and thus the higher
  161. * the barrier to go to an expensive C state.
  162. */
  163. static inline int performance_multiplier(unsigned long nr_iowaiters, unsigned long load)
  164. {
  165. int mult = 1;
  166. /* for higher loadavg, we are more reluctant */
  167. mult += 2 * get_loadavg(load);
  168. /* for IO wait tasks (per cpu!) we add 5x each */
  169. mult += 10 * nr_iowaiters;
  170. return mult;
  171. }
  172. static DEFINE_PER_CPU(struct menu_device, menu_devices);
  173. static void menu_update(struct cpuidle_driver *drv, struct cpuidle_device *dev);
  174. /*
  175. * Try detecting repeating patterns by keeping track of the last 8
  176. * intervals, and checking if the standard deviation of that set
  177. * of points is below a threshold. If it is... then use the
  178. * average of these 8 points as the estimated value.
  179. */
  180. static unsigned int get_typical_interval(struct menu_device *data)
  181. {
  182. int i, divisor;
  183. unsigned int max, thresh, avg;
  184. uint64_t sum, variance;
  185. thresh = UINT_MAX; /* Discard outliers above this value */
  186. again:
  187. /* First calculate the average of past intervals */
  188. max = 0;
  189. sum = 0;
  190. divisor = 0;
  191. for (i = 0; i < INTERVALS; i++) {
  192. unsigned int value = data->intervals[i];
  193. if (value <= thresh) {
  194. sum += value;
  195. divisor++;
  196. if (value > max)
  197. max = value;
  198. }
  199. }
  200. if (divisor == INTERVALS)
  201. avg = sum >> INTERVAL_SHIFT;
  202. else
  203. avg = div_u64(sum, divisor);
  204. /* Then try to determine variance */
  205. variance = 0;
  206. for (i = 0; i < INTERVALS; i++) {
  207. unsigned int value = data->intervals[i];
  208. if (value <= thresh) {
  209. int64_t diff = (int64_t)value - avg;
  210. variance += diff * diff;
  211. }
  212. }
  213. if (divisor == INTERVALS)
  214. variance >>= INTERVAL_SHIFT;
  215. else
  216. do_div(variance, divisor);
  217. /*
  218. * The typical interval is obtained when standard deviation is
  219. * small (stddev <= 20 us, variance <= 400 us^2) or standard
  220. * deviation is small compared to the average interval (avg >
  221. * 6*stddev, avg^2 > 36*variance). The average is smaller than
  222. * UINT_MAX aka U32_MAX, so computing its square does not
  223. * overflow a u64. We simply reject this candidate average if
  224. * the standard deviation is greater than 715 s (which is
  225. * rather unlikely).
  226. *
  227. * Use this result only if there is no timer to wake us up sooner.
  228. */
  229. if (likely(variance <= U64_MAX/36)) {
  230. if ((((u64)avg*avg > variance*36) && (divisor * 4 >= INTERVALS * 3))
  231. || variance <= 400) {
  232. return avg;
  233. }
  234. }
  235. /*
  236. * If we have outliers to the upside in our distribution, discard
  237. * those by setting the threshold to exclude these outliers, then
  238. * calculate the average and standard deviation again. Once we get
  239. * down to the bottom 3/4 of our samples, stop excluding samples.
  240. *
  241. * This can deal with workloads that have long pauses interspersed
  242. * with sporadic activity with a bunch of short pauses.
  243. */
  244. if ((divisor * 4) <= INTERVALS * 3)
  245. return UINT_MAX;
  246. thresh = max - 1;
  247. goto again;
  248. }
  249. /**
  250. * menu_select - selects the next idle state to enter
  251. * @drv: cpuidle driver containing state data
  252. * @dev: the CPU
  253. * @stop_tick: indication on whether or not to stop the tick
  254. */
  255. static int menu_select(struct cpuidle_driver *drv, struct cpuidle_device *dev,
  256. bool *stop_tick)
  257. {
  258. struct menu_device *data = this_cpu_ptr(&menu_devices);
  259. int latency_req = cpuidle_governor_latency_req(dev->cpu);
  260. int i;
  261. int first_idx;
  262. int idx;
  263. unsigned int interactivity_req;
  264. unsigned int expected_interval;
  265. unsigned long nr_iowaiters, cpu_load;
  266. ktime_t delta_next;
  267. if (data->needs_update) {
  268. menu_update(drv, dev);
  269. data->needs_update = 0;
  270. }
  271. /* Special case when user has set very strict latency requirement */
  272. if (unlikely(latency_req == 0)) {
  273. *stop_tick = false;
  274. return 0;
  275. }
  276. /* determine the expected residency time, round up */
  277. data->next_timer_us = ktime_to_us(tick_nohz_get_sleep_length(&delta_next));
  278. get_iowait_load(&nr_iowaiters, &cpu_load);
  279. data->bucket = which_bucket(data->next_timer_us, nr_iowaiters);
  280. /*
  281. * Force the result of multiplication to be 64 bits even if both
  282. * operands are 32 bits.
  283. * Make sure to round up for half microseconds.
  284. */
  285. data->predicted_us = DIV_ROUND_CLOSEST_ULL((uint64_t)data->next_timer_us *
  286. data->correction_factor[data->bucket],
  287. RESOLUTION * DECAY);
  288. expected_interval = get_typical_interval(data);
  289. expected_interval = min(expected_interval, data->next_timer_us);
  290. first_idx = 0;
  291. if (drv->states[0].flags & CPUIDLE_FLAG_POLLING) {
  292. struct cpuidle_state *s = &drv->states[1];
  293. unsigned int polling_threshold;
  294. /*
  295. * Default to a physical idle state, not to busy polling, unless
  296. * a timer is going to trigger really really soon.
  297. */
  298. polling_threshold = max_t(unsigned int, 20, s->target_residency);
  299. if (data->next_timer_us > polling_threshold &&
  300. latency_req > s->exit_latency && !s->disabled &&
  301. !dev->states_usage[1].disable)
  302. first_idx = 1;
  303. }
  304. /*
  305. * Use the lowest expected idle interval to pick the idle state.
  306. */
  307. data->predicted_us = min(data->predicted_us, expected_interval);
  308. if (tick_nohz_tick_stopped()) {
  309. /*
  310. * If the tick is already stopped, the cost of possible short
  311. * idle duration misprediction is much higher, because the CPU
  312. * may be stuck in a shallow idle state for a long time as a
  313. * result of it. In that case say we might mispredict and use
  314. * the known time till the closest timer event for the idle
  315. * state selection.
  316. */
  317. if (data->predicted_us < TICK_USEC)
  318. data->predicted_us = ktime_to_us(delta_next);
  319. } else {
  320. /*
  321. * Use the performance multiplier and the user-configurable
  322. * latency_req to determine the maximum exit latency.
  323. */
  324. interactivity_req = data->predicted_us / performance_multiplier(nr_iowaiters, cpu_load);
  325. if (latency_req > interactivity_req)
  326. latency_req = interactivity_req;
  327. }
  328. expected_interval = data->predicted_us;
  329. /*
  330. * Find the idle state with the lowest power while satisfying
  331. * our constraints.
  332. */
  333. idx = -1;
  334. for (i = first_idx; i < drv->state_count; i++) {
  335. struct cpuidle_state *s = &drv->states[i];
  336. struct cpuidle_state_usage *su = &dev->states_usage[i];
  337. if (s->disabled || su->disable)
  338. continue;
  339. if (idx == -1)
  340. idx = i; /* first enabled state */
  341. if (s->target_residency > data->predicted_us) {
  342. if (data->predicted_us < TICK_USEC)
  343. break;
  344. if (!tick_nohz_tick_stopped()) {
  345. /*
  346. * If the state selected so far is shallow,
  347. * waking up early won't hurt, so retain the
  348. * tick in that case and let the governor run
  349. * again in the next iteration of the loop.
  350. */
  351. expected_interval = drv->states[idx].target_residency;
  352. break;
  353. }
  354. /*
  355. * If the state selected so far is shallow and this
  356. * state's target residency matches the time till the
  357. * closest timer event, select this one to avoid getting
  358. * stuck in the shallow one for too long.
  359. */
  360. if (drv->states[idx].target_residency < TICK_USEC &&
  361. s->target_residency <= ktime_to_us(delta_next))
  362. idx = i;
  363. goto out;
  364. }
  365. if (s->exit_latency > latency_req) {
  366. /*
  367. * If we break out of the loop for latency reasons, use
  368. * the target residency of the selected state as the
  369. * expected idle duration so that the tick is retained
  370. * as long as that target residency is low enough.
  371. */
  372. expected_interval = drv->states[idx].target_residency;
  373. break;
  374. }
  375. idx = i;
  376. }
  377. if (idx == -1)
  378. idx = 0; /* No states enabled. Must use 0. */
  379. /*
  380. * Don't stop the tick if the selected state is a polling one or if the
  381. * expected idle duration is shorter than the tick period length.
  382. */
  383. if (((drv->states[idx].flags & CPUIDLE_FLAG_POLLING) ||
  384. expected_interval < TICK_USEC) && !tick_nohz_tick_stopped()) {
  385. unsigned int delta_next_us = ktime_to_us(delta_next);
  386. *stop_tick = false;
  387. if (idx > 0 && drv->states[idx].target_residency > delta_next_us) {
  388. /*
  389. * The tick is not going to be stopped and the target
  390. * residency of the state to be returned is not within
  391. * the time until the next timer event including the
  392. * tick, so try to correct that.
  393. */
  394. for (i = idx - 1; i >= 0; i--) {
  395. if (drv->states[i].disabled ||
  396. dev->states_usage[i].disable)
  397. continue;
  398. idx = i;
  399. if (drv->states[i].target_residency <= delta_next_us)
  400. break;
  401. }
  402. }
  403. }
  404. out:
  405. data->last_state_idx = idx;
  406. return data->last_state_idx;
  407. }
  408. /**
  409. * menu_reflect - records that data structures need update
  410. * @dev: the CPU
  411. * @index: the index of actual entered state
  412. *
  413. * NOTE: it's important to be fast here because this operation will add to
  414. * the overall exit latency.
  415. */
  416. static void menu_reflect(struct cpuidle_device *dev, int index)
  417. {
  418. struct menu_device *data = this_cpu_ptr(&menu_devices);
  419. data->last_state_idx = index;
  420. data->needs_update = 1;
  421. data->tick_wakeup = tick_nohz_idle_got_tick();
  422. }
  423. /**
  424. * menu_update - attempts to guess what happened after entry
  425. * @drv: cpuidle driver containing state data
  426. * @dev: the CPU
  427. */
  428. static void menu_update(struct cpuidle_driver *drv, struct cpuidle_device *dev)
  429. {
  430. struct menu_device *data = this_cpu_ptr(&menu_devices);
  431. int last_idx = data->last_state_idx;
  432. struct cpuidle_state *target = &drv->states[last_idx];
  433. unsigned int measured_us;
  434. unsigned int new_factor;
  435. /*
  436. * Try to figure out how much time passed between entry to low
  437. * power state and occurrence of the wakeup event.
  438. *
  439. * If the entered idle state didn't support residency measurements,
  440. * we use them anyway if they are short, and if long,
  441. * truncate to the whole expected time.
  442. *
  443. * Any measured amount of time will include the exit latency.
  444. * Since we are interested in when the wakeup begun, not when it
  445. * was completed, we must subtract the exit latency. However, if
  446. * the measured amount of time is less than the exit latency,
  447. * assume the state was never reached and the exit latency is 0.
  448. */
  449. if (data->tick_wakeup && data->next_timer_us > TICK_USEC) {
  450. /*
  451. * The nohz code said that there wouldn't be any events within
  452. * the tick boundary (if the tick was stopped), but the idle
  453. * duration predictor had a differing opinion. Since the CPU
  454. * was woken up by a tick (that wasn't stopped after all), the
  455. * predictor was not quite right, so assume that the CPU could
  456. * have been idle long (but not forever) to help the idle
  457. * duration predictor do a better job next time.
  458. */
  459. measured_us = 9 * MAX_INTERESTING / 10;
  460. } else if ((drv->states[last_idx].flags & CPUIDLE_FLAG_POLLING) &&
  461. dev->poll_time_limit) {
  462. /*
  463. * The CPU exited the "polling" state due to a time limit, so
  464. * the idle duration prediction leading to the selection of that
  465. * state was inaccurate. If a better prediction had been made,
  466. * the CPU might have been woken up from idle by the next timer.
  467. * Assume that to be the case.
  468. */
  469. measured_us = data->next_timer_us;
  470. } else {
  471. /* measured value */
  472. measured_us = cpuidle_get_last_residency(dev);
  473. /* Deduct exit latency */
  474. if (measured_us > 2 * target->exit_latency)
  475. measured_us -= target->exit_latency;
  476. else
  477. measured_us /= 2;
  478. }
  479. /* Make sure our coefficients do not exceed unity */
  480. if (measured_us > data->next_timer_us)
  481. measured_us = data->next_timer_us;
  482. /* Update our correction ratio */
  483. new_factor = data->correction_factor[data->bucket];
  484. new_factor -= new_factor / DECAY;
  485. if (data->next_timer_us > 0 && measured_us < MAX_INTERESTING)
  486. new_factor += RESOLUTION * measured_us / data->next_timer_us;
  487. else
  488. /*
  489. * we were idle so long that we count it as a perfect
  490. * prediction
  491. */
  492. new_factor += RESOLUTION;
  493. /*
  494. * We don't want 0 as factor; we always want at least
  495. * a tiny bit of estimated time. Fortunately, due to rounding,
  496. * new_factor will stay nonzero regardless of measured_us values
  497. * and the compiler can eliminate this test as long as DECAY > 1.
  498. */
  499. if (DECAY == 1 && unlikely(new_factor == 0))
  500. new_factor = 1;
  501. data->correction_factor[data->bucket] = new_factor;
  502. /* update the repeating-pattern data */
  503. data->intervals[data->interval_ptr++] = measured_us;
  504. if (data->interval_ptr >= INTERVALS)
  505. data->interval_ptr = 0;
  506. }
  507. /**
  508. * menu_enable_device - scans a CPU's states and does setup
  509. * @drv: cpuidle driver
  510. * @dev: the CPU
  511. */
  512. static int menu_enable_device(struct cpuidle_driver *drv,
  513. struct cpuidle_device *dev)
  514. {
  515. struct menu_device *data = &per_cpu(menu_devices, dev->cpu);
  516. int i;
  517. memset(data, 0, sizeof(struct menu_device));
  518. /*
  519. * if the correction factor is 0 (eg first time init or cpu hotplug
  520. * etc), we actually want to start out with a unity factor.
  521. */
  522. for(i = 0; i < BUCKETS; i++)
  523. data->correction_factor[i] = RESOLUTION * DECAY;
  524. return 0;
  525. }
  526. static struct cpuidle_governor menu_governor = {
  527. .name = "menu",
  528. .rating = 20,
  529. .enable = menu_enable_device,
  530. .select = menu_select,
  531. .reflect = menu_reflect,
  532. };
  533. /**
  534. * init_menu - initializes the governor
  535. */
  536. static int __init init_menu(void)
  537. {
  538. return cpuidle_register_governor(&menu_governor);
  539. }
  540. postcore_initcall(init_menu);