diff --git a/Documentation/devicetree/bindings/power/apple,pmc.yaml b/Documentation/devicetree/bindings/power/apple,pmc.yaml index 9ecd11e5ab6bc..c8e4c86a5f36e 100644 --- a/Documentation/devicetree/bindings/power/apple,pmc.yaml +++ b/Documentation/devicetree/bindings/power/apple,pmc.yaml @@ -350,6 +350,25 @@ patternProperties: The low-power platform profile tells the SMC (apple,smc) that Low Power Mode is on, in the record that carries High Power mode. + apple,low-power-capacity-ceiling: + type: boolean + description: + When the low-power profile holds a package power target, scale + each CPU cluster's initial frequency ceiling from + apple,low-power-frequency-max-mhz by the ratio of the fastest + cluster's capacity-dmips-mhz to that cluster's capacity-dmips-mhz. + Efficiency clusters then stay uncapped up to the same single-thread + performance level as the performance cluster at the ceiling, and + the power loop steps them down only when package power exceeds the + target. + + apple,energy-monitor: + $ref: /schemas/types.yaml#/definitions/phandle + description: + Optional apple,acc-energy node providing hardware CPU and cluster + energy accumulators sampled alongside live GPU power every 100 ms + in the low-power profile, supplementing the slower SMC power key. + apple,gpu-busy-memory-states: $ref: /schemas/types.yaml#/definitions/uint32-matrix description: diff --git a/Documentation/devicetree/bindings/soc/apple/apple,acc-energy.yaml b/Documentation/devicetree/bindings/soc/apple/apple,acc-energy.yaml new file mode 100644 index 0000000000000..73c603a0f7f97 --- /dev/null +++ b/Documentation/devicetree/bindings/soc/apple/apple,acc-energy.yaml @@ -0,0 +1,61 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/soc/apple/apple,acc-energy.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Apple SoC CPU/cluster hardware energy accumulators + +maintainers: + - Nick + +description: | + Memory-mapped 64-bit hardware energy accumulators in the Apple CPU complex + (per-core and cluster memory energy counters). Each reg entry covers one + 16-byte accumulator pair: the primary 64-bit counter at +0x0 and the + companion SRAM 64-bit counter at +0x8, incremented in units of + apple,picojoules-per-tick. Referenced by apple,energy-monitor from a CLPC + node for 100 ms low-power package limiting. + +properties: + compatible: + items: + - enum: + - apple,t8142-acc-energy + - const: apple,acc-energy + + reg: + minItems: 1 + maxItems: 32 + description: + 16-byte register windows, each containing a pair of 64-bit hardware + energy accumulators (core/cluster logic at +0x0, SRAM at +0x8). + + apple,picojoules-per-tick: + $ref: /schemas/types.yaml#/definitions/uint32 + minimum: 1 + description: + Energy represented by one accumulator tick, in picojoules. + +required: + - compatible + - reg + - apple,picojoules-per-tick + +additionalProperties: false + +examples: + - | + soc { + #address-cells = <2>; + #size-cells = <2>; + + power-monitor@210059000 { + compatible = "apple,t8142-acc-energy", "apple,acc-energy"; + reg = <0x2 0x10059000 0x0 0x10>, + <0x2 0x10e48000 0x0 0x10>, + <0x2 0x11059000 0x0 0x10>, + <0x2 0x11e48000 0x0 0x10>; + apple,picojoules-per-tick = <25>; + }; + }; diff --git a/Documentation/devicetree/bindings/soc/apple/apple,clpc.yaml b/Documentation/devicetree/bindings/soc/apple/apple,clpc.yaml index 3e270094bded4..db8f5a2e72f2d 100644 --- a/Documentation/devicetree/bindings/soc/apple/apple,clpc.yaml +++ b/Documentation/devicetree/bindings/soc/apple/apple,clpc.yaml @@ -81,6 +81,21 @@ properties: The low-power platform profile tells the SMC (apple,smc) that Low Power Mode is on, in the record that carries High Power mode. + apple,low-power-capacity-ceiling: + type: boolean + description: + When the low-power profile holds a package power target, scale each + CPU cluster's initial frequency ceiling from + apple,low-power-frequency-max-mhz by the ratio of the fastest + cluster's capacity-dmips-mhz to that cluster's capacity-dmips-mhz. + + apple,energy-monitor: + $ref: /schemas/types.yaml#/definitions/phandle + description: + Optional apple,acc-energy node providing hardware CPU and cluster + energy accumulators sampled alongside live GPU power every 100 ms in + the low-power profile, supplementing the slower SMC power key. + required: - compatible diff --git a/arch/arm64/boot/dts/apple/t8142-j813-j815.dtsi b/arch/arm64/boot/dts/apple/t8142-j813-j815.dtsi index 8233cb953cda6..70c1171f60a34 100644 --- a/arch/arm64/boot/dts/apple/t8142-j813-j815.dtsi +++ b/arch/arm64/boot/dts/apple/t8142-j813-j815.dtsi @@ -207,6 +207,23 @@ }; &{/soc} { + cpu_energy: power-monitor@210059000 { + compatible = "apple,t8142-acc-energy", "apple,acc-energy"; + reg = <0x2 0x10059000 0x0 0x10>, + <0x2 0x10159000 0x0 0x10>, + <0x2 0x10259000 0x0 0x10>, + <0x2 0x10359000 0x0 0x10>, + <0x2 0x10459000 0x0 0x10>, + <0x2 0x10559000 0x0 0x10>, + <0x2 0x10e48000 0x0 0x10>, + <0x2 0x11059000 0x0 0x10>, + <0x2 0x11159000 0x0 0x10>, + <0x2 0x11259000 0x0 0x10>, + <0x2 0x11359000 0x0 0x10>, + <0x2 0x11e48000 0x0 0x10>; + apple,picojoules-per-tick = <25>; + }; + cpufreq_e: performance-controller@210e20000 { compatible = "apple,t8142-cluster-cpufreq"; reg = <0x2 0x10e20000 0 0x1000>; @@ -256,6 +273,8 @@ apple,low-power-gpu-cap; /* Tell the SMC when the low-power platform profile is on. */ apple,low-power-smc-notice; + apple,low-power-capacity-ceiling; + apple,energy-monitor = <&cpu_energy>; /* The ANE engine clock follows the P cluster's frequency */ apple,ane-cpu-opp = <&pcluster_opp_4176>; /* diff --git a/drivers/gpu/drm/asahi/g17/clpc.c b/drivers/gpu/drm/asahi/g17/clpc.c index 071bed6db51de..42daa7d7a476d 100644 --- a/drivers/gpu/drm/asahi/g17/clpc.c +++ b/drivers/gpu/drm/asahi/g17/clpc.c @@ -21,6 +21,11 @@ void asahi_clpc_gpu_clear_busy(struct apple_clpc_gpu *gpu) apple_clpc_gpu_clear_busy(gpu); } +void asahi_clpc_gpu_set_power_mw(struct apple_clpc_gpu *gpu, unsigned int power_mw) +{ + apple_clpc_gpu_set_power_mw(gpu, power_mw); +} + unsigned int asahi_clpc_gpu_power_cap(struct apple_clpc_gpu *gpu) { return apple_clpc_gpu_power_cap(gpu); diff --git a/drivers/gpu/drm/asahi/g17/clpc.h b/drivers/gpu/drm/asahi/g17/clpc.h index 19a776a752b01..24530b52da601 100644 --- a/drivers/gpu/drm/asahi/g17/clpc.h +++ b/drivers/gpu/drm/asahi/g17/clpc.h @@ -7,6 +7,7 @@ int asahi_clpc_gpu_get(void *dev, struct apple_clpc_gpu **out); void asahi_clpc_gpu_set_active(struct apple_clpc_gpu *gpu, bool active); void asahi_clpc_gpu_set_busy(struct apple_clpc_gpu *gpu, unsigned int permille); void asahi_clpc_gpu_clear_busy(struct apple_clpc_gpu *gpu); +void asahi_clpc_gpu_set_power_mw(struct apple_clpc_gpu *gpu, unsigned int power_mw); unsigned int asahi_clpc_gpu_power_cap(struct apple_clpc_gpu *gpu); void asahi_clpc_gpu_put(struct apple_clpc_gpu *gpu); #endif diff --git a/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs b/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs index a7829960a39cc..7aa12bebbb62b 100644 --- a/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs @@ -2239,6 +2239,13 @@ pub(crate) const M5_STATUS_CONFIG_LINK_WORD: usize = 0x774; pub(crate) const M5_STATUS_CONFIG_LINK_PTR: usize = 0x778; +/// Fast host power-target words in the M5 status config (inside the unshifted +/// `0x000..0x1dc` band across all M5 firmware layouts): enable flag, target in mW, +/// and policy reason word. +pub(crate) const M5_STATUS_CONFIG_POWER_TARGET_ENABLE: usize = 0x128; +pub(crate) const M5_STATUS_CONFIG_POWER_TARGET_MW: usize = 0x12c; +pub(crate) const M5_STATUS_CONFIG_POWER_TARGET_REASON: usize = 0x144; + /// Submission-history period and slot count (two u64), its generation word and its per-slot /// bytes in the status config, at 26A428 offsets. pub(crate) const M5_STATUS_CONFIG_HISTORY: usize = 0x73c; diff --git a/drivers/gpu/drm/asahi/g17/initdata/m5.rs b/drivers/gpu/drm/asahi/g17/initdata/m5.rs index 21c37670f3129..bebe0548b08d5 100644 --- a/drivers/gpu/drm/asahi/g17/initdata/m5.rs +++ b/drivers/gpu/drm/asahi/g17/initdata/m5.rs @@ -159,6 +159,67 @@ impl InitData { self.m5_policy = m::m5_policy(layouts); } + /// M5 only: reads the live status-config power target word (mW). + pub(in crate::g17) fn m5_power_target(&self) -> Result { + if !self.m5 { + return Err(EINVAL); + } + let private = self.object(self.cluster)?; + let offset = self + .m5_status_config + .relocate(m::M5_STATUS_CONFIG_POWER_TARGET_MW) + .ok_or(EINVAL)?; + Ok(private + .word(self.graph.private.status_config + offset)? + .load(Ordering::Relaxed)) + } + + /// M5 only: publishes the fast status-config power target (mW) and policy reason. + /// The reason sits on another cache line than the target and enable words, so it is + /// written, cleaned and drained first: the firmware never sees the new enable and + /// target with the old reason. Then the target, then the enable, each cleaned and + /// drained before the next store. + pub(in crate::g17) fn publish_m5_power_target(&self, target_mw: u32, reason: u32) -> Result { + if !self.m5 { + return Err(EINVAL); + } + let private = self.object(self.cluster)?; + let base = self.graph.private.status_config; + let field = |offset| { + self.m5_status_config + .relocate(offset) + .map(|at| base + at) + .ok_or(EINVAL) + }; + let enable_at = field(m::M5_STATUS_CONFIG_POWER_TARGET_ENABLE)?; + let target_at = field(m::M5_STATUS_CONFIG_POWER_TARGET_MW)?; + let reason_at = field(m::M5_STATUS_CONFIG_POWER_TARGET_REASON)?; + let enable_word = private.word(enable_at)?; + let target_word = private.word(target_at)?; + let reason_word = private.word(reason_at)?; + let enable_line = private.pointer(enable_at, 4)?; + let target_line = private.pointer(target_at, 4)?; + let reason_line = private.pointer(reason_at, 4)?; + // SAFETY: the pointer lies inside the retained host mapping of the + // private cluster; cleaning its cache line and draining publishes the + // naturally aligned store before it to the firmware. + let publish = |line: *mut u8| unsafe { + core::arch::asm!( + "dc cvac, {line}", + "dsb sy", + line = in(reg) line, + options(nostack, preserves_flags) + ) + }; + reason_word.store(reason, Ordering::Relaxed); + publish(reason_line); + target_word.store(target_mw, Ordering::Relaxed); + publish(target_line); + enable_word.store(1, Ordering::Relaxed); + publish(enable_line); + Ok(()) + } + /// Counts `submissions` in the firmware's submission history, in the slot of this moment. pub(crate) fn note_m5_submission_history(&self, submissions: u8) -> Result { if !self.m5 { return Err(EINVAL); } diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index 8f5cc4335bac9..2dfc9442aace6 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -832,6 +832,8 @@ struct Firmware { hold: power::Hold, /// M5: host GPU power budget governor (Region C's budget word). governor: thermal::Governor, + /// M5: fast CLPC low-power target (status config `+0x12c`). + power_target: thermal::PowerTarget, registration_power_release_pending: bool, variant: &'static fw::Variant, queues: runtime::Registry, @@ -971,6 +973,8 @@ impl Firmware { // preparations, or the sleep's commit: the firmware no longer runs, and its latched // effort must not keep the fans boosted. if !self.primary.running || power::Control::crashed(self) { + // No stale GPU power in CLPC's loop while the firmware is not running. + self.port.set_power_mw(0); return None; } let now = now_ns(); @@ -985,13 +989,18 @@ impl Firmware { self.governor.note_activity(now); } // The low-power profile's GPU power cap (CLPC), applied while the GPU is busy. - let cap = self.port.power_cap_mw(); + let busy = thermal::requested() && self.governor.recent_activity(now); + let power = if busy { self.init.m5_gpu_power_mw().unwrap_or(0) } else { 0 }; + self.port.set_power_mw(power); + let raw_cap = self.port.power_cap_mw(); + let active_cap = if busy { raw_cap } else { 0 }; + // Prefer the fast M5 status-config power target; fall back to Region C if absent. + let cap = if self.apply_power_target(active_cap) { 0 } else { raw_cap }; // Without the budget controller (not requested, or the SoC die zone or its passive trip // gone) only the fan assistance and the cap run (FanBoost::apply). A budget the // controller left below the calibrated maximum (or the cap) goes back, and a failed write // is retried. if !thermal::enabled() { - let busy = thermal::requested() && self.governor.recent_activity(now); let cap = if busy { cap } else { 0 }; if let Ok(current) = self.init.m5_power_budget() { self.governor.set_maximum(current); @@ -999,14 +1008,13 @@ impl Firmware { if let Some(budget) = self.governor.restore_capped(cap) { self.publish_budget(budget); } - let again = busy || fans || self.governor.pending(); + let again = busy || fans || self.governor.pending() || self.power_target.pending(); return Some((again, thermal::CpuAdvice::Release, busy)); } let Ok(current) = self.init.m5_power_budget() else { - return Some((false, thermal::CpuAdvice::Release, false)); + return Some((self.power_target.pending(), thermal::CpuAdvice::Release, false)); }; self.governor.set_maximum(current); - let power = self.init.m5_gpu_power_mw().unwrap_or(0); let clamped = self.init.m5_firmware_clamped().unwrap_or(false); let (publish, again) = self.governor.tick(temp_mc, power, clamped, cap, now); if let Some(budget) = publish { @@ -1015,8 +1023,25 @@ impl Firmware { let advice = self.governor.cpu_advice(power, now); let want_fans = self.governor.fans_wanted(now); // Keep ticking while the fans are still boosted, so the hold can expire, and while a - // budget write is owed. - Some((again || fans || self.governor.pending(), advice, want_fans)) + // budget or status-config target write is owed. + Some(( + again || fans || self.governor.pending() || self.power_target.pending(), + advice, + want_fans, + )) + } + + /// Publishes the fast M5 status-config power target when available; returns true if handled. + fn apply_power_target(&mut self, cap_mw: u32) -> bool { + let Ok(current) = self.init.m5_power_target() else { + return false; + }; + if let Some((target_mw, reason)) = self.power_target.apply(cap_mw, current) { + if self.init.publish_m5_power_target(target_mw, reason).is_err() { + self.power_target.publish_failed(); + } + } + true } /// Publishes a budget the governor returned; a failed write stays owed for the next step. @@ -1026,14 +1051,24 @@ impl Firmware { } } - /// Restore the calibrated maximum budget (shutdown). + /// Restore the calibrated maximum budget and status-config power target (shutdown). fn governor_restore(&mut self) { + self.port.set_power_mw(0); + if let Ok(current) = self.init.m5_power_target() { + if let Some((target_mw, reason)) = self.power_target.restore(current) { + let _ = self.init.publish_m5_power_target(target_mw, reason); + } + } if let Some(budget) = self.governor.restore() { let _ = self.init.publish_m5_power_budget(budget); } } fn apply_effort(&mut self, effort: u32) -> Result { + // The power target is lazy (thermal::PowerTarget): a zero cap only restores a cap this + // driver put in, so leaving the low-power profile under load uncaps at once. + let cap = if effort == 0 { 0 } else { self.port.power_cap_mw() }; + let _ = self.apply_power_target(cap); Self::apply_shared_effort( &self.primary.state.shared, &self.init, @@ -2675,6 +2710,7 @@ impl Gpu { effort: power::Effort::new(), hold: power::Hold::new(), governor: thermal::Governor::new(), + power_target: thermal::PowerTarget::new(), registration_power_release_pending: false, variant: shared.variant, queues <- runtime::Registry::with_waiters( @@ -2884,6 +2920,7 @@ impl Gpu { effort: power::Effort::new(), hold: power::Hold::new(), governor: thermal::Governor::new(), + power_target: thermal::PowerTarget::new(), registration_power_release_pending: false, variant: shared.variant, queues <- runtime::Registry::with_waiters( diff --git a/drivers/gpu/drm/asahi/g17/port.rs b/drivers/gpu/drm/asahi/g17/port.rs index c803bbf8df727..eb1b80f478b55 100644 --- a/drivers/gpu/drm/asahi/g17/port.rs +++ b/drivers/gpu/drm/asahi/g17/port.rs @@ -1068,6 +1068,11 @@ impl Port { self.effort_full.store(true, Ordering::SeqCst); } + /// Reports live GPU power draw in mW to the CLPC low-power loop. + pub(super) fn set_power_mw(&self, power_mw: u32) { + self.demand.set_power_mw(power_mw); + } + /// The power in mW the low-power profile allows the GPU's power budget, 0 for no limit. pub(super) fn power_cap_mw(&self) -> u32 { self.demand.power_cap_mw() diff --git a/drivers/gpu/drm/asahi/g17/power.rs b/drivers/gpu/drm/asahi/g17/power.rs index f28545fc8f4c9..f492d479b0e02 100644 --- a/drivers/gpu/drm/asahi/g17/power.rs +++ b/drivers/gpu/drm/asahi/g17/power.rs @@ -1250,6 +1250,7 @@ unsafe extern "C" { fn asahi_clpc_gpu_put(gpu: *mut core::ffi::c_void); fn asahi_clpc_gpu_set_busy(gpu: *mut core::ffi::c_void, permille: core::ffi::c_uint); fn asahi_clpc_gpu_clear_busy(gpu: *mut core::ffi::c_void); + fn asahi_clpc_gpu_set_power_mw(gpu: *mut core::ffi::c_void, power_mw: core::ffi::c_uint); fn asahi_clpc_gpu_power_cap(gpu: *mut core::ffi::c_void) -> core::ffi::c_uint; } @@ -1293,6 +1294,11 @@ impl Demand { unsafe { asahi_clpc_gpu_clear_busy(self.0) }; } + pub(super) fn set_power_mw(&self, power_mw: u32) { + // SAFETY: the retained reference is live; NULL denotes no DT provider. + unsafe { asahi_clpc_gpu_set_power_mw(self.0, power_mw as core::ffi::c_uint) }; + } + /// The power in mW the low-power profile allows the GPU's own budget, 0 for no limit /// (and without a provider). pub(super) fn power_cap_mw(&self) -> u32 { diff --git a/drivers/gpu/drm/asahi/g17/thermal.rs b/drivers/gpu/drm/asahi/g17/thermal.rs index c7551b38dd4db..f95c23ec78c03 100644 --- a/drivers/gpu/drm/asahi/g17/thermal.rs +++ b/drivers/gpu/drm/asahi/g17/thermal.rs @@ -1075,3 +1075,78 @@ impl Governor { (publish, again) } } + +/// Reason word written alongside a CLPC low-power target in the M5 status config. +pub(crate) const POWER_TARGET_REASON_LOW_POWER: u32 = 0x3120_0003; +/// Reason word written when restoring the M5 status config's initial maximum target. +pub(crate) const POWER_TARGET_REASON_RESTORE: u32 = 0x3000_001d; + +/// Fast host power-target controller backed by the M5 status-config words +/// (`+0x128` enable, `+0x12c` target mW, `+0x144` reason). Keeps low-power +/// capping decoupled from the slow Region C thermal budget governor. +pub(crate) struct PowerTarget { + /// The firmware's own target, read when the first cap went in; restored when the cap goes. + maximum_mw: u32, + published: Option<(u32, u32)>, + pending: bool, + /// A cap is in force or its restore is still owed. Until then the status-config words are + /// neither latched nor written, so a GPU without a low-power cap keeps the firmware's own + /// (possibly changing) target untouched. + engaged: bool, +} + +impl PowerTarget { + pub(crate) const fn new() -> Self { + Self { maximum_mw: 0, published: None, pending: false, engaged: false } + } + + /// Returns `(target_mw, reason)` to publish for the requested CLPC cap (`0`: uncapped), + /// given the live status-config target `current_mw`. Nothing is written until a non-zero + /// cap below the firmware's target is requested; the write that restores that target ends + /// the engagement, so the uncapped state leaves the words alone again. + pub(crate) fn apply(&mut self, cap_mw: u32, current_mw: u32) -> Option<(u32, u32)> { + if !self.engaged { + if cap_mw == 0 || current_mw == 0 || cap_mw >= current_mw { + return None; + } + self.engaged = true; + self.maximum_mw = current_mw; + self.published = Some((current_mw, POWER_TARGET_REASON_RESTORE)); + } else if let Some((published_mw, _)) = self.published { + // The live word no longer holds what was last published (for example after the + // firmware's initialization data was set up again on wake or recovery). + if current_mw != published_mw { + self.published = None; + } + } + let desired = if cap_mw > 0 && cap_mw < self.maximum_mw { + (cap_mw, POWER_TARGET_REASON_LOW_POWER) + } else { + (self.maximum_mw, POWER_TARGET_REASON_RESTORE) + }; + if desired.1 == POWER_TARGET_REASON_RESTORE { + // publish_failed() engages again if this write fails. + self.engaged = false; + } + if self.published == Some(desired) && !self.pending { + return None; + } + self.published = Some(desired); + self.pending = false; + Some(desired) + } + + /// Restore the firmware's target if a cap is in force or its restore is owed. + pub(crate) fn restore(&mut self, current_mw: u32) -> Option<(u32, u32)> { + self.apply(0, current_mw) + } + + pub(crate) fn publish_failed(&mut self) { + self.pending = true; + self.engaged = true; + } + + pub(crate) fn pending(&self) -> bool { + self.pending + } +} diff --git a/drivers/soc/apple/clpc.c b/drivers/soc/apple/clpc.c index 9f6ba95d0b073..62149beb77ce6 100644 --- a/drivers/soc/apple/clpc.c +++ b/drivers/soc/apple/clpc.c @@ -36,11 +36,13 @@ #include #include #include +#include #include #include #include #include #include +#include #include #include #include @@ -57,6 +59,7 @@ #define APPLE_CLPC_MAX_CLUSTERS 8 #define APPLE_CLPC_LEVELS 4 +#define APPLE_CLPC_MAX_ENERGY_REGS 32 #define APPLE_CLPC_CPG_PERF_BIT BIT_ULL(0) enum apple_clpc_rail { @@ -184,6 +187,8 @@ struct apple_clpc_hw { struct apple_clpc_cluster { unsigned int policy_cpu; cpumask_var_t cpus; + /* DT capacity-dmips-mhz of this cluster's CPUs (0 when absent) */ + u32 capacity_dmips; unsigned int busy; /* Busy share since the last package power reading the profile acted on */ unsigned int power_busy; @@ -215,6 +220,8 @@ struct apple_clpc_gpu { struct delayed_work *wake; /* Power cap in mW for the GPU's own budget, 0 for none (READ_ONCE) */ unsigned int cap_mw; + /* Live GPU power draw in mW reported by the GPU driver (READ_ONCE) */ + unsigned int power_mw; /* * Reduction steps taken below the target (0 when uncapped or at the * target, up to APPLE_CLPC_GPU_CAP_MAX_LEVEL at the minimum cap), for @@ -330,6 +337,9 @@ struct apple_clpc { smc_key power_key; /* apple,low-power-gpu-cap: the limit caps the GPU's power budget first */ bool gpu_power_cap; + /* apple,low-power-capacity-ceiling: scale ceiling by capacity-dmips-mhz */ + bool low_power_capacity_ceiling; + u32 max_capacity_dmips; /* The performance profile is sent to the SMC as High Power mode */ bool high_power; /* apple,low-power-smc-notice: the low-power profile is sent to the SMC too */ @@ -341,6 +351,16 @@ struct apple_clpc { unsigned long power_next; unsigned long power_reads, power_updates; int power_mw; + int smc_power_mw; + /* Optional hardware CPU/cluster energy accumulators (apple,energy-monitor) */ + void __iomem *energy_regs[APPLE_CLPC_MAX_ENERGY_REGS]; + unsigned int nr_energy_regs; + u32 energy_pj_per_tick; + bool energy_valid; + bool energy_in_limit; + u64 energy_ticks; + u64 energy_ns; + int energy_mw; /* Per-CPU baselines for power_busy, taken at each package power reading */ u64 *power_idle; u64 *power_wall; @@ -418,6 +438,22 @@ void apple_clpc_gpu_clear_busy(struct apple_clpc_gpu *gpu) } EXPORT_SYMBOL_GPL(apple_clpc_gpu_clear_busy); +/** + * apple_clpc_gpu_set_power_mw() - Report live GPU power draw in milliwatts + * @gpu: the GPU input, from apple_clpc_gpu_get() + * @power_mw: GPU power draw in mW as reported by the GPU firmware, 0 when idle + * + * Added to hardware CPU energy measurements in the 100 ms low-power loop when + * apple,energy-monitor is configured. + */ +void apple_clpc_gpu_set_power_mw(struct apple_clpc_gpu *gpu, unsigned int power_mw) +{ + if (!gpu) + return; + WRITE_ONCE(gpu->power_mw, power_mw); +} +EXPORT_SYMBOL_GPL(apple_clpc_gpu_set_power_mw); + /** * apple_clpc_gpu_power_cap() - The GPU power the low-power profile allows * @gpu: the GPU input, from apple_clpc_gpu_get() @@ -462,6 +498,7 @@ void apple_clpc_gpu_put(struct apple_clpc_gpu *gpu) if (gpu) { apple_clpc_gpu_set_active(gpu, false); apple_clpc_gpu_clear_busy(gpu); + apple_clpc_gpu_set_power_mw(gpu, 0); kref_put(&gpu->ref, apple_clpc_gpu_free); } } @@ -779,8 +816,18 @@ static void apple_clpc_find_clusters(struct apple_clpc *clpc) if (clpc->clusters[i].policy_cpu == policy->cpu) break; if (i == clpc->nr_clusters && i < APPLE_CLPC_MAX_CLUSTERS) { + struct device_node *cpu_np = of_get_cpu_node(policy->cpu, NULL); + u32 dmips = 0; + + if (cpu_np) { + of_property_read_u32(cpu_np, "capacity-dmips-mhz", &dmips); + of_node_put(cpu_np); + } cl = &clpc->clusters[clpc->nr_clusters++]; cl->policy_cpu = policy->cpu; + cl->capacity_dmips = dmips; + if (dmips > clpc->max_capacity_dmips) + clpc->max_capacity_dmips = dmips; } if (i < clpc->nr_clusters) { cl = &clpc->clusters[i]; @@ -1039,7 +1086,8 @@ static void apple_clpc_arm_idle(struct apple_clpc *clpc) */ static bool apple_clpc_power_limited(const struct apple_clpc *clpc) { - return clpc->low_power_khz && clpc->low_power_mw && clpc->smc_np && + return clpc->low_power_khz && clpc->low_power_mw && + (clpc->smc_np || clpc->nr_energy_regs) && READ_ONCE(clpc->low_power); } @@ -1282,6 +1330,24 @@ static unsigned int apple_clpc_step_khz(struct cpufreq_policy *policy, return best; } +/* + * Scale @low_power_khz from the highest-capacity cluster's per-MHz throughput + * (capacity-dmips-mhz) to a cluster with @cl_dmips. A lower-IPC efficiency + * cluster needs a higher frequency for the same single-thread performance; if + * that exceeds its top OPP, apple_clpc_low_power_top_khz() leaves it at + * cpuinfo.max_freq so the package power limiter caps it only under load. + */ +static unsigned int apple_clpc_cluster_low_power_khz(unsigned int low_power_khz, + u32 cl_dmips, u32 max_dmips) +{ + u64 scaled; + + if (!low_power_khz || !cl_dmips || !max_dmips || cl_dmips >= max_dmips) + return low_power_khz; + scaled = DIV_ROUND_UP_ULL((u64)low_power_khz * max_dmips, cl_dmips); + return scaled > UINT_MAX ? UINT_MAX : (unsigned int)scaled; +} + /* * The low-power platform-profile frequency ceiling for @policy: the first * table frequency at or above @low_power_khz (matching macOS Low Power Mode's @@ -1342,6 +1408,124 @@ static int apple_clpc_read_power(struct apple_clpc *clpc) return exp >= 0 ? INT_MAX : mw >> -exp; } +static u64 apple_clpc_read_acc64(void __iomem *reg) +{ + u32 hi, lo, hi2; + + do { + hi = readl_relaxed(reg + 4); + lo = readl_relaxed(reg); + hi2 = readl_relaxed(reg + 4); + } while (hi != hi2); + return ((u64)hi << 32) | lo; +} + +/* + * Convert a hardware energy accumulator delta (in ticks at @pj_per_tick pJ + * each) over @delta_ns nanoseconds into milliwatts: 1 pJ / 1 ns = 1 mW. + * Returns -ENODATA on invalid window or counter reset/wrap. + */ +static int apple_clpc_energy_delta_mw(u64 prev_ticks, u64 cur_ticks, + u64 delta_ns, u32 pj_per_tick) +{ + u64 delta, mw; + + if (!delta_ns || !pj_per_tick || cur_ticks < prev_ticks) + return -ENODATA; + delta = cur_ticks - prev_ticks; + if (delta > div64_u64(U64_MAX, pj_per_tick)) + return INT_MAX; + mw = div64_u64(delta * pj_per_tick, delta_ns); + return mw > INT_MAX ? INT_MAX : (int)mw; +} + +static int apple_clpc_combine_power_mw(int hw_mw, int smc_mw) +{ + if (hw_mw >= 0 && smc_mw >= 0) + return max(hw_mw, smc_mw); + if (hw_mw >= 0) + return hw_mw; + return smc_mw; +} + +/* + * Choose the low-power loop's step (-1 down, 0 hold, +1 up) from the latest + * 100 ms hardware energy reading (@hw_mw) and 1 Hz SMC whole-SoC reading + * (@smc_mw, updated when @smc_fresh). + * + * When both sources are present, SMC updates once per second while the + * hardware monitor updates every 100 ms. Acting on a stale SMC reading on + * every 100 ms tick would step 10 times before SMC reflects the first step + * and oscillate. Instead: + * - on a fresh SMC reading, act once on max(hw_mw, smc_mw) (whole SoC); + * - between SMC updates, let a fresh hardware burst above @target_mw step + * down immediately (each 100 ms window sees the new frequency right away), + * but do not step up until SMC confirms whole-SoC power is below 90%; + * - without an SMC reading (@smc_mw < 0), @hw_mw drives both directions. + */ +static int apple_clpc_power_step(int hw_mw, int smc_mw, bool smc_fresh, + unsigned int target_mw, int *out_mw, + bool *out_fresh) +{ + int mw = apple_clpc_combine_power_mw(hw_mw, smc_mw); + int step = 0; + bool fresh = false; + + *out_mw = mw; + if (smc_fresh) { + fresh = true; + if (mw > (int)target_mw) + step = -1; + else if (mw < (int)target_mw * 9 / 10) + step = 1; + } else if (hw_mw >= 0) { + if (smc_mw < 0) { + fresh = true; + if (hw_mw > (int)target_mw) + step = -1; + else if (hw_mw < (int)target_mw * 9 / 10) + step = 1; + } else if (hw_mw > (int)target_mw) { + fresh = true; + step = -1; + } + } + *out_fresh = fresh; + return step; +} + +/* Hardware CPU/cluster energy over the last window plus live GPU power, in mW. */ +static int apple_clpc_read_energy_mw(struct apple_clpc *clpc) +{ + u64 ticks = 0, now_ns; + unsigned int i, gpu_mw = 0; + int cpu_mw; + + if (!clpc->nr_energy_regs || !clpc->energy_pj_per_tick) + return -ENODEV; + for (i = 0; i < clpc->nr_energy_regs; i++) { + ticks += apple_clpc_read_acc64(clpc->energy_regs[i]); + ticks += apple_clpc_read_acc64(clpc->energy_regs[i] + 8); + } + now_ns = ktime_get_mono_fast_ns(); + if (!clpc->energy_valid || now_ns <= clpc->energy_ns) { + clpc->energy_ticks = ticks; + clpc->energy_ns = now_ns; + clpc->energy_valid = true; + return -EAGAIN; + } + cpu_mw = apple_clpc_energy_delta_mw(clpc->energy_ticks, ticks, + now_ns - clpc->energy_ns, + clpc->energy_pj_per_tick); + clpc->energy_ticks = ticks; + clpc->energy_ns = now_ns; + if (cpu_mw < 0) + return cpu_mw; + if (clpc->gpu) + gpu_mw = READ_ONCE(clpc->gpu->power_mw); + return min_t(u64, (u64)cpu_mw + gpu_mw, INT_MAX); +} + /* * Whether cluster a's ceiling takes the next step before cluster b's: down, * the higher ceiling (the faster cluster on a tie); up, the lower (the @@ -1486,19 +1670,26 @@ static void apple_clpc_profile_limit(struct apple_clpc *clpc) if (!clpc->low_power_khz || time_before(jiffies, clpc->power_next)) return; clpc->power_next = jiffies + msecs_to_jiffies(APPLE_CLPC_POWER_MS); + if (apple_clpc_power_limited(clpc) != clpc->energy_in_limit) { + clpc->energy_valid = false; + clpc->energy_mw = -1; + clpc->energy_in_limit = apple_clpc_power_limited(clpc); + } if (apple_clpc_power_limited(clpc)) { - mw = apple_clpc_read_power(clpc); + int smc_mw = clpc->smc_np ? apple_clpc_read_power(clpc) : -ENODEV; + int hw_mw = clpc->nr_energy_regs ? apple_clpc_read_energy_mw(clpc) : -ENODEV; + bool smc_fresh = smc_mw >= 0 && smc_mw != clpc->smc_power_mw; + clpc->power_reads++; - /* The SMC updates the reading less often: act on a new one only. */ - if (mw >= 0 && mw != clpc->power_mw) { + clpc->smc_power_mw = smc_mw; + clpc->energy_mw = hw_mw >= 0 ? hw_mw : -1; + step = apple_clpc_power_step(hw_mw, smc_mw, smc_fresh, + clpc->low_power_mw, &mw, &fresh); + if (fresh) clpc->power_updates++; - fresh = true; - if (mw > (int)clpc->low_power_mw) - step = -1; - else if (mw < (int)clpc->low_power_mw * 9 / 10) - step = 1; - } clpc->power_mw = mw; + } else { + clpc->smc_power_mw = -1; } step = apple_clpc_gpu_cap_down(clpc, step); for (i = 0; i < clpc->nr_clusters; i++) { @@ -1520,8 +1711,17 @@ static void apple_clpc_profile_limit(struct apple_clpc *clpc) freq_qos_add_request(&policy[i]->constraints, &cl->max_qos, FREQ_QOS_MAX, FREQ_QOS_MAX_DEFAULT_VALUE) < 0) clpc->update_errors++; - cl->top_khz = apple_clpc_low_power_top_khz(policy[i], - clpc->low_power_khz); + { + unsigned int target_khz = clpc->low_power_khz; + + if (clpc->low_power_capacity_ceiling && + apple_clpc_power_limited(clpc)) + target_khz = apple_clpc_cluster_low_power_khz( + target_khz, cl->capacity_dmips, + clpc->max_capacity_dmips); + cl->top_khz = apple_clpc_low_power_top_khz(policy[i], + target_khz); + } if (!low) cl->max_khz = 0; else if (!cl->max_khz || !clpc->low_power_mw || @@ -1870,14 +2070,27 @@ static int apple_clpc_status_show(struct seq_file *s, void *unused) READ_ONCE(clpc->cpg_keepalive_transitions)); if (clpc->low_power_khz) { int power_mw = clpc->power_mw; + int energy_mw = clpc->energy_mw; - if (!clpc->low_power_mw && clpc->smc_np) { + if ((!clpc->low_power_mw && clpc->smc_np) || + (!apple_clpc_power_limited(clpc) && clpc->nr_energy_regs)) { mutex_lock(&clpc->sample_lock); if (!READ_ONCE(clpc->stopped)) { - int mw = apple_clpc_read_power(clpc); + if (!clpc->low_power_mw && clpc->smc_np) { + int mw = apple_clpc_read_power(clpc); - if (mw >= 0) - power_mw = mw; + if (mw >= 0) + power_mw = mw; + } + if (!apple_clpc_power_limited(clpc) && + clpc->nr_energy_regs) { + int mw = apple_clpc_read_energy_mw(clpc); + + if (mw >= 0) { + clpc->energy_mw = mw; + energy_mw = mw; + } + } } mutex_unlock(&clpc->sample_lock); } @@ -1895,6 +2108,11 @@ static int apple_clpc_status_show(struct seq_file *s, void *unused) (char)(clpc->power_key >> 8), (char)clpc->power_key, clpc->low_power_mw, clpc->gpu ? READ_ONCE(clpc->gpu->cap_mw) : 0); + if (clpc->nr_energy_regs) + seq_printf(s, "energy monitor: %d mW (%u windows, %u pJ/tick) gpu power %u mW\n", + energy_mw, clpc->nr_energy_regs, + clpc->energy_pj_per_tick, + clpc->gpu ? READ_ONCE(clpc->gpu->power_mw) : 0); } if (clpc->high_power || clpc->low_power_notice) seq_printf(s, "smc power mode: high power %s, low power %s (%u records sent)\n", @@ -2284,6 +2502,7 @@ static int apple_clpc_profile_set(struct device *dev, enum platform_profile_opti for (i = 0; i < clpc->nr_clusters; i++) clpc->clusters[i].max_khz = 0; clpc->power_mw = -1; + clpc->smc_power_mw = -1; } /* Apply profile ceilings right away so userspace sees the change immediately. */ clpc->power_next = jiffies; @@ -2423,6 +2642,52 @@ static void apple_clpc_put_smc_np(void *data) of_node_put(clpc->smc_np); } +static void apple_clpc_init_energy_monitor(struct apple_clpc *clpc, struct device *dev) +{ + struct device_node *en_np; + struct resource res; + unsigned int idx; + u32 pj = 0; + + en_np = of_parse_phandle(dev->of_node, "apple,energy-monitor", 0); + if (!en_np) + return; + if (!of_device_is_available(en_np)) { + of_node_put(en_np); + return; + } + if (of_property_read_u32(en_np, "apple,picojoules-per-tick", &pj) || !pj) { + dev_warn(dev, "energy monitor missing apple,picojoules-per-tick\n"); + of_node_put(en_np); + return; + } + for (idx = 0; idx < APPLE_CLPC_MAX_ENERGY_REGS; idx++) { + void __iomem *base; + + if (of_address_to_resource(en_np, idx, &res)) + break; + if (resource_size(&res) < 16) { + dev_warn(dev, "energy monitor reg %u too small (%pa)\n", + idx, &res.start); + clpc->nr_energy_regs = 0; + of_node_put(en_np); + return; + } + /* Maps non-posted when the bus asks for it (nonposted-mmio on /soc). */ + base = devm_ioremap_resource(dev, &res); + if (IS_ERR(base)) { + dev_warn(dev, "energy monitor reg %u ioremap failed\n", idx); + clpc->nr_energy_regs = 0; + of_node_put(en_np); + return; + } + clpc->energy_regs[clpc->nr_energy_regs++] = base; + } + of_node_put(en_np); + if (clpc->nr_energy_regs) + clpc->energy_pj_per_tick = pj; +} + static int apple_clpc_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; @@ -2505,7 +2770,13 @@ static int apple_clpc_probe(struct platform_device *pdev) } clpc->gpu_power_cap = of_property_read_bool(dev->of_node, "apple,low-power-gpu-cap"); + clpc->low_power_capacity_ceiling = + of_property_read_bool(dev->of_node, + "apple,low-power-capacity-ceiling"); clpc->power_mw = -1; + clpc->smc_power_mw = -1; + clpc->energy_mw = -1; + apple_clpc_init_energy_monitor(clpc, dev); clpc->high_power = clpc->smc_np && high_power; clpc->low_power_notice = clpc->smc_np && clpc->low_power_khz && of_property_read_bool(dev->of_node, "apple,low-power-smc-notice"); @@ -2753,6 +3024,9 @@ static int apple_clpc_resume(struct device *dev) * act on the first reading after the wake. */ clpc->power_mw = -1; + clpc->smc_power_mw = -1; + clpc->energy_mw = -1; + clpc->energy_valid = false; for (i = 0; i < clpc->nr_clusters; i++) clpc->clusters[i].max_khz = 0; if (clpc->gpu && READ_ONCE(clpc->gpu->cap_mw)) { @@ -4271,12 +4545,16 @@ static void apple_clpc_gpu_busy_clear_test(struct kunit *test) KUNIT_EXPECT_EQ(test, demand[APPLE_CLPC_DCS], 5u); KUNIT_EXPECT_EQ(test, demand[APPLE_CLPC_SOC], 3u); - /* Releasing the consumer clears both activity and busy_valid. */ + /* Releasing the consumer clears activity, busy_valid, and reported GPU power. */ kref_get(&gpu->ref); apple_clpc_gpu_set_busy(gpu, 15); + apple_clpc_gpu_set_power_mw(gpu, 4200); + apple_clpc_gpu_set_active(gpu, false); + KUNIT_EXPECT_EQ(test, READ_ONCE(gpu->power_mw), 4200u); apple_clpc_gpu_put(gpu); KUNIT_EXPECT_FALSE(test, gpu->active); KUNIT_EXPECT_FALSE(test, gpu->busy_valid); + KUNIT_EXPECT_EQ(test, READ_ONCE(gpu->power_mw), 0u); kref_put(&gpu->ref, apple_clpc_gpu_free); } @@ -4341,6 +4619,107 @@ static void apple_clpc_t6050_gpu_fabric_test(struct kunit *test) kref_put(&gpu->ref, apple_clpc_gpu_free); } +static void apple_clpc_capacity_ceiling_test(struct kunit *test) +{ + struct cpufreq_frequency_table e_table[] = { + { .frequency = 1020000 }, + { .frequency = 2352000 }, + { .frequency = 2964000 }, + { .frequency = CPUFREQ_TABLE_END }, + }; + struct cpufreq_frequency_table p_table[] = { + { .frequency = 1260000 }, + { .frequency = 2220000 }, + { .frequency = 4464000 }, + { .frequency = CPUFREQ_TABLE_END }, + }; + struct cpufreq_policy e_pol = { + .freq_table = e_table, + .cpuinfo = { .min_freq = 1020000, .max_freq = 2964000 }, + }; + struct cpufreq_policy p_pol = { + .freq_table = p_table, + .cpuinfo = { .min_freq = 1260000, .max_freq = 4464000 }, + }; + unsigned int target; + + /* P-cluster (1024/1024) stays at 2220 MHz. */ + target = apple_clpc_cluster_low_power_khz(2220000, 1024, 1024); + KUNIT_EXPECT_EQ(test, target, 2220000u); + KUNIT_EXPECT_EQ(test, apple_clpc_low_power_top_khz(&p_pol, target), 2220000u); + + /* E-cluster (671 vs 1024) needs 3388 MHz (> 2964 max) -> uncapped at 2964 MHz. */ + target = apple_clpc_cluster_low_power_khz(2220000, 671, 1024); + KUNIT_EXPECT_GT(test, target, 2964000u); + KUNIT_EXPECT_EQ(test, apple_clpc_low_power_top_khz(&e_pol, target), 2964000u); + + /* Missing capacity metadata falls back to the raw frequency ceiling. */ + KUNIT_EXPECT_EQ(test, apple_clpc_cluster_low_power_khz(2220000, 0, 1024), 2220000u); + KUNIT_EXPECT_EQ(test, apple_clpc_cluster_low_power_khz(2220000, 671, 0), 2220000u); +} + +static void apple_clpc_energy_power_test(struct kunit *test) +{ + int mw; + bool fresh; + + /* 4e9 ticks at 25 pJ/tick over 100 ms (1e8 ns) = 1000 mW exactly. */ + KUNIT_EXPECT_EQ(test, + apple_clpc_energy_delta_mw(1000, 1000 + 4000000000ULL, + 100000000ULL, 25), + 1000); + /* 20e9 ticks at 25 pJ/tick over 100 ms = 5000 mW. */ + KUNIT_EXPECT_EQ(test, + apple_clpc_energy_delta_mw(0, 20000000000ULL, + 100000000ULL, 25), + 5000); + /* Counter reset/wrap or zero window yields -ENODATA. */ + KUNIT_EXPECT_EQ(test, apple_clpc_energy_delta_mw(500, 499, 100000000ULL, 25), + -ENODATA); + KUNIT_EXPECT_EQ(test, apple_clpc_energy_delta_mw(0, 1000, 0, 25), + -ENODATA); + /* Combined power takes max(hw, smc) when both exist, else whichever is valid. */ + KUNIT_EXPECT_EQ(test, apple_clpc_combine_power_mw(5400, 4800), 5400); + KUNIT_EXPECT_EQ(test, apple_clpc_combine_power_mw(4100, 5600), 5600); + KUNIT_EXPECT_EQ(test, apple_clpc_combine_power_mw(4100, -ENODEV), 4100); + KUNIT_EXPECT_EQ(test, apple_clpc_combine_power_mw(-EAGAIN, 5200), 5200); + KUNIT_EXPECT_EQ(test, apple_clpc_combine_power_mw(-EAGAIN, -ENODEV), -ENODEV); + + /* Fresh 1 Hz SMC reading acts once in either direction or holds in the 90..100% band. */ + KUNIT_EXPECT_EQ(test, apple_clpc_power_step(3800, 5600, true, 5000, &mw, &fresh), -1); + KUNIT_EXPECT_TRUE(test, fresh); + KUNIT_EXPECT_EQ(test, mw, 5600); + KUNIT_EXPECT_EQ(test, apple_clpc_power_step(3800, 4750, true, 5000, &mw, &fresh), 0); + KUNIT_EXPECT_TRUE(test, fresh); + KUNIT_EXPECT_EQ(test, apple_clpc_power_step(3200, 4200, true, 5000, &mw, &fresh), 1); + KUNIT_EXPECT_TRUE(test, fresh); + + /* Stale SMC between 1 Hz updates must not oscillate in either direction. */ + KUNIT_EXPECT_EQ(test, apple_clpc_power_step(3800, 5600, false, 5000, &mw, &fresh), 0); + KUNIT_EXPECT_FALSE(test, fresh); + KUNIT_EXPECT_EQ(test, apple_clpc_power_step(3200, 3800, false, 5000, &mw, &fresh), 0); + KUNIT_EXPECT_FALSE(test, fresh); + + /* A fresh 100 ms hardware burst above target steps down at once despite stale low SMC. */ + KUNIT_EXPECT_EQ(test, apple_clpc_power_step(9000, 2800, false, 5000, &mw, &fresh), -1); + KUNIT_EXPECT_TRUE(test, fresh); + KUNIT_EXPECT_EQ(test, mw, 9000); + + /* Without SMC, hardware energy drives both down and up cleanly. */ + KUNIT_EXPECT_EQ(test, apple_clpc_power_step(6200, -ENODEV, false, 5000, &mw, &fresh), -1); + KUNIT_EXPECT_TRUE(test, fresh); + KUNIT_EXPECT_EQ(test, apple_clpc_power_step(4700, -ENODEV, false, 5000, &mw, &fresh), 0); + KUNIT_EXPECT_TRUE(test, fresh); + KUNIT_EXPECT_EQ(test, apple_clpc_power_step(3200, -ENODEV, false, 5000, &mw, &fresh), 1); + KUNIT_EXPECT_TRUE(test, fresh); + + /* Without energy monitor, only fresh SMC readings act. */ + KUNIT_EXPECT_EQ(test, apple_clpc_power_step(-ENODEV, 5600, false, 5000, &mw, &fresh), 0); + KUNIT_EXPECT_FALSE(test, fresh); + KUNIT_EXPECT_EQ(test, apple_clpc_power_step(-ENODEV, 5600, true, 5000, &mw, &fresh), -1); + KUNIT_EXPECT_TRUE(test, fresh); +} + static void apple_clpc_profile_reset_test(struct kunit *test) { struct apple_clpc *clpc = kunit_kzalloc(test, sizeof(*clpc), GFP_KERNEL); @@ -4399,6 +4778,8 @@ static struct kunit_case apple_clpc_policy_cases[] = { KUNIT_CASE(apple_clpc_profile_step_busy_test), KUNIT_CASE(apple_clpc_gpu_busy_clear_test), KUNIT_CASE(apple_clpc_t6050_gpu_fabric_test), + KUNIT_CASE(apple_clpc_capacity_ceiling_test), + KUNIT_CASE(apple_clpc_energy_power_test), KUNIT_CASE(apple_clpc_profile_reset_test), {} }; diff --git a/include/linux/soc/apple/clpc.h b/include/linux/soc/apple/clpc.h index 21893bdaa5e42..430fb0235f4e8 100644 --- a/include/linux/soc/apple/clpc.h +++ b/include/linux/soc/apple/clpc.h @@ -14,6 +14,7 @@ int apple_clpc_gpu_get(struct device *dev, struct apple_clpc_gpu **out); void apple_clpc_gpu_set_active(struct apple_clpc_gpu *gpu, bool active); void apple_clpc_gpu_set_busy(struct apple_clpc_gpu *gpu, unsigned int permille); void apple_clpc_gpu_clear_busy(struct apple_clpc_gpu *gpu); +void apple_clpc_gpu_set_power_mw(struct apple_clpc_gpu *gpu, unsigned int power_mw); unsigned int apple_clpc_gpu_power_cap(struct apple_clpc_gpu *gpu); unsigned int apple_clpc_gpu_power_cap_level(struct apple_clpc_gpu *gpu, unsigned int *max_level); @@ -31,6 +32,8 @@ static inline int apple_clpc_gpu_get(struct device *dev, struct apple_clpc_gpu * static inline void apple_clpc_gpu_set_active(struct apple_clpc_gpu *gpu, bool active) {} static inline void apple_clpc_gpu_set_busy(struct apple_clpc_gpu *gpu, unsigned int permille) {} static inline void apple_clpc_gpu_clear_busy(struct apple_clpc_gpu *gpu) {} +static inline void apple_clpc_gpu_set_power_mw(struct apple_clpc_gpu *gpu, + unsigned int power_mw) {} static inline unsigned int apple_clpc_gpu_power_cap(struct apple_clpc_gpu *gpu) { diff --git a/tools/asahi/clpc-gpu-demand-tests.py b/tools/asahi/clpc-gpu-demand-tests.py index 1dbabba1e1cb3..8f5ffadf5eaa4 100644 --- a/tools/asahi/clpc-gpu-demand-tests.py +++ b/tools/asahi/clpc-gpu-demand-tests.py @@ -401,8 +401,9 @@ def main(): struct apple_clpc_gpu { int lock; bool active; u64 updated_ns; u64 sequence; unsigned int busy; bool busy_valid; unsigned int level; unsigned long level_since; - void *wake; + void *wake; unsigned int power_mw; }; +#define WRITE_ONCE(x, v) ((x) = (v)) struct apple_clpc_ane { int lock; bool active, pending; }; #define spin_lock_irqsave(l, f) ((void)(l), (f) = 0) #define spin_unlock_irqrestore(l, f) ((void)(l), (void)(f)) @@ -451,6 +452,7 @@ def main(): unsigned int low_power_khz; unsigned int low_power_mw; void *smc_np; + unsigned int nr_energy_regs; atomic_t idle_armed; }; static unsigned long jiffies; diff --git a/tools/asahi/clpc-high-power-cleanup-tests.py b/tools/asahi/clpc-high-power-cleanup-tests.py index 476b505af8162..71b8477169731 100755 --- a/tools/asahi/clpc-high-power-cleanup-tests.py +++ b/tools/asahi/clpc-high-power-cleanup-tests.py @@ -86,6 +86,9 @@ def function(source, name): enum platform_profile_option profile; unsigned long power_next, ane_until; unsigned low_power_khz, low_power_mw, ane_qos_khz, nr_clusters, agent, mask, saved_floor; + unsigned nr_energy_regs; + /* the SMC's last power reading, -1 = none yet (reset on a low-power profile change) */ + int smc_power_mw; struct freq_qos_request ane_qos; struct cluster clusters[2]; struct vote vote[APPLE_CLPC_RAILS]; diff --git a/tools/asahi/g17-m5-governor-stop-tests.py b/tools/asahi/g17-m5-governor-stop-tests.py index 76a09b551905c..022e96daa6add 100755 --- a/tools/asahi/g17-m5-governor-stop-tests.py +++ b/tools/asahi/g17-m5-governor-stop-tests.py @@ -36,6 +36,8 @@ 'drop-stop-gate': ( MOD, ' if !self.primary.running || power::Control::crashed(self) {\n' + ' // No stale GPU power in CLPC\'s loop while the firmware is not running.\n' + ' self.port.set_power_mw(0);\n' ' return None;\n' ' }\n', ''), @@ -104,6 +106,7 @@ def read(path, old_ref): @CPU_ADVICE@ @GOVERNOR@ + @POWER_TARGET@ #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Call { Apply(CpuAdvice, bool), Stop } @@ -135,8 +138,15 @@ def read(path, old_ref): pub struct Effort { pub applied: u32 } impl Effort { fn applied(&self) -> u32 { self.applied } } -/// Region C's budget word and the power-policy block. -pub struct Init { pub word: AtomicU32, pub fail: AtomicBool, pub power: AtomicU32 } +/// Region C's budget word, the status-config power target, and the power-policy block. +pub struct Init { + pub word: AtomicU32, + pub fail: AtomicBool, + pub power: AtomicU32, + pub target_word: AtomicU32, + pub target_reason: AtomicU32, + pub target_fail: AtomicBool, +} impl Init { fn m5_power_budget(&self) -> Result { Ok(self.word.load(Ordering::Relaxed)) } fn m5_gpu_power_mw(&self) -> Result { Ok(self.power.load(Ordering::Relaxed)) } @@ -148,21 +158,35 @@ def read(path, old_ref): self.word.store(budget_mw, Ordering::Relaxed); Ok(()) } + fn m5_power_target(&self) -> Result { Ok(self.target_word.load(Ordering::Relaxed)) } + fn publish_m5_power_target(&self, target_mw: u32, reason: u32) -> Result<(), i32> { + if self.target_fail.load(Ordering::Relaxed) { + return Err(-5); + } + self.target_word.store(target_mw, Ordering::Relaxed); + self.target_reason.store(reason, Ordering::Relaxed); + Ok(()) + } } -/// The CLPC's low-power GPU power cap (0: none). -pub struct Port { pub cap: AtomicU32 } -impl Port { fn power_cap_mw(&self) -> u32 { self.cap.load(Ordering::Relaxed) } } +/// The CLPC's low-power GPU power cap (0: none) and live GPU power input. +pub struct Port { pub cap: AtomicU32, pub reported_power: AtomicU32 } +impl Port { + fn power_cap_mw(&self) -> u32 { self.cap.load(Ordering::Relaxed) } + fn set_power_mw(&self, power_mw: u32) { self.reported_power.store(power_mw, Ordering::Relaxed); } +} pub struct Firmware { pub port: Port, pub primary: Coprocessor, pub effort: Effort, pub governor: thermal::Governor, + pub power_target: thermal::PowerTarget, pub init: Init, } impl Firmware { @GOVERNOR_TICK@ + @APPLY_POWER_TARGET@ @PUBLISH_BUDGET@ } impl power::Control for Firmware { @@ -205,11 +229,19 @@ def read(path, old_ref): governor_activity_ns: AtomicU64::new(0), crashed: AtomicBool::new(false), }); let firmware = Firmware { - port: Port { cap: AtomicU32::new(0) }, + port: Port { cap: AtomicU32::new(0), reported_power: AtomicU32::new(0) }, primary: Coprocessor { running: true, state: Arc::new(RoleState { shared }) }, effort: Effort { applied: 0 }, governor: thermal::Governor::new(), - init: Init { word: AtomicU32::new(MAXIMUM), fail: AtomicBool::new(false), power: AtomicU32::new(45_000) }, + power_target: thermal::PowerTarget::new(), + init: Init { + word: AtomicU32::new(MAXIMUM), + fail: AtomicBool::new(false), + power: AtomicU32::new(45_000), + target_word: AtomicU32::new(24_240), + target_reason: AtomicU32::new(0), + target_fail: AtomicBool::new(false), + }, }; Arc::new(Shared { governor_armed: AtomicBool::new(true), @@ -322,6 +354,36 @@ def read(path, old_ref): fn a_crashed_firmware_hands_every_actuator_back() { stop_hands_everything_back(|fw| fw.primary.state.shared.crashed.store(true, Ordering::Release)); } + + #[test] + fn low_power_cap_drives_status_config_power_target_and_restores() { + let device = device(); + TARGET.store(0, Ordering::Relaxed); + firmware(&device, |fw| fw.port.cap.store(3_300, Ordering::Relaxed)); + assert!(busy(&device, 1)); + assert_eq!(word(&device), MAXIMUM, "Region C stays untouched when status-config owns the cap"); + assert_eq!(firmware(&device, |fw| fw.init.target_word.load(Ordering::Relaxed)), 3_300); + assert_eq!(firmware(&device, |fw| fw.init.target_reason.load(Ordering::Relaxed)), 0x3120_0003); + assert_eq!(firmware(&device, |fw| fw.port.reported_power.load(Ordering::Relaxed)), 45_000); + + // Simulated wake/recovery rewriting initdata back to maximum: re-publishes cap. + firmware(&device, |fw| fw.init.target_word.store(24_240, Ordering::Relaxed)); + assert!(busy(&device, 2)); + assert_eq!(firmware(&device, |fw| fw.init.target_word.load(Ordering::Relaxed)), 3_300); + + // Clearing the cap with a failed write retries until the maximum lands. + firmware(&device, |fw| { + fw.port.cap.store(0, Ordering::Relaxed); + fw.init.target_fail.store(true, Ordering::Relaxed); + }); + assert!(step(&device, 10), "failed restore keeps the work armed"); + assert_eq!(firmware(&device, |fw| fw.init.target_word.load(Ordering::Relaxed)), 3_300); + firmware(&device, |fw| fw.init.target_fail.store(false, Ordering::Relaxed)); + assert!(!step(&device, 11), "work stops once restore lands while idle"); + assert_eq!(firmware(&device, |fw| fw.init.target_word.load(Ordering::Relaxed)), 24_240); + assert_eq!(firmware(&device, |fw| fw.init.target_reason.load(Ordering::Relaxed)), 0x3000_001d); + assert_eq!(firmware(&device, |fw| fw.port.reported_power.load(Ordering::Relaxed)), 0); + } } ''' @@ -339,11 +401,19 @@ def build(mutation, old_ref): consts = re.findall(r'^(?:pub\([a-z]+\) )?const [A-Z0-9_]+: (?:u32|u64|i32|i64|usize) = [^;]+;$', thermal, re.M) publish = item(mod, ' fn publish_budget(&mut self') if 'fn publish_budget(&mut self' in mod else '' + apply_pt = item(mod, ' fn apply_power_target(&mut self') if 'fn apply_power_target(&mut self' in mod else '' + power_target = ( + item(thermal, 'pub(crate) struct PowerTarget {') + '\n' + item(thermal, '\nimpl PowerTarget {') + if 'pub(crate) struct PowerTarget {' in thermal + else 'pub(crate) struct PowerTarget; impl PowerTarget { pub(crate) const fn new() -> Self { Self } pub(crate) fn pending(&self) -> bool { false } }' + ) return (HARNESS .replace('@THERMAL_CONSTS@', '\n '.join(consts)) .replace('@CPU_ADVICE@', item(thermal, 'pub(crate) enum CpuAdvice {')) .replace('@GOVERNOR@', item(thermal, 'pub(crate) struct Governor {') + '\n' + item(thermal, '\nimpl Governor {')) + .replace('@POWER_TARGET@', power_target) + .replace('@APPLY_POWER_TARGET@', apply_pt) .replace('@PUBLISH_BUDGET@', publish) .replace('@GOVERNOR_TICK@', item(mod, ' fn governor_tick(&mut self')) .replace('@WORK_ITEM@', item(mod, 'impl WorkItem for Shared {')))