menu.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * menu.c - the menu idle governor
  4. *
  5. * Copyright (C) 2006-2007 Adam Belay <abelay@novell.com>
  6. * Copyright (C) 2009 Intel Corporation
  7. * Author:
  8. * Arjan van de Ven <arjan@linux.intel.com>
  9. */
  10. #include <linux/kernel.h>
  11. #include <linux/cpuidle.h>
  12. #include <linux/time.h>
  13. #include <linux/ktime.h>
  14. #include <linux/hrtimer.h>
  15. #include <linux/tick.h>
  16. #include <linux/sched/stat.h>
  17. #include <linux/math64.h>
  18. #include "gov.h"
  19. #define BUCKETS 6
  20. #define INTERVAL_SHIFT 3
  21. #define INTERVALS (1UL << INTERVAL_SHIFT)
  22. #define RESOLUTION 1024
  23. #define DECAY 8
  24. #define MAX_INTERESTING (50000 * NSEC_PER_USEC)
  25. /*
  26. * Concepts and ideas behind the menu governor
  27. *
  28. * For the menu governor, there are 2 decision factors for picking a C
  29. * state:
  30. * 1) Energy break even point
  31. * 2) Latency tolerance (from pmqos infrastructure)
  32. * These two factors are treated independently.
  33. *
  34. * Energy break even point
  35. * -----------------------
  36. * C state entry and exit have an energy cost, and a certain amount of time in
  37. * the C state is required to actually break even on this cost. CPUIDLE
  38. * provides us this duration in the "target_residency" field. So all that we
  39. * need is a good prediction of how long we'll be idle. Like the traditional
  40. * menu governor, we start with the actual known "next timer event" time.
  41. *
  42. * Since there are other source of wakeups (interrupts for example) than
  43. * the next timer event, this estimation is rather optimistic. To get a
  44. * more realistic estimate, a correction factor is applied to the estimate,
  45. * that is based on historic behavior. For example, if in the past the actual
  46. * duration always was 50% of the next timer tick, the correction factor will
  47. * be 0.5.
  48. *
  49. * menu uses a running average for this correction factor, however it uses a
  50. * set of factors, not just a single factor. This stems from the realization
  51. * that the ratio is dependent on the order of magnitude of the expected
  52. * duration; if we expect 500 milliseconds of idle time the likelihood of
  53. * getting an interrupt very early is much higher than if we expect 50 micro
  54. * seconds of idle time. A second independent factor that has big impact on
  55. * the actual factor is if there is (disk) IO outstanding or not.
  56. * (as a special twist, we consider every sleep longer than 50 milliseconds
  57. * as perfect; there are no power gains for sleeping longer than this)
  58. *
  59. * For these two reasons we keep an array of 12 independent factors, that gets
  60. * indexed based on the magnitude of the expected duration as well as the
  61. * "is IO outstanding" property.
  62. *
  63. * Repeatable-interval-detector
  64. * ----------------------------
  65. * There are some cases where "next timer" is a completely unusable predictor:
  66. * Those cases where the interval is fixed, for example due to hardware
  67. * interrupt mitigation, but also due to fixed transfer rate devices such as
  68. * mice.
  69. * For this, we use a different predictor: We track the duration of the last 8
  70. * intervals and if the stand deviation of these 8 intervals is below a
  71. * threshold value, we use the average of these intervals as prediction.
  72. *
  73. */
  74. struct menu_device {
  75. int needs_update;
  76. int tick_wakeup;
  77. u64 next_timer_ns;
  78. unsigned int bucket;
  79. unsigned int correction_factor[BUCKETS];
  80. unsigned int intervals[INTERVALS];
  81. int interval_ptr;
  82. };
  83. static inline int which_bucket(u64 duration_ns)
  84. {
  85. int bucket = 0;
  86. if (duration_ns < 10ULL * NSEC_PER_USEC)
  87. return bucket;
  88. if (duration_ns < 100ULL * NSEC_PER_USEC)
  89. return bucket + 1;
  90. if (duration_ns < 1000ULL * NSEC_PER_USEC)
  91. return bucket + 2;
  92. if (duration_ns < 10000ULL * NSEC_PER_USEC)
  93. return bucket + 3;
  94. if (duration_ns < 100000ULL * NSEC_PER_USEC)
  95. return bucket + 4;
  96. return bucket + 5;
  97. }
  98. static DEFINE_PER_CPU(struct menu_device, menu_devices);
  99. static void menu_update_intervals(struct menu_device *data, unsigned int interval_us)
  100. {
  101. /* Update the repeating-pattern data. */
  102. data->intervals[data->interval_ptr++] = interval_us;
  103. if (data->interval_ptr >= INTERVALS)
  104. data->interval_ptr = 0;
  105. }
  106. static void menu_update(struct cpuidle_driver *drv, struct cpuidle_device *dev);
  107. /*
  108. * Try detecting repeating patterns by keeping track of the last 8
  109. * intervals, and checking if the standard deviation of that set
  110. * of points is below a threshold. If it is... then use the
  111. * average of these 8 points as the estimated value.
  112. */
  113. static unsigned int get_typical_interval(struct menu_device *data)
  114. {
  115. int i, divisor;
  116. unsigned int min, max, thresh, avg;
  117. uint64_t sum, variance;
  118. thresh = INT_MAX; /* Discard outliers above this value */
  119. again:
  120. /* First calculate the average of past intervals */
  121. min = UINT_MAX;
  122. max = 0;
  123. sum = 0;
  124. divisor = 0;
  125. for (i = 0; i < INTERVALS; i++) {
  126. unsigned int value = data->intervals[i];
  127. if (value <= thresh) {
  128. sum += value;
  129. divisor++;
  130. if (value > max)
  131. max = value;
  132. if (value < min)
  133. min = value;
  134. }
  135. }
  136. if (!max)
  137. return UINT_MAX;
  138. if (divisor == INTERVALS)
  139. avg = sum >> INTERVAL_SHIFT;
  140. else
  141. avg = div_u64(sum, divisor);
  142. /* Then try to determine variance */
  143. variance = 0;
  144. for (i = 0; i < INTERVALS; i++) {
  145. unsigned int value = data->intervals[i];
  146. if (value <= thresh) {
  147. int64_t diff = (int64_t)value - avg;
  148. variance += diff * diff;
  149. }
  150. }
  151. if (divisor == INTERVALS)
  152. variance >>= INTERVAL_SHIFT;
  153. else
  154. do_div(variance, divisor);
  155. /*
  156. * The typical interval is obtained when standard deviation is
  157. * small (stddev <= 20 us, variance <= 400 us^2) or standard
  158. * deviation is small compared to the average interval (avg >
  159. * 6*stddev, avg^2 > 36*variance). The average is smaller than
  160. * UINT_MAX aka U32_MAX, so computing its square does not
  161. * overflow a u64. We simply reject this candidate average if
  162. * the standard deviation is greater than 715 s (which is
  163. * rather unlikely).
  164. *
  165. * Use this result only if there is no timer to wake us up sooner.
  166. */
  167. if (likely(variance <= U64_MAX/36)) {
  168. if ((((u64)avg*avg > variance*36) && (divisor * 4 >= INTERVALS * 3))
  169. || variance <= 400) {
  170. return avg;
  171. }
  172. }
  173. /*
  174. * If we have outliers to the upside in our distribution, discard
  175. * those by setting the threshold to exclude these outliers, then
  176. * calculate the average and standard deviation again. Once we get
  177. * down to the bottom 3/4 of our samples, stop excluding samples.
  178. *
  179. * This can deal with workloads that have long pauses interspersed
  180. * with sporadic activity with a bunch of short pauses.
  181. *
  182. * However, if the number of remaining samples is too small to exclude
  183. * any more outliers, allow the deepest available idle state to be
  184. * selected because there are systems where the time spent by CPUs in
  185. * deep idle states is correlated to the maximum frequency the CPUs
  186. * can get to. On those systems, shallow idle states should be avoided
  187. * unless there is a clear indication that the given CPU is most likley
  188. * going to be woken up shortly.
  189. */
  190. if (divisor * 4 <= INTERVALS * 3)
  191. return UINT_MAX;
  192. thresh = max - 1;
  193. goto again;
  194. }
  195. /**
  196. * menu_select - selects the next idle state to enter
  197. * @drv: cpuidle driver containing state data
  198. * @dev: the CPU
  199. * @stop_tick: indication on whether or not to stop the tick
  200. */
  201. static int menu_select(struct cpuidle_driver *drv, struct cpuidle_device *dev,
  202. bool *stop_tick)
  203. {
  204. struct menu_device *data = this_cpu_ptr(&menu_devices);
  205. s64 latency_req = cpuidle_governor_latency_req(dev->cpu);
  206. u64 predicted_ns;
  207. ktime_t delta, delta_tick;
  208. int i, idx;
  209. if (data->needs_update) {
  210. menu_update(drv, dev);
  211. data->needs_update = 0;
  212. } else if (!dev->last_residency_ns) {
  213. /*
  214. * This happens when the driver rejects the previously selected
  215. * idle state and returns an error, so update the recent
  216. * intervals table to prevent invalid information from being
  217. * used going forward.
  218. */
  219. menu_update_intervals(data, UINT_MAX);
  220. }
  221. /* Find the shortest expected idle interval. */
  222. predicted_ns = get_typical_interval(data) * NSEC_PER_USEC;
  223. if (predicted_ns > RESIDENCY_THRESHOLD_NS) {
  224. unsigned int timer_us;
  225. /* Determine the time till the closest timer. */
  226. delta = tick_nohz_get_sleep_length(&delta_tick);
  227. if (unlikely(delta < 0)) {
  228. delta = 0;
  229. delta_tick = 0;
  230. }
  231. data->next_timer_ns = delta;
  232. data->bucket = which_bucket(data->next_timer_ns);
  233. /* Round up the result for half microseconds. */
  234. timer_us = div_u64((RESOLUTION * DECAY * NSEC_PER_USEC) / 2 +
  235. data->next_timer_ns *
  236. data->correction_factor[data->bucket],
  237. RESOLUTION * DECAY * NSEC_PER_USEC);
  238. /* Use the lowest expected idle interval to pick the idle state. */
  239. predicted_ns = min((u64)timer_us * NSEC_PER_USEC, predicted_ns);
  240. } else {
  241. /*
  242. * Because the next timer event is not going to be determined
  243. * in this case, assume that without the tick the closest timer
  244. * will be in distant future and that the closest tick will occur
  245. * after 1/2 of the tick period.
  246. */
  247. data->next_timer_ns = KTIME_MAX;
  248. delta_tick = TICK_NSEC / 2;
  249. data->bucket = which_bucket(KTIME_MAX);
  250. }
  251. if (unlikely(drv->state_count <= 1 || latency_req == 0) ||
  252. ((data->next_timer_ns < drv->states[1].target_residency_ns ||
  253. latency_req < drv->states[1].exit_latency_ns) &&
  254. !dev->states_usage[0].disable)) {
  255. /*
  256. * In this case state[0] will be used no matter what, so return
  257. * it right away and keep the tick running if state[0] is a
  258. * polling one.
  259. */
  260. *stop_tick = !(drv->states[0].flags & CPUIDLE_FLAG_POLLING);
  261. return 0;
  262. }
  263. /*
  264. * If the tick is already stopped, the cost of possible short idle
  265. * duration misprediction is much higher, because the CPU may be stuck
  266. * in a shallow idle state for a long time as a result of it. In that
  267. * case, say we might mispredict and use the known time till the closest
  268. * timer event for the idle state selection.
  269. */
  270. if (tick_nohz_tick_stopped() && predicted_ns < TICK_NSEC)
  271. predicted_ns = data->next_timer_ns;
  272. /*
  273. * Find the idle state with the lowest power while satisfying
  274. * our constraints.
  275. */
  276. idx = -1;
  277. for (i = 0; i < drv->state_count; i++) {
  278. struct cpuidle_state *s = &drv->states[i];
  279. if (dev->states_usage[i].disable)
  280. continue;
  281. if (idx == -1)
  282. idx = i; /* first enabled state */
  283. if (s->exit_latency_ns > latency_req)
  284. break;
  285. if (s->target_residency_ns > predicted_ns) {
  286. /*
  287. * Use a physical idle state, not busy polling, unless
  288. * a timer is going to trigger soon enough.
  289. */
  290. if ((drv->states[idx].flags & CPUIDLE_FLAG_POLLING) &&
  291. s->target_residency_ns <= data->next_timer_ns) {
  292. predicted_ns = s->target_residency_ns;
  293. idx = i;
  294. break;
  295. }
  296. if (predicted_ns < TICK_NSEC)
  297. break;
  298. if (!tick_nohz_tick_stopped()) {
  299. /*
  300. * If the state selected so far is shallow,
  301. * waking up early won't hurt, so retain the
  302. * tick in that case and let the governor run
  303. * again in the next iteration of the loop.
  304. */
  305. predicted_ns = drv->states[idx].target_residency_ns;
  306. break;
  307. }
  308. /*
  309. * If the state selected so far is shallow and this
  310. * state's target residency matches the time till the
  311. * closest timer event, select this one to avoid getting
  312. * stuck in the shallow one for too long.
  313. */
  314. if (drv->states[idx].target_residency_ns < TICK_NSEC &&
  315. s->target_residency_ns <= delta_tick)
  316. idx = i;
  317. return idx;
  318. }
  319. idx = i;
  320. }
  321. if (idx == -1)
  322. idx = 0; /* No states enabled. Must use 0. */
  323. /*
  324. * Don't stop the tick if the selected state is a polling one or if the
  325. * expected idle duration is shorter than the tick period length.
  326. */
  327. if (((drv->states[idx].flags & CPUIDLE_FLAG_POLLING) ||
  328. predicted_ns < TICK_NSEC) && !tick_nohz_tick_stopped()) {
  329. *stop_tick = false;
  330. if (idx > 0 && drv->states[idx].target_residency_ns > delta_tick) {
  331. /*
  332. * The tick is not going to be stopped and the target
  333. * residency of the state to be returned is not within
  334. * the time until the next timer event including the
  335. * tick, so try to correct that.
  336. */
  337. for (i = idx - 1; i >= 0; i--) {
  338. if (dev->states_usage[i].disable)
  339. continue;
  340. idx = i;
  341. if (drv->states[i].target_residency_ns <= delta_tick)
  342. break;
  343. }
  344. }
  345. }
  346. return idx;
  347. }
  348. /**
  349. * menu_reflect - records that data structures need update
  350. * @dev: the CPU
  351. * @index: the index of actual entered state
  352. *
  353. * NOTE: it's important to be fast here because this operation will add to
  354. * the overall exit latency.
  355. */
  356. static void menu_reflect(struct cpuidle_device *dev, int index)
  357. {
  358. struct menu_device *data = this_cpu_ptr(&menu_devices);
  359. dev->last_state_idx = index;
  360. data->needs_update = 1;
  361. data->tick_wakeup = tick_nohz_idle_got_tick();
  362. }
  363. /**
  364. * menu_update - attempts to guess what happened after entry
  365. * @drv: cpuidle driver containing state data
  366. * @dev: the CPU
  367. */
  368. static void menu_update(struct cpuidle_driver *drv, struct cpuidle_device *dev)
  369. {
  370. struct menu_device *data = this_cpu_ptr(&menu_devices);
  371. int last_idx = dev->last_state_idx;
  372. struct cpuidle_state *target = &drv->states[last_idx];
  373. u64 measured_ns;
  374. unsigned int new_factor;
  375. /*
  376. * Try to figure out how much time passed between entry to low
  377. * power state and occurrence of the wakeup event.
  378. *
  379. * If the entered idle state didn't support residency measurements,
  380. * we use them anyway if they are short, and if long,
  381. * truncate to the whole expected time.
  382. *
  383. * Any measured amount of time will include the exit latency.
  384. * Since we are interested in when the wakeup begun, not when it
  385. * was completed, we must subtract the exit latency. However, if
  386. * the measured amount of time is less than the exit latency,
  387. * assume the state was never reached and the exit latency is 0.
  388. */
  389. if (data->tick_wakeup && data->next_timer_ns > TICK_NSEC) {
  390. /*
  391. * The nohz code said that there wouldn't be any events within
  392. * the tick boundary (if the tick was stopped), but the idle
  393. * duration predictor had a differing opinion. Since the CPU
  394. * was woken up by a tick (that wasn't stopped after all), the
  395. * predictor was not quite right, so assume that the CPU could
  396. * have been idle long (but not forever) to help the idle
  397. * duration predictor do a better job next time.
  398. */
  399. measured_ns = 9 * MAX_INTERESTING / 10;
  400. } else if ((drv->states[last_idx].flags & CPUIDLE_FLAG_POLLING) &&
  401. dev->poll_time_limit) {
  402. /*
  403. * The CPU exited the "polling" state due to a time limit, so
  404. * the idle duration prediction leading to the selection of that
  405. * state was inaccurate. If a better prediction had been made,
  406. * the CPU might have been woken up from idle by the next timer.
  407. * Assume that to be the case.
  408. */
  409. measured_ns = data->next_timer_ns;
  410. } else {
  411. /* measured value */
  412. measured_ns = dev->last_residency_ns;
  413. /* Deduct exit latency */
  414. if (measured_ns > 2 * target->exit_latency_ns)
  415. measured_ns -= target->exit_latency_ns;
  416. else
  417. measured_ns /= 2;
  418. }
  419. /* Make sure our coefficients do not exceed unity */
  420. if (measured_ns > data->next_timer_ns)
  421. measured_ns = data->next_timer_ns;
  422. /* Update our correction ratio */
  423. new_factor = data->correction_factor[data->bucket];
  424. new_factor -= new_factor / DECAY;
  425. if (data->next_timer_ns > 0 && measured_ns < MAX_INTERESTING)
  426. new_factor += div64_u64(RESOLUTION * measured_ns,
  427. data->next_timer_ns);
  428. else
  429. /*
  430. * we were idle so long that we count it as a perfect
  431. * prediction
  432. */
  433. new_factor += RESOLUTION;
  434. /*
  435. * We don't want 0 as factor; we always want at least
  436. * a tiny bit of estimated time. Fortunately, due to rounding,
  437. * new_factor will stay nonzero regardless of measured_us values
  438. * and the compiler can eliminate this test as long as DECAY > 1.
  439. */
  440. if (DECAY == 1 && unlikely(new_factor == 0))
  441. new_factor = 1;
  442. data->correction_factor[data->bucket] = new_factor;
  443. menu_update_intervals(data, ktime_to_us(measured_ns));
  444. }
  445. /**
  446. * menu_enable_device - scans a CPU's states and does setup
  447. * @drv: cpuidle driver
  448. * @dev: the CPU
  449. */
  450. static int menu_enable_device(struct cpuidle_driver *drv,
  451. struct cpuidle_device *dev)
  452. {
  453. struct menu_device *data = &per_cpu(menu_devices, dev->cpu);
  454. int i;
  455. memset(data, 0, sizeof(struct menu_device));
  456. /*
  457. * if the correction factor is 0 (eg first time init or cpu hotplug
  458. * etc), we actually want to start out with a unity factor.
  459. */
  460. for(i = 0; i < BUCKETS; i++)
  461. data->correction_factor[i] = RESOLUTION * DECAY;
  462. return 0;
  463. }
  464. static struct cpuidle_governor menu_governor = {
  465. .name = "menu",
  466. .rating = 20,
  467. .enable = menu_enable_device,
  468. .select = menu_select,
  469. .reflect = menu_reflect,
  470. };
  471. /**
  472. * init_menu - initializes the governor
  473. */
  474. static int __init init_menu(void)
  475. {
  476. return cpuidle_register_governor(&menu_governor);
  477. }
  478. postcore_initcall(init_menu);