// 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 fall into the51* same bin (that is, the CPU appears to wake up "on time" relative to the sleep52* length). In turn, the "intercepts" metric reflects the relative frequency of53* non-timer wakeup events for which the measured idle duration falls into a bin54* that corresponds to an idle state shallower than the one whose bin is fallen55* into by the sleep length (these events are also referred to as "intercepts"56* below).57*58* The governor also counts "intercepts" with the measured idle duration below59* the tick period length and uses this information when deciding whether or not60* to stop the scheduler tick.61*62* In order to select an idle state for a CPU, the governor takes the following63* steps (modulo the possible latency constraint that must be taken into account64* too):65*66* 1. Find the deepest enabled CPU idle state (the candidate idle state) and67* compute 2 sums as follows:68*69* - The sum of the "hits" metric for all of the idle states shallower than70* the candidate one (it represents the cases in which the CPU was likely71* woken up by a timer).72*73* - The sum of the "intercepts" metric for all of the idle states shallower74* than the candidate one (it represents the cases in which the CPU was75* likely woken up by a non-timer wakeup source).76*77* 2. If the second sum computed in step 1 is greater than a half of the sum of78* both metrics for the candidate state bin and all subsequent bins(if any),79* a shallower idle state is likely to be more suitable, so look for it.80*81* - Traverse the enabled idle states shallower than the candidate one in the82* descending order.83*84* - For each of them compute the sum of the "intercepts" metrics over all85* of the idle states between it and the candidate one (including the86* former and excluding the latter).87*88* - If this sum is greater than a half of the second sum computed in step 1,89* use the given idle state as the new candidate one.90*91* 3. If the current candidate state is state 0 or its target residency is short92* enough, return it and prevent the scheduler tick from being stopped.93*94* 4. Obtain the sleep length value and check if it is below the target95* residency of the current candidate state, in which case a new shallower96* candidate state needs to be found, so look for it.97*/9899#include <linux/cpuidle.h>100#include <linux/jiffies.h>101#include <linux/kernel.h>102#include <linux/sched/clock.h>103#include <linux/tick.h>104105#include "gov.h"106107/*108* Idle state exit latency threshold used for deciding whether or not to check109* the time till the closest expected timer event.110*/111#define LATENCY_THRESHOLD_NS (RESIDENCY_THRESHOLD_NS / 2)112113/*114* The PULSE value is added to metrics when they grow and the DECAY_SHIFT value115* is used for decreasing metrics on a regular basis.116*/117#define PULSE 1024118#define DECAY_SHIFT 3119120/**121* struct teo_bin - Metrics used by the TEO cpuidle governor.122* @intercepts: The "intercepts" metric.123* @hits: The "hits" metric.124*/125struct teo_bin {126unsigned int intercepts;127unsigned int hits;128};129130/**131* struct teo_cpu - CPU data used by the TEO cpuidle governor.132* @sleep_length_ns: Time till the closest timer event (at the selection time).133* @state_bins: Idle state data bins for this CPU.134* @total: Grand total of the "intercepts" and "hits" metrics for all bins.135* @tick_intercepts: "Intercepts" before TICK_NSEC.136* @short_idles: Wakeups after short idle periods.137* @artificial_wakeup: Set if the wakeup has been triggered by a safety net.138*/139struct teo_cpu {140s64 sleep_length_ns;141struct teo_bin state_bins[CPUIDLE_STATE_MAX];142unsigned int total;143unsigned int tick_intercepts;144unsigned int short_idles;145bool artificial_wakeup;146};147148static DEFINE_PER_CPU(struct teo_cpu, teo_cpus);149150/**151* teo_update - Update CPU metrics after wakeup.152* @drv: cpuidle driver containing state data.153* @dev: Target CPU.154*/155static void teo_update(struct cpuidle_driver *drv, struct cpuidle_device *dev)156{157struct teo_cpu *cpu_data = per_cpu_ptr(&teo_cpus, dev->cpu);158int i, idx_timer = 0, idx_duration = 0;159s64 target_residency_ns;160u64 measured_ns;161162cpu_data->short_idles -= cpu_data->short_idles >> DECAY_SHIFT;163164if (cpu_data->artificial_wakeup) {165/*166* If one of the safety nets has triggered, assume that this167* might have been a long sleep.168*/169measured_ns = U64_MAX;170} else {171u64 lat_ns = drv->states[dev->last_state_idx].exit_latency_ns;172173measured_ns = dev->last_residency_ns;174/*175* The delay between the wakeup and the first instruction176* executed by the CPU is not likely to be worst-case every177* time, so take 1/2 of the exit latency as a very rough178* approximation of the average of it.179*/180if (measured_ns >= lat_ns) {181measured_ns -= lat_ns / 2;182if (measured_ns < RESIDENCY_THRESHOLD_NS)183cpu_data->short_idles += PULSE;184} else {185measured_ns /= 2;186cpu_data->short_idles += PULSE;187}188}189190/*191* Decay the "hits" and "intercepts" metrics for all of the bins and192* find the bins that the sleep length and the measured idle duration193* fall into.194*/195for (i = 0; i < drv->state_count; i++) {196struct teo_bin *bin = &cpu_data->state_bins[i];197198bin->hits -= bin->hits >> DECAY_SHIFT;199bin->intercepts -= bin->intercepts >> DECAY_SHIFT;200201target_residency_ns = drv->states[i].target_residency_ns;202203if (target_residency_ns <= cpu_data->sleep_length_ns) {204idx_timer = i;205if (target_residency_ns <= measured_ns)206idx_duration = i;207}208}209210cpu_data->tick_intercepts -= cpu_data->tick_intercepts >> DECAY_SHIFT;211/*212* If the measured idle duration falls into the same bin as the sleep213* length, this is a "hit", so update the "hits" metric for that bin.214* Otherwise, update the "intercepts" metric for the bin fallen into by215* the measured idle duration.216*/217if (idx_timer == idx_duration) {218cpu_data->state_bins[idx_timer].hits += PULSE;219} else {220cpu_data->state_bins[idx_duration].intercepts += PULSE;221if (TICK_NSEC <= measured_ns)222cpu_data->tick_intercepts += PULSE;223}224225cpu_data->total -= cpu_data->total >> DECAY_SHIFT;226cpu_data->total += PULSE;227}228229static bool teo_state_ok(int i, struct cpuidle_driver *drv)230{231return !tick_nohz_tick_stopped() ||232drv->states[i].target_residency_ns >= TICK_NSEC;233}234235/**236* teo_find_shallower_state - Find shallower idle state matching given duration.237* @drv: cpuidle driver containing state data.238* @dev: Target CPU.239* @state_idx: Index of the capping idle state.240* @duration_ns: Idle duration value to match.241* @no_poll: Don't consider polling states.242*/243static int teo_find_shallower_state(struct cpuidle_driver *drv,244struct cpuidle_device *dev, int state_idx,245s64 duration_ns, bool no_poll)246{247int i;248249for (i = state_idx - 1; i >= 0; i--) {250if (dev->states_usage[i].disable ||251(no_poll && drv->states[i].flags & CPUIDLE_FLAG_POLLING))252continue;253254state_idx = i;255if (drv->states[i].target_residency_ns <= duration_ns)256break;257}258return state_idx;259}260261/**262* teo_select - Selects the next idle state to enter.263* @drv: cpuidle driver containing state data.264* @dev: Target CPU.265* @stop_tick: Indication on whether or not to stop the scheduler tick.266*/267static int teo_select(struct cpuidle_driver *drv, struct cpuidle_device *dev,268bool *stop_tick)269{270struct teo_cpu *cpu_data = per_cpu_ptr(&teo_cpus, dev->cpu);271s64 latency_req = cpuidle_governor_latency_req(dev->cpu);272ktime_t delta_tick = TICK_NSEC / 2;273unsigned int idx_intercept_sum = 0;274unsigned int intercept_sum = 0;275unsigned int idx_hit_sum = 0;276unsigned int hit_sum = 0;277int constraint_idx = 0;278int idx0 = 0, idx = -1;279s64 duration_ns;280int i;281282if (dev->last_state_idx >= 0) {283teo_update(drv, dev);284dev->last_state_idx = -1;285}286287/*288* Set the sleep length to infinity in case the invocation of289* tick_nohz_get_sleep_length() below is skipped, in which case it won't290* be known whether or not the subsequent wakeup is caused by a timer.291* It is generally fine to count the wakeup as an intercept then, except292* for the cases when the CPU is mostly woken up by timers and there may293* be opportunities to ask for a deeper idle state when no imminent294* timers are scheduled which may be missed.295*/296cpu_data->sleep_length_ns = KTIME_MAX;297298/* Check if there is any choice in the first place. */299if (drv->state_count < 2) {300idx = 0;301goto out_tick;302}303304if (!dev->states_usage[0].disable)305idx = 0;306307/* Compute the sums of metrics for early wakeup pattern detection. */308for (i = 1; i < drv->state_count; i++) {309struct teo_bin *prev_bin = &cpu_data->state_bins[i-1];310struct cpuidle_state *s = &drv->states[i];311312/*313* Update the sums of idle state metrics for all of the states314* shallower than the current one.315*/316intercept_sum += prev_bin->intercepts;317hit_sum += prev_bin->hits;318319if (dev->states_usage[i].disable)320continue;321322if (idx < 0)323idx0 = i; /* first enabled state */324325idx = i;326327if (s->exit_latency_ns <= latency_req)328constraint_idx = i;329330/* Save the sums for the current state. */331idx_intercept_sum = intercept_sum;332idx_hit_sum = hit_sum;333}334335/* Avoid unnecessary overhead. */336if (idx < 0) {337idx = 0; /* No states enabled, must use 0. */338goto out_tick;339}340341if (idx == idx0) {342/*343* Only one idle state is enabled, so use it, but do not344* allow the tick to be stopped it is shallow enough.345*/346duration_ns = drv->states[idx].target_residency_ns;347goto end;348}349350/*351* If the sum of the intercepts metric for all of the idle states352* shallower than the current candidate one (idx) is greater than the353* sum of the intercepts and hits metrics for the candidate state and354* all of the deeper states, a shallower idle state is likely to be a355* better choice.356*/357if (2 * idx_intercept_sum > cpu_data->total - idx_hit_sum) {358int first_suitable_idx = idx;359360/*361* Look for the deepest idle state whose target residency had362* not exceeded the idle duration in over a half of the relevant363* cases in the past.364*365* Take the possible duration limitation present if the tick366* has been stopped already into account.367*/368intercept_sum = 0;369370for (i = idx - 1; i >= 0; i--) {371struct teo_bin *bin = &cpu_data->state_bins[i];372373intercept_sum += bin->intercepts;374375if (2 * intercept_sum > idx_intercept_sum) {376/*377* Use the current state unless it is too378* shallow or disabled, in which case take the379* first enabled state that is deep enough.380*/381if (teo_state_ok(i, drv) &&382!dev->states_usage[i].disable) {383idx = i;384break;385}386idx = first_suitable_idx;387break;388}389390if (dev->states_usage[i].disable)391continue;392393if (teo_state_ok(i, drv)) {394/*395* The current state is deep enough, but still396* there may be a better one.397*/398first_suitable_idx = i;399continue;400}401402/*403* The current state is too shallow, so if no suitable404* states other than the initial candidate have been405* found, give up (the remaining states to check are406* shallower still), but otherwise the first suitable407* state other than the initial candidate may turn out408* to be preferable.409*/410if (first_suitable_idx == idx)411break;412}413}414415/*416* If there is a latency constraint, it may be necessary to select an417* idle state shallower than the current candidate one.418*/419if (idx > constraint_idx)420idx = constraint_idx;421422/*423* If either the candidate state is state 0 or its target residency is424* low enough, there is basically nothing more to do, but if the sleep425* length is not updated, the subsequent wakeup will be counted as an426* "intercept" which may be problematic in the cases when timer wakeups427* are dominant. Namely, it may effectively prevent deeper idle states428* from being selected at one point even if no imminent timers are429* scheduled.430*431* However, frequent timers in the RESIDENCY_THRESHOLD_NS range on one432* CPU are unlikely (user space has a default 50 us slack value for433* hrtimers and there are relatively few timers with a lower deadline434* value in the kernel), and even if they did happen, the potential435* benefit from using a deep idle state in that case would be436* questionable anyway for latency reasons. Thus if the measured idle437* duration falls into that range in the majority of cases, assume438* non-timer wakeups to be dominant and skip updating the sleep length439* to reduce latency.440*441* Also, if the latency constraint is sufficiently low, it will force442* shallow idle states regardless of the wakeup type, so the sleep443* length need not be known in that case.444*/445if ((!idx || drv->states[idx].target_residency_ns < RESIDENCY_THRESHOLD_NS) &&446(2 * cpu_data->short_idles >= cpu_data->total ||447latency_req < LATENCY_THRESHOLD_NS))448goto out_tick;449450duration_ns = tick_nohz_get_sleep_length(&delta_tick);451cpu_data->sleep_length_ns = duration_ns;452453if (!idx)454goto out_tick;455456/*457* If the closest expected timer is before the target residency of the458* candidate state, a shallower one needs to be found.459*/460if (drv->states[idx].target_residency_ns > duration_ns) {461i = teo_find_shallower_state(drv, dev, idx, duration_ns, false);462if (teo_state_ok(i, drv))463idx = i;464}465466/*467* If the selected state's target residency is below the tick length468* and intercepts occurring before the tick length are the majority of469* total wakeup events, do not stop the tick.470*/471if (drv->states[idx].target_residency_ns < TICK_NSEC &&472cpu_data->tick_intercepts > cpu_data->total / 2 + cpu_data->total / 8)473duration_ns = TICK_NSEC / 2;474475end:476/*477* Allow the tick to be stopped unless the selected state is a polling478* one or the expected idle duration is shorter than the tick period479* length.480*/481if ((!(drv->states[idx].flags & CPUIDLE_FLAG_POLLING) &&482duration_ns >= TICK_NSEC) || tick_nohz_tick_stopped())483return idx;484485/*486* The tick is not going to be stopped, so if the target residency of487* the state to be returned is not within the time till the closest488* timer including the tick, try to correct that.489*/490if (idx > idx0 &&491drv->states[idx].target_residency_ns > delta_tick)492idx = teo_find_shallower_state(drv, dev, idx, delta_tick, false);493494out_tick:495*stop_tick = false;496return idx;497}498499/**500* teo_reflect - Note that governor data for the CPU need to be updated.501* @dev: Target CPU.502* @state: Entered state.503*/504static void teo_reflect(struct cpuidle_device *dev, int state)505{506struct teo_cpu *cpu_data = per_cpu_ptr(&teo_cpus, dev->cpu);507508dev->last_state_idx = state;509if (dev->poll_time_limit ||510(tick_nohz_idle_got_tick() && cpu_data->sleep_length_ns > TICK_NSEC)) {511/*512* The wakeup was not "genuine", but triggered by one of the513* safety nets.514*/515dev->poll_time_limit = false;516cpu_data->artificial_wakeup = true;517} else {518cpu_data->artificial_wakeup = false;519}520}521522/**523* teo_enable_device - Initialize the governor's data for the target CPU.524* @drv: cpuidle driver (not used).525* @dev: Target CPU.526*/527static int teo_enable_device(struct cpuidle_driver *drv,528struct cpuidle_device *dev)529{530struct teo_cpu *cpu_data = per_cpu_ptr(&teo_cpus, dev->cpu);531532memset(cpu_data, 0, sizeof(*cpu_data));533534return 0;535}536537static struct cpuidle_governor teo_governor = {538.name = "teo",539.rating = 19,540.enable = teo_enable_device,541.select = teo_select,542.reflect = teo_reflect,543};544545static int __init teo_governor_init(void)546{547return cpuidle_register_governor(&teo_governor);548}549550postcore_initcall(teo_governor_init);551552553