// SPDX-License-Identifier: GPL-2.01/*2* Timer events oriented CPU idle governor3*4* Copyright (C) 2018 - 2021 Intel Corporation5* Author: Rafael J. Wysocki <[email protected]>6*/78/**9* DOC: teo-description10*11* The idea of this governor is based on the observation that on many systems12* timer interrupts are two or more orders of magnitude more frequent than any13* other interrupt types, so they are likely to dominate CPU wakeup patterns.14* Moreover, in principle, the time when the next timer event is going to occur15* can be determined at the idle state selection time, although doing that may16* be costly, so it can be regarded as the most reliable source of information17* for idle state selection.18*19* Of course, non-timer wakeup sources are more important in some use cases,20* but even then it is generally unnecessary to consider idle duration values21* greater than the time till the next timer event, referred as the sleep22* length in what follows, because the closest timer will ultimately wake up the23* CPU anyway unless it is woken up earlier.24*25* However, since obtaining the sleep length may be costly, the governor first26* checks if it can select a shallow idle state using wakeup pattern information27* from recent times, in which case it can do without knowing the sleep length28* at all. For this purpose, it counts CPU wakeup events and looks for an idle29* state whose target residency has not exceeded the idle duration (measured30* after wakeup) in the majority of relevant recent cases. If the target31* residency of that state is small enough, it may be used right away and the32* sleep length need not be determined.33*34* The computations carried out by this governor are based on using bins whose35* boundaries are aligned with the target residency parameter values of the CPU36* idle states provided by the %CPUIdle driver in the ascending order. That is,37* the first bin spans from 0 up to, but not including, the target residency of38* the second idle state (idle state 1), the second bin spans from the target39* residency of idle state 1 up to, but not including, the target residency of40* idle state 2, the third bin spans from the target residency of idle state 241* up to, but not including, the target residency of idle state 3 and so on.42* The last bin spans from the target residency of the deepest idle state43* supplied by the driver to infinity.44*45* Two metrics called "hits" and "intercepts" are associated with each bin.46* They are updated every time before selecting an idle state for the given CPU47* in accordance with what happened last time.48*49* The "hits" metric reflects the relative frequency of situations in which the50* sleep length and the idle duration measured after CPU wakeup are close enough51* (that is, the CPU appears to wake up "on time" relative to the sleep length).52* In turn, the "intercepts" metric reflects the relative frequency of non-timer53* wakeup events for which the measured idle duration is significantly different54* from the sleep length (these events are also referred to as "intercepts"55* below).56*57* The governor also counts "intercepts" with the measured idle duration below58* the tick period length and uses this information when deciding whether or not59* to stop the scheduler tick.60*61* In order to select an idle state for a CPU, the governor takes the following62* steps (modulo the possible latency constraint that must be taken into account63* too):64*65* 1. Find the deepest enabled CPU idle state (the candidate idle state) and66* compute 2 sums as follows:67*68* - The sum of the "hits" metric for all of the idle states shallower than69* the candidate one (it represents the cases in which the CPU was likely70* woken up by a timer).71*72* - The sum of the "intercepts" metric for all of the idle states shallower73* than the candidate one (it represents the cases in which the CPU was74* likely woken up by a non-timer wakeup source).75*76* Also find the idle state with the maximum intercepts metric (if there are77* multiple states with the maximum intercepts metric, choose the one with78* the highest index).79*80* 2. If the second sum computed in step 1 is greater than a half of the sum of81* both metrics for the candidate state bin and all subsequent bins (if any),82* a shallower idle state is likely to be more suitable, so look for it.83*84* - Traverse the enabled idle states shallower than the candidate one in the85* descending order, starting at the state with the maximum intercepts86* metric found in step 1.87*88* - For each of them compute the sum of the "intercepts" metrics over all89* of the idle states between it and the candidate one (including the90* former and excluding the latter).91*92* - If this sum is greater than a half of the second sum computed in step 1,93* use the given idle state as the new candidate one.94*95* 3. If the current candidate state is state 0 or its target residency is short96* enough, return it and prevent the scheduler tick from being stopped.97*98* 4. Obtain the sleep length value and check if it is below the target99* residency of the current candidate state, in which case a new shallower100* candidate state needs to be found, so look for it.101*/102103#include <linux/cpuidle.h>104#include <linux/jiffies.h>105#include <linux/kernel.h>106#include <linux/sched/clock.h>107#include <linux/tick.h>108109#include "gov.h"110111/*112* Idle state exit latency threshold used for deciding whether or not to check113* the time till the closest expected timer event.114*/115#define LATENCY_THRESHOLD_NS (RESIDENCY_THRESHOLD_NS / 2)116117/*118* The PULSE value is added to metrics when they grow and the DECAY_SHIFT value119* is used for decreasing metrics on a regular basis.120*/121#define PULSE 1024122#define DECAY_SHIFT 3123124/**125* struct teo_bin - Metrics used by the TEO cpuidle governor.126* @intercepts: The "intercepts" metric.127* @hits: The "hits" metric.128*/129struct teo_bin {130unsigned int intercepts;131unsigned int hits;132};133134/**135* struct teo_cpu - CPU data used by the TEO cpuidle governor.136* @sleep_length_ns: Time till the closest timer event (at the selection time).137* @state_bins: Idle state data bins for this CPU.138* @total: Grand total of the "intercepts" and "hits" metrics for all bins.139* @total_tick: Wakeups by the scheduler tick.140* @tick_intercepts: "Intercepts" before TICK_NSEC.141* @short_idles: Wakeups after short idle periods.142* @tick_wakeup: Set if the last wakeup was by the scheduler tick.143*/144struct teo_cpu {145s64 sleep_length_ns;146struct teo_bin state_bins[CPUIDLE_STATE_MAX];147unsigned int total;148unsigned int total_tick;149unsigned int tick_intercepts;150unsigned int short_idles;151bool tick_wakeup;152};153154static DEFINE_PER_CPU(struct teo_cpu, teo_cpus);155156static void teo_decay(unsigned int *metric)157{158unsigned int delta = *metric >> DECAY_SHIFT;159160if (delta)161*metric -= delta;162else163*metric = 0;164}165166/**167* teo_update - Update CPU metrics after wakeup.168* @drv: cpuidle driver containing state data.169* @dev: Target CPU.170*/171static void teo_update(struct cpuidle_driver *drv, struct cpuidle_device *dev)172{173s64 lat_ns = drv->states[dev->last_state_idx].exit_latency_ns;174struct teo_cpu *cpu_data = this_cpu_ptr(&teo_cpus);175int i, idx_timer = 0, idx_duration = 0;176s64 target_residency_ns, measured_ns;177unsigned int total = 0;178179teo_decay(&cpu_data->short_idles);180181if (dev->poll_time_limit) {182dev->poll_time_limit = false;183/*184* Polling state timeout has triggered, so assume that this185* might have been a long sleep.186*/187measured_ns = S64_MAX;188} else {189measured_ns = dev->last_residency_ns;190/*191* The delay between the wakeup and the first instruction192* executed by the CPU is not likely to be worst-case every193* time, so take 1/2 of the exit latency as a very rough194* approximation of the average of it.195*/196if (measured_ns >= lat_ns) {197measured_ns -= lat_ns / 2;198if (measured_ns < RESIDENCY_THRESHOLD_NS)199cpu_data->short_idles += PULSE;200} else {201measured_ns /= 2;202cpu_data->short_idles += PULSE;203}204}205206/*207* Decay the "hits" and "intercepts" metrics for all of the bins and208* find the bins that the sleep length and the measured idle duration209* fall into.210*/211for (i = 0; i < drv->state_count; i++) {212struct teo_bin *bin = &cpu_data->state_bins[i];213214teo_decay(&bin->hits);215total += bin->hits;216teo_decay(&bin->intercepts);217total += bin->intercepts;218219target_residency_ns = drv->states[i].target_residency_ns;220221if (target_residency_ns <= cpu_data->sleep_length_ns) {222idx_timer = i;223if (target_residency_ns <= measured_ns)224idx_duration = i;225}226}227228cpu_data->total = total + PULSE;229230teo_decay(&cpu_data->tick_intercepts);231232teo_decay(&cpu_data->total_tick);233if (cpu_data->tick_wakeup) {234cpu_data->total_tick += PULSE;235/*236* If tick wakeups dominate the wakeup pattern, count this one237* as a hit on the deepest available idle state to increase the238* likelihood of stopping the tick.239*/240if (3 * cpu_data->total_tick > 2 * cpu_data->total) {241cpu_data->state_bins[drv->state_count-1].hits += PULSE;242return;243}244/*245* If intercepts within the tick period range are not frequent246* enough, count this wakeup as a hit, since it is likely that247* the tick has woken up the CPU because an expected intercept248* was not there. Otherwise, one of the intercepts may have249* been incidentally preceded by the tick wakeup.250*/251if (3 * cpu_data->tick_intercepts < 2 * total) {252cpu_data->state_bins[idx_timer].hits += PULSE;253return;254}255}256257/*258* If the measured idle duration (adjusted for the entered state exit259* latency) falls into the same bin as the sleep length and the latter260* is less than the "raw" measured idle duration (so the wakeup appears261* to have occurred after the anticipated timer event), this is a "hit",262* so update the "hits" metric for that bin.263*264* Otherwise, update the "intercepts" metric for the bin fallen into by265* the measured idle duration.266*/267if (idx_timer == idx_duration &&268cpu_data->sleep_length_ns - measured_ns < lat_ns / 2) {269cpu_data->state_bins[idx_timer].hits += PULSE;270} else {271cpu_data->state_bins[idx_duration].intercepts += PULSE;272if (measured_ns <= TICK_NSEC)273cpu_data->tick_intercepts += PULSE;274}275}276277/**278* teo_find_shallower_state - Find shallower idle state matching given duration.279* @drv: cpuidle driver containing state data.280* @dev: Target CPU.281* @state_idx: Index of the capping idle state.282* @duration_ns: Idle duration value to match.283*/284static int teo_find_shallower_state(struct cpuidle_driver *drv,285struct cpuidle_device *dev, int state_idx,286s64 duration_ns)287{288int i;289290for (i = state_idx - 1; i >= 0; i--) {291if (dev->states_usage[i].disable)292continue;293294state_idx = i;295if (drv->states[i].target_residency_ns <= duration_ns)296break;297}298return state_idx;299}300301/**302* teo_select - Selects the next idle state to enter.303* @drv: cpuidle driver containing state data.304* @dev: Target CPU.305* @stop_tick: Indication on whether or not to stop the scheduler tick.306*/307static int teo_select(struct cpuidle_driver *drv, struct cpuidle_device *dev,308bool *stop_tick)309{310struct teo_cpu *cpu_data = this_cpu_ptr(&teo_cpus);311s64 latency_req = cpuidle_governor_latency_req(dev->cpu);312ktime_t delta_tick = TICK_NSEC / 2;313unsigned int idx_intercept_sum = 0;314unsigned int intercept_sum = 0;315unsigned int intercept_max = 0;316unsigned int idx_hit_sum = 0;317unsigned int hit_sum = 0;318int intercept_max_idx = -1;319int constraint_idx = 0;320int idx0 = 0, idx = -1;321s64 duration_ns;322int i;323324if (dev->last_state_idx >= 0) {325teo_update(drv, dev);326dev->last_state_idx = -1;327}328329/*330* Set the sleep length to infinity in case the invocation of331* tick_nohz_get_sleep_length() below is skipped, in which case it won't332* be known whether or not the subsequent wakeup is caused by a timer.333* It is generally fine to count the wakeup as an intercept then, except334* for the cases when the CPU is mostly woken up by timers and there may335* be opportunities to ask for a deeper idle state when no imminent336* timers are scheduled which may be missed.337*/338cpu_data->sleep_length_ns = KTIME_MAX;339340/* Check if there is any choice in the first place. */341if (drv->state_count < 2) {342idx = 0;343goto out_tick;344}345346if (!dev->states_usage[0].disable)347idx = 0;348349/*350* Compute the sums of metrics for early wakeup pattern detection and351* look for the state bin with the maximum intercepts metric below the352* deepest enabled one (if there are multiple states with the maximum353* intercepts metric, choose the one with the highest index).354*/355for (i = 1; i < drv->state_count; i++) {356struct teo_bin *prev_bin = &cpu_data->state_bins[i-1];357unsigned int prev_intercepts = prev_bin->intercepts;358struct cpuidle_state *s = &drv->states[i];359360/*361* Update the sums of idle state metrics for all of the states362* shallower than the current one.363*/364hit_sum += prev_bin->hits;365intercept_sum += prev_intercepts;366/*367* Check if this is the bin with the maximum number of368* intercepts so far and in that case update the index of369* the state with the maximum intercepts metric.370*/371if (prev_intercepts >= intercept_max) {372intercept_max = prev_intercepts;373intercept_max_idx = i - 1;374}375376if (dev->states_usage[i].disable)377continue;378379if (idx < 0)380idx0 = i; /* first enabled state */381382idx = i;383384if (s->exit_latency_ns <= latency_req)385constraint_idx = i;386387/* Save the sums for the current state. */388idx_intercept_sum = intercept_sum;389idx_hit_sum = hit_sum;390}391392/* Avoid unnecessary overhead. */393if (idx < 0) {394idx = 0; /* No states enabled, must use 0. */395goto out_tick;396}397398if (idx == idx0) {399/*400* Only one idle state is enabled, so use it, but do not401* allow the tick to be stopped it is shallow enough.402*/403duration_ns = drv->states[idx].target_residency_ns;404goto end;405}406407/*408* If the sum of the intercepts metric for all of the idle states409* shallower than the current candidate one (idx) is greater than the410* sum of the intercepts and hits metrics for the candidate state and411* all of the deeper states, a shallower idle state is likely to be a412* better choice.413*/414if (2 * idx_intercept_sum > cpu_data->total - idx_hit_sum) {415int min_idx = idx0;416417if (tick_nohz_tick_stopped()) {418/*419* Look for the shallowest idle state below the current420* candidate one whose target residency is at least421* equal to the tick period length.422*/423while (min_idx < idx &&424drv->states[min_idx].target_residency_ns < TICK_NSEC)425min_idx++;426427/*428* Avoid selecting a state with a lower index, but with429* the same target residency as the current candidate430* one.431*/432if (drv->states[min_idx].target_residency_ns ==433drv->states[idx].target_residency_ns)434goto constraint;435}436437/*438* If the minimum state index is greater than or equal to the439* index of the state with the maximum intercepts metric and440* the corresponding state is enabled, there is no need to look441* at the deeper states.442*/443if (min_idx >= intercept_max_idx &&444!dev->states_usage[min_idx].disable) {445idx = min_idx;446goto constraint;447}448449/*450* Look for the deepest enabled idle state, at most as deep as451* the one with the maximum intercepts metric, whose target452* residency had not been greater than the idle duration in over453* a half of the relevant cases in the past.454*455* Take the possible duration limitation present if the tick456* has been stopped already into account.457*/458for (i = idx - 1, intercept_sum = 0; i >= min_idx; i--) {459intercept_sum += cpu_data->state_bins[i].intercepts;460461if (dev->states_usage[i].disable)462continue;463464idx = i;465if (2 * intercept_sum > idx_intercept_sum &&466i <= intercept_max_idx)467break;468}469}470471constraint:472/*473* If there is a latency constraint, it may be necessary to select an474* idle state shallower than the current candidate one.475*/476if (idx > constraint_idx)477idx = constraint_idx;478479/*480* If either the candidate state is state 0 or its target residency is481* low enough, there is basically nothing more to do, but if the sleep482* length is not updated, the subsequent wakeup will be counted as an483* "intercept" which may be problematic in the cases when timer wakeups484* are dominant. Namely, it may effectively prevent deeper idle states485* from being selected at one point even if no imminent timers are486* scheduled.487*488* However, frequent timers in the RESIDENCY_THRESHOLD_NS range on one489* CPU are unlikely (user space has a default 50 us slack value for490* hrtimers and there are relatively few timers with a lower deadline491* value in the kernel), and even if they did happen, the potential492* benefit from using a deep idle state in that case would be493* questionable anyway for latency reasons. Thus if the measured idle494* duration falls into that range in the majority of cases, assume495* non-timer wakeups to be dominant and skip updating the sleep length496* to reduce latency.497*498* Also, if the latency constraint is sufficiently low, it will force499* shallow idle states regardless of the wakeup type, so the sleep500* length need not be known in that case.501*/502if ((!idx || drv->states[idx].target_residency_ns < RESIDENCY_THRESHOLD_NS) &&503(2 * cpu_data->short_idles >= cpu_data->total ||504latency_req < LATENCY_THRESHOLD_NS))505goto out_tick;506507duration_ns = tick_nohz_get_sleep_length(&delta_tick);508cpu_data->sleep_length_ns = duration_ns;509510if (!idx)511goto out_tick;512513/*514* If the closest expected timer is before the target residency of the515* candidate state, a shallower one needs to be found.516*/517if (drv->states[idx].target_residency_ns > duration_ns)518idx = teo_find_shallower_state(drv, dev, idx, duration_ns);519520/*521* If the selected state's target residency is below the tick length522* and intercepts occurring before the tick length are the majority of523* total wakeup events, do not stop the tick.524*/525if (drv->states[idx].target_residency_ns < TICK_NSEC &&5263 * cpu_data->tick_intercepts >= 2 * cpu_data->total)527duration_ns = TICK_NSEC / 2;528529end:530/*531* Allow the tick to be stopped unless the selected state is a polling532* one or the expected idle duration is shorter than the tick period533* length.534*/535if ((!(drv->states[idx].flags & CPUIDLE_FLAG_POLLING) &&536duration_ns >= TICK_NSEC) || tick_nohz_tick_stopped())537return idx;538539/*540* The tick is not going to be stopped, so if the target residency of541* the state to be returned is not within the time till the closest542* timer including the tick, try to correct that.543*/544if (idx > idx0 &&545drv->states[idx].target_residency_ns > delta_tick)546idx = teo_find_shallower_state(drv, dev, idx, delta_tick);547548out_tick:549*stop_tick = false;550return idx;551}552553/**554* teo_reflect - Note that governor data for the CPU need to be updated.555* @dev: Target CPU.556* @state: Entered state.557*/558static void teo_reflect(struct cpuidle_device *dev, int state)559{560struct teo_cpu *cpu_data = this_cpu_ptr(&teo_cpus);561562cpu_data->tick_wakeup = tick_nohz_idle_got_tick();563564dev->last_state_idx = state;565}566567/**568* teo_enable_device - Initialize the governor's data for the target CPU.569* @drv: cpuidle driver (not used).570* @dev: Target CPU.571*/572static int teo_enable_device(struct cpuidle_driver *drv,573struct cpuidle_device *dev)574{575struct teo_cpu *cpu_data = per_cpu_ptr(&teo_cpus, dev->cpu);576577memset(cpu_data, 0, sizeof(*cpu_data));578579return 0;580}581582static struct cpuidle_governor teo_governor = {583.name = "teo",584.rating = 19,585.enable = teo_enable_device,586.select = teo_select,587.reflect = teo_reflect,588};589590static int __init teo_governor_init(void)591{592return cpuidle_register_governor(&teo_governor);593}594595postcore_initcall(teo_governor_init);596597598