From cc2c3ed6e594ad59b7b98fd0f9e558454b15f480 Mon Sep 17 00:00:00 2001 From: Gava <21977618+broslife@users.noreply.github.com> Date: Wed, 4 Nov 2026 18:38:33 -0300 Subject: [PATCH 1/9] feat(probe): check 7 sets the CPU clock and logs what the system does Y at the start runs it alone. X, Y and B ask for 1785, 1224 and 1020 MHz; every change of the clocks, focus or mode becomes a line in probe-clock.log. Leaving does not restore the rate, so the next run shows what the system left. Co-Authored-By: Claude Opus 5.5 --- crates/pf-nx-probe/src/clock.rs | 181 ++++++++++++++++++++++++++++++++ crates/pf-nx-probe/src/main.rs | 9 ++ crates/pf-nx-probe/src/nx.rs | 8 ++ crates/pf-nx-sys/src/clk.rs | 27 +++++ 4 files changed, 225 insertions(+) create mode 100644 crates/pf-nx-probe/src/clock.rs diff --git a/crates/pf-nx-probe/src/clock.rs b/crates/pf-nx-probe/src/clock.rs new file mode 100644 index 0000000..89ba3bb --- /dev/null +++ b/crates/pf-nx-probe/src/clock.rs @@ -0,0 +1,181 @@ +//! Check 7: whether the title can set the CPU clock, and what the system does to it after. +//! +//! Y in the first seconds of a run starts it in place of the other checks. The tester asks for a +//! rate with a button, then sleeps, docks or leaves; every change of the clocks, focus or mode +//! becomes a line. The rate is never put back on the way out: the next run's first line shows +//! what the system left. Runs add to `probe-clock.log`, so one file holds a whole session. + +use std::fs::{File, OpenOptions}; +use std::io::Write; +use std::path::Path; +use std::sync::mpsc; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use pf_nx_sys::clk::{self, Clocks}; +use pf_nx_sys::{applet, hid, result_code}; + +use crate::{nx, Out}; + +/// `HidNpadButton`'s bits. +const BUTTON_B: u64 = 1 << 1; +const BUTTON_X: u64 = 1 << 2; +const BUTTON_Y: u64 = 1 << 3; +const BUTTON_PLUS: u64 = 1 << 10; + +/// The official top rate, a middle one for the menu, and the rate games run at. +const CPU_TOP_HZ: u32 = 1_785_000_000; +const CPU_MIDDLE_HZ: u32 = 1_224_000_000; +const CPU_STOCK_HZ: u32 = 1_020_000_000; + +const ASK_WINDOW: Duration = Duration::from_secs(5); +const FRAME: Duration = Duration::from_micros(16_667); +/// Between reads of the clocks: under the rate a sysmodule could rewrite them at, so a rewrite +/// shows as its own line. +const SAMPLE: Duration = Duration::from_millis(100); +/// A line with nothing new, so a quiet stretch reads as held and not as a stopped probe. +const BEAT: Duration = Duration::from_secs(10); + +/// Runs the check if Y comes within [`ASK_WINDOW`]; `true` once it ran. +pub fn run_if_asked(dir: &Path, out: &mut Out) -> bool { + let mut pads = match hid::Pads::init(1) { + Ok(pads) => pads, + Err(e) => { + out.line(&format!("probe 7 clock fail pads={e:#}")); + return false; + } + }; + out.line("Y now: clock test. Wait 5 s: all the other checks."); + let start = Instant::now(); + while start.elapsed() < ASK_WINDOW && applet::main_loop() { + if buttons(&mut pads) & BUTTON_Y != 0 { + run(dir, out, &mut pads); + return true; + } + nx::screen_flush(); + std::thread::sleep(FRAME); + } + false +} + +/// A line on the screen, in `probe.log` and in `probe-clock.log`. +struct Lines<'a> { + out: &'a mut Out, + file: Option, +} + +impl Lines<'_> { + fn say(&mut self, text: &str) { + let line = format!("probe 7 clock {} {text}", stamp()); + self.out.line(&line); + if let Some(file) = self.file.as_mut() { + let _ = writeln!(file, "{line}").and_then(|()| file.sync_data()); + } + } +} + +fn run(dir: &Path, out: &mut Out, pads: &mut hid::Pads) { + let file = OpenOptions::new() + .create(true) + .append(true) + .open(dir.join("probe-clock.log")) + .ok(); + let mut lines = Lines { out, file }; + let mut seen = clk::clocks(); + lines.say(&format!( + "start {:?} {:?} {:?} {}", + applet::applet_type(), + applet::operation_mode(), + applet::focus_state(), + show(seen) + )); + lines.say("X: CPU 1785. Y: CPU 1224. B: CPU 1020. Plus: leave without restoring."); + + let (tx, events) = mpsc::channel(); + let _hook = applet::hook(move |e| { + let _ = tx.send(e); + }); + let mut held = buttons(pads); + let mut sampled = Instant::now(); + let mut beat = Instant::now(); + while applet::main_loop() { + for event in events.try_iter() { + lines.say(&format!( + "event {event:?} {:?} {:?} {}", + applet::operation_mode(), + applet::focus_state(), + show(clk::clocks()) + )); + } + + let now = buttons(pads); + let pressed = now & !held; + held = now; + if pressed & BUTTON_PLUS != 0 { + lines.say(&format!("leave {}", show(clk::clocks()))); + return; + } + for (button, hz) in [ + (BUTTON_X, CPU_TOP_HZ), + (BUTTON_Y, CPU_MIDDLE_HZ), + (BUTTON_B, CPU_STOCK_HZ), + ] { + if pressed & button != 0 { + let answer = match clk::set_rate(clk::MODULE_CPU, hz) { + Ok(()) => "ok".to_owned(), + Err(rc) => format!("FAIL({})", result_code(rc)), + }; + lines.say(&format!("ask cpu={} {answer} {}", hz / 1_000_000, show(clk::clocks()))); + } + } + + if sampled.elapsed() >= SAMPLE { + sampled = Instant::now(); + let clocks = clk::clocks(); + if clocks != seen { + lines.say(&format!("change {} -> {}", show(seen), show(clocks))); + seen = clocks; + beat = Instant::now(); + } + } + if beat.elapsed() >= BEAT { + beat = Instant::now(); + lines.say(&format!("held {}", show(seen))); + } + nx::screen_flush(); + std::thread::sleep(FRAME); + } + lines.say("closed by the system"); +} + +/// The buttons down on player 1 or the handheld. +fn buttons(pads: &mut hid::Pads) -> u64 { + pads.update(); + pads.sample(0).map_or(0, |pad| pad.buttons) +} + +fn show(clocks: Option) -> String { + clocks.map_or_else( + || "clocks=unreadable".to_owned(), + |c| { + format!( + "cpu={} gpu={} emc={}", + c.cpu_hz / 1_000_000, + c.gpu_hz / 1_000_000, + c.emc_hz / 1_000_000 + ) + }, + ) +} + +/// The wall clock, UTC: unlike a monotonic count, it still runs through sleep. +fn stamp() -> String { + let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default(); + let secs = now.as_secs() % 86_400; + format!( + "{:02}:{:02}:{:02}.{:03}Z", + secs / 3600, + secs / 60 % 60, + secs % 60, + now.subsec_millis() + ) +} diff --git a/crates/pf-nx-probe/src/main.rs b/crates/pf-nx-probe/src/main.rs index 2b222a1..055ad5c 100644 --- a/crates/pf-nx-probe/src/main.rs +++ b/crates/pf-nx-probe/src/main.rs @@ -4,7 +4,10 @@ //! A check runs all its steps and lists each as `step=value` or `step=FAIL(why)`, so one run on //! the console names every failure. `--panic` ends the run with a panic: the hook writes //! `panic.txt`, and the next run prints it as `probe 1 panic-log`. Runs the same on a dev box. +//! On the console, Y in the first seconds runs check 7 alone (`clock`). +#[cfg(target_os = "horizon")] +mod clock; #[cfg(all(target_os = "horizon", feature = "nvdec"))] mod nvdec; #[cfg(target_os = "horizon")] @@ -55,6 +58,12 @@ fn main() { println!("probe 1 panic {} {text}", if wrote { "ok" } else { "fail" }); })); + #[cfg(target_os = "horizon")] + if clock::run_if_asked(&dir, &mut out) { + nx::leave(); + return; + } + out.check(1, "std", std_steps(&dir)); out.check(2, "sockets", socket_steps()); #[cfg(feature = "quic")] diff --git a/crates/pf-nx-probe/src/nx.rs b/crates/pf-nx-probe/src/nx.rs index be4180a..10612a0 100644 --- a/crates/pf-nx-probe/src/nx.rs +++ b/crates/pf-nx-probe/src/nx.rs @@ -73,3 +73,11 @@ pub fn finish() { } socket::exit(); } + +/// Tears down at once, for check 7: its last lines were read while it ran. +pub fn leave() { + if SCREEN.load(Ordering::Relaxed) { + console::exit(); + } + socket::exit(); +} diff --git a/crates/pf-nx-sys/src/clk.rs b/crates/pf-nx-sys/src/clk.rs index 707157b..e613cde 100644 --- a/crates/pf-nx-sys/src/clk.rs +++ b/crates/pf-nx-sys/src/clk.rs @@ -29,6 +29,7 @@ mod ffi { pub fn clkrstOpenSession(session_out: *mut ClkrstSession, module_id: u32, unk: u32) -> u32; pub fn clkrstCloseSession(session: *mut ClkrstSession); pub fn clkrstGetClockRate(session: *mut ClkrstSession, out_hz: *mut u32) -> u32; + pub fn clkrstSetClockRate(session: *mut ClkrstSession, hz: u32) -> u32; } } @@ -65,3 +66,29 @@ pub fn clocks() -> Option { unsafe { ffi::clkrstExit() }; c } + +/// Asks for `hz` on `module`, a `MODULE_*`. `Err` is the libnx result of the step that failed. +#[cfg(target_os = "horizon")] +pub fn set_rate(module: u32, hz: u32) -> Result<(), u32> { + // SAFETY: no arguments; balanced by clkrstExit. + let rc = unsafe { ffi::clkrstInitialize() }; + if rc != 0 { + return Err(rc); + } + let mut s = ClkrstSession::default(); + // SAFETY: clkrst is open; `s` receives the session. + let mut rc = unsafe { ffi::clkrstOpenSession(&mut s, module, 3) }; + if rc == 0 { + // SAFETY: `s` is the session just opened; closed right after. + rc = unsafe { ffi::clkrstSetClockRate(&mut s, hz) }; + // SAFETY: closes the session opened above. + unsafe { ffi::clkrstCloseSession(&mut s) }; + } + // SAFETY: balances the clkrstInitialize above. + unsafe { ffi::clkrstExit() }; + if rc == 0 { + Ok(()) + } else { + Err(rc) + } +} From 4dc5a99afefabc82ffba54da708ba6a596a08679 Mon Sep 17 00:00:00 2001 From: Gava <21977618+broslife@users.noreply.github.com> Date: Thu, 5 Nov 2026 19:08:38 -0300 Subject: [PATCH 2/9] feat(probe): check 7 asks the overclock module for the clock Horizon OC puts the CPU back to stock when no profile sets it, so a direct clkrst rate falls within 300 ms while the module runs. Its service and sys-clk's share the override command. The check finds which one runs, logs its versions, and A and R hold and release the CPU through it. Co-Authored-By: Claude Opus 5.5 --- crates/pf-nx-probe/src/clock.rs | 37 +++++++++++++++ crates/pf-nx-sys/build.rs | 3 +- crates/pf-nx-sys/csrc/pf_ocmod.c | 70 +++++++++++++++++++++++++++ crates/pf-nx-sys/src/lib.rs | 1 + crates/pf-nx-sys/src/ocmod.rs | 81 ++++++++++++++++++++++++++++++++ 5 files changed, 191 insertions(+), 1 deletion(-) create mode 100644 crates/pf-nx-sys/csrc/pf_ocmod.c create mode 100644 crates/pf-nx-sys/src/ocmod.rs diff --git a/crates/pf-nx-probe/src/clock.rs b/crates/pf-nx-probe/src/clock.rs index 89ba3bb..91f9241 100644 --- a/crates/pf-nx-probe/src/clock.rs +++ b/crates/pf-nx-probe/src/clock.rs @@ -4,6 +4,8 @@ //! rate with a button, then sleeps, docks or leaves; every change of the clocks, focus or mode //! becomes a line. The rate is never put back on the way out: the next run's first line shows //! what the system left. Runs add to `probe-clock.log`, so one file holds a whole session. +//! +//! X, Y and B set clkrst directly. A and R go through the overclock module, when one runs. use std::fs::{File, OpenOptions}; use std::io::Write; @@ -12,14 +14,17 @@ use std::sync::mpsc; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use pf_nx_sys::clk::{self, Clocks}; +use pf_nx_sys::ocmod::OcModule; use pf_nx_sys::{applet, hid, result_code}; use crate::{nx, Out}; /// `HidNpadButton`'s bits. +const BUTTON_A: u64 = 1 << 0; const BUTTON_B: u64 = 1 << 1; const BUTTON_X: u64 = 1 << 2; const BUTTON_Y: u64 = 1 << 3; +const BUTTON_R: u64 = 1 << 7; const BUTTON_PLUS: u64 = 1 << 10; /// The official top rate, a middle one for the menu, and the rate games run at. @@ -89,6 +94,7 @@ fn run(dir: &Path, out: &mut Out, pads: &mut hid::Pads) { show(seen) )); lines.say("X: CPU 1785. Y: CPU 1224. B: CPU 1020. Plus: leave without restoring."); + let module = find_module(&mut lines); let (tx, events) = mpsc::channel(); let _hook = applet::hook(move |e| { @@ -114,6 +120,16 @@ fn run(dir: &Path, out: &mut Out, pads: &mut hid::Pads) { lines.say(&format!("leave {}", show(clk::clocks()))); return; } + for (button, hz) in [(BUTTON_A, CPU_TOP_HZ), (BUTTON_R, 0)] { + if pressed & button != 0 { + let answer = match module.as_ref().map(|m| m.hold_cpu(hz)) { + Some(Ok(())) => "ok".to_owned(), + Some(Err(rc)) => format!("FAIL({})", result_code(rc)), + None => "no-module".to_owned(), + }; + lines.say(&format!("hold cpu={} {answer} {}", hz / 1_000_000, show(clk::clocks()))); + } + } for (button, hz) in [ (BUTTON_X, CPU_TOP_HZ), (BUTTON_Y, CPU_MIDDLE_HZ), @@ -147,6 +163,27 @@ fn run(dir: &Path, out: &mut Out, pads: &mut hid::Pads) { lines.say("closed by the system"); } +/// The overclock module that runs, named in a line with its versions. +fn find_module(lines: &mut Lines) -> Option { + let module = match OcModule::find() { + Ok(module) => module, + Err(rc) => { + lines.say(&format!("module FAIL({})", result_code(rc))); + return None; + } + }; + let Some(found) = module else { + lines.say("module none"); + return None; + }; + match found.info() { + Ok((api, version)) => lines.say(&format!("module {} api={api} version={version}", found.service())), + Err(rc) => lines.say(&format!("module {} info=FAIL({})", found.service(), result_code(rc))), + } + lines.say("A: module holds CPU 1785. R: module lets go."); + module +} + /// The buttons down on player 1 or the handheld. fn buttons(pads: &mut hid::Pads) -> u64 { pads.update(); diff --git a/crates/pf-nx-sys/build.rs b/crates/pf-nx-sys/build.rs index 0dced81..9500438 100644 --- a/crates/pf-nx-sys/build.rs +++ b/crates/pf-nx-sys/build.rs @@ -1,4 +1,4 @@ -//! On the console target: builds `csrc/pf_swkbd.c`, and `csrc/pf_av.c` with `av`, and links libnx, newlib, the pinned libavcodec and +//! On the console target: builds `csrc/pf_swkbd.c` and `csrc/pf_ocmod.c`, and `csrc/pf_av.c` with `av`, and links libnx, newlib, the pinned libavcodec and //! NVK. On Linux with `av`: the same shim against the system's libavcodec, which decodes in //! software for the dev box. Elsewhere: nothing. `cfg(pf_av)` says the shim is linked. @@ -28,6 +28,7 @@ fn main() { println!("cargo:rustc-cfg=pf_av"); } build_shim(&dkp, &portlibs, "pf_swkbd"); + build_shim(&dkp, &portlibs, "pf_ocmod"); let nvk = PathBuf::from(env::var_os("PF_NX_NVK_LIB").unwrap_or_else(|| "/opt/pf-nx/nvk/lib".into())); if nvk_on && !nvk.join("libvulkan_bh.a").is_file() { diff --git a/crates/pf-nx-sys/csrc/pf_ocmod.c b/crates/pf-nx-sys/csrc/pf_ocmod.c new file mode 100644 index 0000000..8740f49 --- /dev/null +++ b/crates/pf-nx-sys/csrc/pf_ocmod.c @@ -0,0 +1,70 @@ +// The overclock module's IPC, for src/ocmod.rs. libnx's dispatch calls are inline, so they stay on +// this side. sys-clk and Horizon OC share commands 0, 1 and 8 under different service names. +#include + +#define CMD_API_VERSION 0 +#define CMD_VERSION_STRING 1 +#define CMD_SET_OVERRIDE 8 +// Atmosphère's sm extension. +#define SM_HAS_SERVICE 65100 + +// Whether `name` is registered, in `out`. smGetService on a missing name waits for it for good, +// so this comes first. +uint32_t pf_ocmod_has(const char *name, uint8_t *out) { + Result rc = smInitialize(); + if (R_FAILED(rc)) { + return rc; + } + SmServiceName encoded = smEncodeName(name); + if (hosversionAtLeast(12, 0, 0)) { + rc = tipcDispatchInOut(smGetServiceSessionTipc(), SM_HAS_SERVICE, encoded, *out); + } else { + rc = serviceDispatchInOut(smGetServiceSession(), SM_HAS_SERVICE, encoded, *out); + } + smExit(); + return rc; +} + +static Result open_module(const char *name, Service *srv) { + Result rc = smInitialize(); + if (R_FAILED(rc)) { + return rc; + } + rc = smGetService(srv, name); + smExit(); + return rc; +} + +// The module's API version and its version string, NUL-terminated in `version`. +uint32_t pf_ocmod_info(const char *name, uint32_t *api, char *version, size_t version_len) { + Service srv; + Result rc = open_module(name, &srv); + if (R_FAILED(rc)) { + return rc; + } + rc = serviceDispatchOut(&srv, CMD_API_VERSION, *api); + if (R_SUCCEEDED(rc)) { + rc = serviceDispatch(&srv, CMD_VERSION_STRING, + .buffer_attrs = { SfBufferAttr_HipcAutoSelect | SfBufferAttr_Out }, + .buffers = { { version, version_len } }, + ); + } + serviceClose(&srv); + return rc; +} + +// Asks the module to hold `module` at `hz`; 0 hands the clock back. +uint32_t pf_ocmod_override(const char *name, uint32_t module, uint32_t hz) { + Service srv; + Result rc = open_module(name, &srv); + if (R_FAILED(rc)) { + return rc; + } + const struct { + uint32_t module; + uint32_t hz; + } args = { module, hz }; + rc = serviceDispatchIn(&srv, CMD_SET_OVERRIDE, args); + serviceClose(&srv); + return rc; +} diff --git a/crates/pf-nx-sys/src/lib.rs b/crates/pf-nx-sys/src/lib.rs index 344aa28..bd1c3fb 100644 --- a/crates/pf-nx-sys/src/lib.rs +++ b/crates/pf-nx-sys/src/lib.rs @@ -24,6 +24,7 @@ pub mod hid; pub mod mem; #[cfg(all(target_os = "horizon", feature = "nvk"))] pub mod nvk; +pub mod ocmod; pub mod pl; pub mod random; #[cfg(target_os = "horizon")] diff --git a/crates/pf-nx-sys/src/ocmod.rs b/crates/pf-nx-sys/src/ocmod.rs new file mode 100644 index 0000000..6503216 --- /dev/null +++ b/crates/pf-nx-sys/src/ocmod.rs @@ -0,0 +1,81 @@ +//! The overclock module a player may run, through `csrc/pf_ocmod.c`. A module that sees the clock +//! change under it can put it back (Horizon OC does, with no profile set), so while one runs the +//! title asks it for the rate instead of setting clkrst itself. + +#[cfg(target_os = "horizon")] +use core::ffi::{c_char, CStr}; + +/// `HocClkModule_CPU`, `SysClkModule_CPU`. +#[cfg(target_os = "horizon")] +const MODULE_CPU: u32 = 0; + +/// Horizon OC's service, then sys-clk's and its forks'. +#[cfg(target_os = "horizon")] +const SERVICES: [&CStr; 2] = [c"hoc:clk", c"sys:clk"]; + +#[cfg(target_os = "horizon")] +mod ffi { + use core::ffi::c_char; + + extern "C" { + pub fn pf_ocmod_has(name: *const c_char, out: *mut u8) -> u32; + pub fn pf_ocmod_info(name: *const c_char, api: *mut u32, version: *mut c_char, version_len: usize) -> u32; + pub fn pf_ocmod_override(name: *const c_char, module: u32, hz: u32) -> u32; + } +} + +/// A running overclock module. +#[cfg(target_os = "horizon")] +#[derive(Clone, Copy, Debug)] +pub struct OcModule { + service: &'static CStr, +} + +#[cfg(target_os = "horizon")] +impl OcModule { + /// The module that is running, if one is. `Err` is the libnx result when sm could not say. + pub fn find() -> Result, u32> { + for service in SERVICES { + let mut has = 0u8; + // SAFETY: `service` is NUL-terminated and `has` is a writable byte. + let rc = unsafe { ffi::pf_ocmod_has(service.as_ptr(), &mut has) }; + if rc != 0 { + return Err(rc); + } + if has != 0 { + return Ok(Some(Self { service })); + } + } + Ok(None) + } + + pub fn service(&self) -> &'static str { + self.service.to_str().unwrap_or("?") + } + + /// Its API version and version string. + pub fn info(&self) -> Result<(u32, String), u32> { + let mut api = 0u32; + let mut version = [0 as c_char; 64]; + // SAFETY: `service` is NUL-terminated; `api` and `version` are writable for their sizes. + let rc = unsafe { ffi::pf_ocmod_info(self.service.as_ptr(), &mut api, version.as_mut_ptr(), version.len()) }; + if rc != 0 { + return Err(rc); + } + // The module may fill the buffer without a NUL. + version[version.len() - 1] = 0; + // SAFETY: NUL-terminated by the line above; `version` outlives the borrow. + let text = unsafe { CStr::from_ptr(version.as_ptr()) }; + Ok((api, text.to_string_lossy().into_owned())) + } + + /// Asks it to hold the CPU at `hz`; 0 hands the clock back. It lives in the module's memory + /// until then, past the title's exit. + pub fn hold_cpu(&self, hz: u32) -> Result<(), u32> { + // SAFETY: `service` is NUL-terminated; the rest are plain values. + match unsafe { ffi::pf_ocmod_override(self.service.as_ptr(), MODULE_CPU, hz) } { + 0 => Ok(()), + rc => Err(rc), + } + } +} From 4ccb10dc6eda905addd89fa6f505031d73d15163 Mon Sep 17 00:00:00 2001 From: Gava <21977618+broslife@users.noreply.github.com> Date: Fri, 6 Nov 2026 20:35:49 -0300 Subject: [PATCH 3/9] feat: the title holds its clocks for the menu and the stream The menu holds CPU 1428, GPU 422.4 in handheld and memory 1600; the stream holds CPU 1785 and memory 1600 and leaves the GPU to the system. A running sys-clk or Horizon OC takes the ask, since it undoes clkrst; without one the title sets clkrst and asks again when the clocks move. A module's hold outlives the title, so Lifecycle::exit and the panic hook hand the clocks back, and the first stage replaces what a hard crash left. Co-Authored-By: Claude Opus 5.5 --- crates/pf-nx-app/src/platform/fake.rs | 9 +- crates/pf-nx-app/src/platform/mod.rs | 67 +++++++ crates/pf-nx-app/src/runtime/mod.rs | 33 +++- crates/pf-nx-app/tests/seams.rs | 10 +- crates/pf-nx-platform/src/console/clocks.rs | 167 ++++++++++++++++++ .../pf-nx-platform/src/console/lifecycle.rs | 23 ++- crates/pf-nx-platform/src/console/mod.rs | 1 + crates/pf-nx-probe/src/clock.rs | 4 +- crates/pf-nx-sys/src/ocmod.rs | 15 +- docs/NOTES.md | 7 + 10 files changed, 314 insertions(+), 22 deletions(-) create mode 100644 crates/pf-nx-platform/src/console/clocks.rs diff --git a/crates/pf-nx-app/src/platform/fake.rs b/crates/pf-nx-app/src/platform/fake.rs index 3b8b333..b466e7c 100644 --- a/crates/pf-nx-app/src/platform/fake.rs +++ b/crates/pf-nx-app/src/platform/fake.rs @@ -8,8 +8,8 @@ use std::sync::{Arc, Mutex}; use anyhow::Result; use super::{ - AudioOut, AudioPort, Display, Fit, FrameReport, Lifecycle, Motion, PadFeedback, PadSample, Pads, Refresh, Rgba, - Storage, StreamSpec, SystemEvent, TouchPoint, VideoDecoders, + AudioOut, AudioPort, ClockStage, Display, Fit, FrameReport, Lifecycle, Motion, PadFeedback, PadSample, Pads, + Refresh, Rgba, Storage, StreamSpec, SystemEvent, TouchPoint, VideoDecoders, }; use crate::core::caps::VideoCaps; use crate::core::media::{VideoSink, VideoSinkCaps}; @@ -240,6 +240,7 @@ impl Storage for FakeStorage { pub struct FakeLifecycle { pub events: Arc>>, pub splash_hidden: Arc>, + pub clock_stages: Arc>>, } impl Lifecycle for FakeLifecycle { @@ -251,6 +252,10 @@ impl Lifecycle for FakeLifecycle { out.extend(self.events.lock().expect("fake lifecycle poisoned").drain(..)); } + fn set_clock_stage(&mut self, stage: ClockStage) { + self.clock_stages.lock().expect("fake lifecycle poisoned").push(stage); + } + fn exit(&self) -> ! { panic!("title exited"); } diff --git a/crates/pf-nx-app/src/platform/mod.rs b/crates/pf-nx-app/src/platform/mod.rs index 129938c..3a152b3 100644 --- a/crates/pf-nx-app/src/platform/mod.rs +++ b/crates/pf-nx-app/src/platform/mod.rs @@ -342,6 +342,14 @@ pub trait Lifecycle { None } + /// Holds the clocks for `stage`. [`Self::exit`] hands them back. + fn set_clock_stage(&mut self, _stage: ClockStage) {} + + /// Hands the clocks back from any thread, for a panic, which never reaches [`Self::exit`]. + fn clock_release(&self) -> Option { + None + } + /// Shows the system's keyboard over the title and blocks until the player closes it: the /// text they confirmed, or `None` when they cancelled or there is no such keyboard. fn keyboard(&mut self) -> Option { @@ -401,6 +409,41 @@ impl SocketCalls { } } +/// What the title is doing, for the clocks it holds. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ClockStage { + Menu, + Stream, +} + +/// The rates a stage holds, in Hz. `None` leaves that clock to the system. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ClockTargets { + pub cpu_hz: Option, + pub gpu_hz: Option, + pub emc_hz: Option, +} + +impl ClockStage { + /// The menu's rates keep it near 60 fps for under a watt. The stream needs the CPU: it cuts + /// the receive path and the VIC transfer, and the GPU adds little there. Docked, the system's + /// GPU rate is already above the menu's, so the GPU stays the system's. + pub fn targets(self, mode: OperationMode) -> ClockTargets { + match self { + Self::Menu => ClockTargets { + cpu_hz: Some(1_428_000_000), + gpu_hz: (mode == OperationMode::Handheld).then_some(422_400_000), + emc_hz: Some(1_600_000_000), + }, + Self::Stream => ClockTargets { + cpu_hz: Some(1_785_000_000), + gpu_hz: None, + emc_hz: Some(1_600_000_000), + }, + } + } +} + /// The CPU, GPU and memory clocks, in Hz. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Clocks { @@ -421,3 +464,27 @@ impl std::fmt::Display for Clocks { ) } } + +#[cfg(test)] +mod clock_tests { + use super::{ClockStage, OperationMode}; + + #[test] + fn the_menu_raises_the_gpu_only_in_handheld() { + assert_eq!( + ClockStage::Menu.targets(OperationMode::Handheld).gpu_hz, + Some(422_400_000) + ); + assert_eq!(ClockStage::Menu.targets(OperationMode::Docked).gpu_hz, None); + } + + #[test] + fn the_stream_leaves_the_gpu_and_stays_in_the_official_limits() { + for mode in [OperationMode::Handheld, OperationMode::Docked] { + let stream = ClockStage::Stream.targets(mode); + assert_eq!(stream.cpu_hz, Some(1_785_000_000)); + assert_eq!(stream.gpu_hz, None); + assert_eq!(stream.emc_hz, Some(1_600_000_000)); + } + } +} diff --git a/crates/pf-nx-app/src/runtime/mod.rs b/crates/pf-nx-app/src/runtime/mod.rs index df91fd2..6548d5a 100644 --- a/crates/pf-nx-app/src/runtime/mod.rs +++ b/crates/pf-nx-app/src/runtime/mod.rs @@ -13,10 +13,11 @@ pub mod testrun; mod touch; use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::OnceLock; use std::time::Instant; use crate::core::model::bitrate_max_kbps; -use crate::platform::{Display, Lifecycle, Pads, Platform, SocketCalls, SystemEvent}; +use crate::platform::{ClockStage, Display, Lifecycle, Pads, Platform, SocketCalls, SystemEvent}; use crate::services::power::ExitPlan; use crate::services::store; use crate::session::{self, Media}; @@ -107,13 +108,16 @@ pub fn run(platform: Platform) -> ! { audio, pads, storage, - lifecycle, + mut lifecycle, log, device, } = platform; crate::services::paths::install(storage.data_dir()); // Without a log there is nothing to diagnose a failure from; the title still runs. let flush = crate::logger::init_subscriber(&crate::services::paths::logs_dir(), log).ok(); + if let Some(release) = lifecycle.clock_release() { + let _ = CLOCK_RELEASE.set(release); + } install_panic_hook(); let language = pf_l10n::set_languages(&device.languages); tracing::info!( @@ -128,6 +132,7 @@ pub fn run(platform: Platform) -> ! { ); tracing::info!("language {language} for the system's {:?}", device.languages); punktfunk_core::client::set_client_label(&client_label(&device)); + lifecycle.set_clock_stage(ClockStage::Menu); crate::core::caps::install(video.caps()); // ureq's agents resolve their provider from the process default and panic without one. punktfunk_core::tls::install_default_provider(); @@ -190,10 +195,16 @@ fn alternate(app: &mut App) -> Option { }; match outcome { UiOutcome::Quit(plan) => return plan, - UiOutcome::Launch(launch) => match stream::run(app, *launch) { - StreamOutcome::ReturnToMenu(why) => notice = why, - StreamOutcome::Quit(plan) => return plan, - }, + UiOutcome::Launch(launch) => { + app.lifecycle.set_clock_stage(ClockStage::Stream); + match stream::run(app, *launch) { + StreamOutcome::ReturnToMenu(why) => { + app.lifecycle.set_clock_stage(ClockStage::Menu); + notice = why; + } + StreamOutcome::Quit(plan) => return plan, + } + } } } } @@ -203,15 +214,21 @@ fn client_label(device: &crate::platform::DeviceInfo) -> String { format!("Switch {}", device.firmware).trim_end().to_string() } +/// The platform's way to hand the clocks back, for the panic hook. +static CLOCK_RELEASE: OnceLock = OnceLock::new(); + /// A panic on any thread goes to the log, then its frames where the target can walk them, then -/// the process aborts. The message is flushed before the walk: on the console, which builds -/// without unwind tables, the walk itself aborts. +/// the process aborts. The message is flushed and the clocks go back before the walk: on the +/// console, which builds without unwind tables, the walk itself aborts. fn install_panic_hook() { std::panic::set_hook(Box::new(|info| { let thread = std::thread::current(); let name = thread.name().unwrap_or("unnamed"); tracing::error!("PANIC on thread {name:?}: {info}"); crate::logger::flush(); + if let Some(release) = CLOCK_RELEASE.get() { + release(); + } let backtrace = std::backtrace::Backtrace::force_capture(); tracing::error!("PANIC on thread {name:?}, frames:\n{backtrace}"); crate::logger::flush(); diff --git a/crates/pf-nx-app/tests/seams.rs b/crates/pf-nx-app/tests/seams.rs index 06d43b1..457285a 100644 --- a/crates/pf-nx-app/tests/seams.rs +++ b/crates/pf-nx-app/tests/seams.rs @@ -4,6 +4,7 @@ use std::sync::Arc; use pf_nx_app::platform::fake::{FakeAudio, FakeDisplay, FakeLifecycle, FakePads, FakeStorage, FakeVideo}; +use pf_nx_app::platform::ClockStage; use pf_nx_app::platform::{AudioOut, Display, Pads, Platform, Refresh, SocketCalls, Storage}; /// A display presents what the UI drew and reads it back at its own size. @@ -59,6 +60,8 @@ fn a_menu_test_run_leaves_a_bundle_and_exits() { let storage = FakeStorage::temp("menu-run"); std::fs::write(storage.data_dir().join("test-run.json"), r#"{"scenario":"menu"}"#).unwrap(); let dir = storage.data_dir().to_path_buf(); + let lifecycle = FakeLifecycle::default(); + let clock_stages = lifecycle.clock_stages.clone(); let title = std::thread::spawn(move || { pf_nx_app::run(Platform { display: Box::new(FakeDisplay::new(640, 360)), @@ -66,7 +69,7 @@ fn a_menu_test_run_leaves_a_bundle_and_exits() { audio: Arc::new(FakeAudio::default()), pads: Box::new(FakePads::default()), storage: Arc::new(storage), - lifecycle: Box::new(FakeLifecycle::default()), + lifecycle: Box::new(lifecycle), log: None, device: pf_nx_app::platform::DeviceInfo { platform: "fake", @@ -77,6 +80,11 @@ fn a_menu_test_run_leaves_a_bundle_and_exits() { let exit = title.join().expect_err("the title only leaves through Lifecycle::exit"); assert_eq!(exit.downcast_ref::<&str>(), Some(&"title exited")); assert!(!dir.join("test-run.json").exists(), "the scenario is consumed"); + assert_eq!( + *clock_stages.lock().unwrap(), + [ClockStage::Menu], + "the menu holds its clocks from the start" + ); let verdict_root = dir.join("verdict"); let bundle = std::fs::read_dir(&verdict_root) .unwrap() diff --git a/crates/pf-nx-platform/src/console/clocks.rs b/crates/pf-nx-platform/src/console/clocks.rs new file mode 100644 index 0000000..6f62acd --- /dev/null +++ b/crates/pf-nx-platform/src/console/clocks.rs @@ -0,0 +1,167 @@ +//! The clocks the title holds for each [`ClockStage`], and the way back to the system's own. +//! +//! A running overclock module takes the ask: it keeps the rates through sleep on its own, and +//! puts back whatever clkrst sets (with no profile, Horizon OC resets the clock in 100-300 ms). +//! Without one the title sets clkrst itself and asks again when the system moves the clocks. +//! A module's hold outlives the title, so the first stage replaces whatever a crash left, and +//! [`release`] runs on every way out. + +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::OnceLock; +use std::time::{Duration, Instant}; + +use pf_nx_app::platform::{ClockStage, OperationMode}; +use pf_nx_sys::ocmod::{self, OcModule}; +use pf_nx_sys::{clk, result_code}; + +/// Between looks at the clocks when no module holds them. +const KEEP_EVERY: Duration = Duration::from_secs(1); +/// Log lines for clocks asked again, so a clock the system never leaves cannot fill the log. +const KEEP_LINES: u32 = 20; + +/// CPU, GPU and memory: the module's id, then clkrst's. +const CLOCKS: [(u32, u32); 3] = [ + (ocmod::MODULE_CPU, clk::MODULE_CPU), + (ocmod::MODULE_GPU, clk::MODULE_GPU), + (ocmod::MODULE_MEM, clk::MODULE_EMC), +]; + +/// The module found at the first stage. Statics, so a panic on any thread can reach them. +static MODULE: OnceLock> = OnceLock::new(); +/// The system's own rates in [`CLOCKS`]' order, for a title with no module; 0 is unknown. +static STOCK: [AtomicU32; 3] = [AtomicU32::new(0), AtomicU32::new(0), AtomicU32::new(0)]; + +fn module() -> Option { + *MODULE.get_or_init(|| { + // The first read comes before any ask, so it is what the system chose. + if let Some(c) = clk::clocks() { + store_stock(&[c.cpu_hz, c.gpu_hz, c.emc_hz]); + } + match OcModule::find() { + Ok(Some(module)) => { + tracing::info!("clocks: asking {}", module.service()); + Some(module) + } + Ok(None) => { + tracing::info!("clocks: no overclock module, setting them directly"); + None + } + Err(rc) => { + tracing::warn!("clocks: sm could not say ({}), setting them directly", result_code(rc)); + None + } + } + }) +} + +fn store_stock(rates: &[u32; 3]) { + for (slot, hz) in STOCK.iter().zip(rates) { + slot.store(*hz, Ordering::Relaxed); + } +} + +/// Hands the clocks back. Safe on any thread and more than once; a title that never asked +/// touches nothing. +pub fn release() { + match MODULE.get() { + Some(Some(module)) => { + for (id, _) in CLOCKS { + let _ = module.hold(id, 0); + } + } + Some(None) => { + for ((_, id), stock) in CLOCKS.into_iter().zip(&STOCK) { + let hz = stock.load(Ordering::Relaxed); + if hz != 0 { + let _ = clk::set_rate(id, hz); + } + } + } + None => {} + } +} + +/// The stage in force, kept up on the main thread. +pub struct ClockHold { + stage: Option, + mode: OperationMode, + /// What the clocks read after the last ask, with no module. + applied: Option, + looked: Instant, + /// The console changed mode, so the system's rates did too; read them at the next look. + restock: bool, + keep_lines: u32, +} + +impl ClockHold { + pub fn new(mode: OperationMode) -> Self { + Self { + stage: None, + mode, + applied: None, + looked: Instant::now(), + restock: false, + keep_lines: 0, + } + } + + pub fn set_stage(&mut self, stage: ClockStage) { + tracing::info!("clocks: {stage:?}"); + self.stage = Some(stage); + self.apply(); + } + + pub fn mode_changed(&mut self, mode: OperationMode) { + self.mode = mode; + if module().is_some() { + self.apply(); + } else { + self.restock = true; + } + } + + /// Once a frame: with no module, sleep and dock changes put the clocks back under the title. + pub fn keep(&mut self) { + if self.stage.is_none() || self.looked.elapsed() < KEEP_EVERY || module().is_some() { + return; + } + self.looked = Instant::now(); + let now = clk::clocks(); + if std::mem::take(&mut self.restock) { + if let Some(c) = now { + store_stock(&[c.cpu_hz, c.gpu_hz, c.emc_hz]); + } + } else if now == self.applied { + return; + } else if self.keep_lines < KEEP_LINES { + self.keep_lines += 1; + tracing::info!("clocks: moved under the title, asking again"); + } + self.apply(); + } + + fn apply(&mut self) { + let Some(stage) = self.stage else { return }; + let targets = stage.targets(self.mode); + let wanted = [targets.cpu_hz, targets.gpu_hz, targets.emc_hz]; + if let Some(module) = module() { + for ((id, _), hz) in CLOCKS.into_iter().zip(wanted) { + if let Err(rc) = module.hold(id, hz.unwrap_or(0)) { + tracing::warn!("clocks: {} refused module {id}: {}", module.service(), result_code(rc)); + } + } + return; + } + for (((_, id), hz), stock) in CLOCKS.into_iter().zip(wanted).zip(&STOCK) { + let hz = hz.unwrap_or_else(|| stock.load(Ordering::Relaxed)); + if hz == 0 { + continue; + } + if let Err(rc) = clk::set_rate(id, hz) { + tracing::warn!("clocks: clkrst refused {id:#x}: {}", result_code(rc)); + } + } + self.applied = clk::clocks(); + self.looked = Instant::now(); + } +} diff --git a/crates/pf-nx-platform/src/console/lifecycle.rs b/crates/pf-nx-platform/src/console/lifecycle.rs index 6fad193..7c45104 100644 --- a/crates/pf-nx-platform/src/console/lifecycle.rs +++ b/crates/pf-nx-platform/src/console/lifecycle.rs @@ -8,13 +8,16 @@ use std::cell::OnceCell; use std::sync::mpsc; use std::time::{Duration, Instant}; -use pf_nx_app::platform::{Clocks, Lifecycle, SocketCalls, SystemEvent}; +use pf_nx_app::platform::{ClockStage, Clocks, Lifecycle, SocketCalls, SystemEvent}; use pf_nx_sys::applet::{self, FocusState, HookEvent}; use pf_nx_sys::{clk, mem, pl, rt, set, socket, swkbd}; +use super::clocks::{self, ClockHold}; + pub struct NxLifecycle { events: mpsc::Receiver, _hook: applet::Hook, + hold: ClockHold, /// The system asked the title to close; the next poll leaves. closing: bool, /// The first poll logs the applet type and mode: the logger starts after `new`. @@ -34,6 +37,7 @@ impl NxLifecycle { Self { events, _hook: hook, + hold: ClockHold::new(super::operation_mode()), closing: false, reported: false, fonts: OnceCell::new(), @@ -58,6 +62,7 @@ impl Lifecycle for NxLifecycle { .map_or_else(|| "unreadable".to_string(), |c| c.to_string()) ); } + self.hold.keep(); // `appletMainLoop` in its halves, so every message is logged: no hook event and no // operation-mode change has reached a log yet, the dock change included. if let Some(msg) = applet::take_message() { @@ -77,7 +82,11 @@ impl Lifecycle for NxLifecycle { FocusState::Background => SystemEvent::Suspend, }), HookEvent::Resume => out.push(SystemEvent::Resume), - HookEvent::OperationMode => out.push(SystemEvent::OperationMode(super::operation_mode())), + HookEvent::OperationMode => { + let mode = super::operation_mode(); + self.hold.mode_changed(mode); + out.push(SystemEvent::OperationMode(mode)); + } // The system moved the title to another clock configuration (WP5's question). HookEvent::PerformanceMode => tracing::info!( "lifecycle: performance mode changed, clocks {}", @@ -111,6 +120,14 @@ impl Lifecycle for NxLifecycle { }) } + fn set_clock_stage(&mut self, stage: ClockStage) { + self.hold.set_stage(stage); + } + + fn clock_release(&self) -> Option { + Some(clocks::release) + } + fn keyboard(&mut self) -> Option { match swkbd::ask("Text to type on the PC", "Send") { Ok(text) => Some(text), @@ -138,7 +155,9 @@ impl Lifecycle for NxLifecycle { /// Returns the socket driver's lent heap, closes the detached threads' stacks, and leaves /// through libnx's `__appExit`: back to hbl when the heap is clean, else through AM to HOME. + /// HOME's close comes straight here from [`Lifecycle::poll_events`], so the clocks go back here. fn exit(&self) -> ! { + clocks::release(); applet::unlock_exit(); socket::exit(); release_heap(); diff --git a/crates/pf-nx-platform/src/console/mod.rs b/crates/pf-nx-platform/src/console/mod.rs index afe6835..d37f600 100644 --- a/crates/pf-nx-platform/src/console/mod.rs +++ b/crates/pf-nx-platform/src/console/mod.rs @@ -1,6 +1,7 @@ //! The console's implementations, assembled into one [`Platform`]. mod audio; +mod clocks; mod display_fb; mod display_nvk; mod lifecycle; diff --git a/crates/pf-nx-probe/src/clock.rs b/crates/pf-nx-probe/src/clock.rs index 91f9241..93c4a72 100644 --- a/crates/pf-nx-probe/src/clock.rs +++ b/crates/pf-nx-probe/src/clock.rs @@ -14,7 +14,7 @@ use std::sync::mpsc; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use pf_nx_sys::clk::{self, Clocks}; -use pf_nx_sys::ocmod::OcModule; +use pf_nx_sys::ocmod::{OcModule, MODULE_CPU}; use pf_nx_sys::{applet, hid, result_code}; use crate::{nx, Out}; @@ -122,7 +122,7 @@ fn run(dir: &Path, out: &mut Out, pads: &mut hid::Pads) { } for (button, hz) in [(BUTTON_A, CPU_TOP_HZ), (BUTTON_R, 0)] { if pressed & button != 0 { - let answer = match module.as_ref().map(|m| m.hold_cpu(hz)) { + let answer = match module.as_ref().map(|m| m.hold(MODULE_CPU, hz)) { Some(Ok(())) => "ok".to_owned(), Some(Err(rc)) => format!("FAIL({})", result_code(rc)), None => "no-module".to_owned(), diff --git a/crates/pf-nx-sys/src/ocmod.rs b/crates/pf-nx-sys/src/ocmod.rs index 6503216..3065b2f 100644 --- a/crates/pf-nx-sys/src/ocmod.rs +++ b/crates/pf-nx-sys/src/ocmod.rs @@ -5,9 +5,10 @@ #[cfg(target_os = "horizon")] use core::ffi::{c_char, CStr}; -/// `HocClkModule_CPU`, `SysClkModule_CPU`. -#[cfg(target_os = "horizon")] -const MODULE_CPU: u32 = 0; +/// `HocClkModule_*`, `SysClkModule_*`: the same numbers in both. +pub const MODULE_CPU: u32 = 0; +pub const MODULE_GPU: u32 = 1; +pub const MODULE_MEM: u32 = 2; /// Horizon OC's service, then sys-clk's and its forks'. #[cfg(target_os = "horizon")] @@ -69,11 +70,11 @@ impl OcModule { Ok((api, text.to_string_lossy().into_owned())) } - /// Asks it to hold the CPU at `hz`; 0 hands the clock back. It lives in the module's memory - /// until then, past the title's exit. - pub fn hold_cpu(&self, hz: u32) -> Result<(), u32> { + /// Asks it to hold `module`, a `MODULE_*`, at `hz`; 0 hands the clock back. It lives in the + /// module's memory until then, past the title's exit. + pub fn hold(&self, module: u32, hz: u32) -> Result<(), u32> { // SAFETY: `service` is NUL-terminated; the rest are plain values. - match unsafe { ffi::pf_ocmod_override(self.service.as_ptr(), MODULE_CPU, hz) } { + match unsafe { ffi::pf_ocmod_override(self.service.as_ptr(), module, hz) } { 0 => Ok(()), rc => Err(rc), } diff --git a/docs/NOTES.md b/docs/NOTES.md index e895912..61faf9b 100644 --- a/docs/NOTES.md +++ b/docs/NOTES.md @@ -208,3 +208,10 @@ record their clocks; the numbers below are under that profile unless an item say (title at `be98e16`, 2026-10-31). - With the accelerometer's sign flipped, a pad lying still reads [0, 1, 0] g on the wire, as SDL's frame has it (title at `8a18316`, 2026-10-31). +- With Horizon OC 2.5.1 on (`hoc:clk`, API 2) and no profile, clkrst alone falls back to 1020 in + 100-300 ms, and the module's override (command 8) holds 1785 with no help from the title. The + hold comes back on its own within 0.2 s of a wake, and a wake without one reads 1020. Clearing + it takes about 0.3 s, and clearing with nothing held answers ok. The hold outlives the title: + 1785 was still there on the next run, 12 s after leaving. With the module off, sm's HasService + answers without blocking and clkrst holds until sleep. Dock changes, plain sys-clk and GPU or + memory holds are not proven (probe at `c5b5088`, 2026-11-06). From 293d25a51f90ca7b3f6add65ad2620f602a9ec88 Mon Sep 17 00:00:00 2001 From: Gava <21977618+broslife@users.noreply.github.com> Date: Sat, 7 Nov 2026 19:22:40 -0300 Subject: [PATCH 4/9] docs(notes): the clock holds pass on the console Co-Authored-By: Claude Opus 5.5 --- docs/NOTES.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/NOTES.md b/docs/NOTES.md index 61faf9b..d77f2bd 100644 --- a/docs/NOTES.md +++ b/docs/NOTES.md @@ -215,3 +215,11 @@ record their clocks; the numbers below are under that profile unless an item say 1785 was still there on the next run, 12 s after leaving. With the module off, sm's HasService answers without blocking and clkrst holds until sleep. Dock changes, plain sys-clk and GPU or memory holds are not proven (probe at `c5b5088`, 2026-11-06). +- The title holds menu clocks of CPU 1428, GPU 422.4 handheld and memory 1600 MHz (422.4 is a + table rate, read back as asked), and CPU 1785 with memory 1600 through a stream. It does so + through `hoc:clk` with Horizon OC on and through clkrst with no module; without one, the system + moves the clocks on wake and on a return from HOME, and the title asks again within a second. + Docked, the menu leaves the GPU at the system's 768. Leaving through the menu or HOME's close + puts the stock clocks back, read on the overlay. The clocks read at a performance-mode message + are the system's stock ones before a hold returns, so the overlay, not that line, shows a dock + change. A dock change mid-stream is not in the logs (title at `cebd83b`, 2026-11-07). From 921a9e9bb5f8307c1daa263ecc1353d5b069f36f Mon Sep 17 00:00:00 2001 From: Gava <21977618+broslife@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:36:37 -0300 Subject: [PATCH 5/9] feat: Save Battery leaves the clocks to the system The clock hold stays on by default. With `nx.save_battery` on in the settings document, the menu and the stream hold nothing: the title lets go of the module's hold, or puts the stock rates back without one, and stops asking again. The menu reads the setting every frame, so a flip takes effect at once. The settings screen has no row for it yet: its rows are the shared console's, and a Switch-only row needs one there. Co-Authored-By: Claude Opus 5.5 --- crates/pf-nx-app/src/core/settings.rs | 32 +++++++++++++++++++-- crates/pf-nx-app/src/platform/mod.rs | 15 ++++++++++ crates/pf-nx-app/src/runtime/menu.rs | 3 ++ crates/pf-nx-app/src/runtime/mod.rs | 31 ++++++++++++++++++-- crates/pf-nx-platform/src/console/clocks.rs | 8 ++++++ 5 files changed, 84 insertions(+), 5 deletions(-) diff --git a/crates/pf-nx-app/src/core/settings.rs b/crates/pf-nx-app/src/core/settings.rs index 2947042..56d2443 100644 --- a/crates/pf-nx-app/src/core/settings.rs +++ b/crates/pf-nx-app/src/core/settings.rs @@ -1,6 +1,6 @@ //! This client's typed view of the shared settings document (`pf_client_core::trust::Settings`), -//! the one settings type it stores and edits. Every row here is a shared field; a row only the -//! console has would live in `extra` under an `nx.` prefix, and none exists. +//! the one settings type it stores and edits. Every row here is a shared field but Save Battery, +//! which only the console has and which lives in `extra` under an `nx.` prefix. use pf_client_core::trust::Settings; use punktfunk_core::config::GamepadPref; @@ -27,8 +27,15 @@ fn local_codec(name: &str) -> CodecPref { } } +/// Save Battery's key in `extra`: on, the title leaves the clocks to the system. +pub const SAVE_BATTERY_KEY: &str = "nx.save_battery"; + /// The typed reads and writes this client makes on the shared document. pub trait NxSettings { + /// Whether the title leaves the clocks to the system instead of holding its own. Off until + /// the player turns it on. + fn save_battery(&self) -> bool; + fn set_save_battery(&mut self, on: bool); fn codec_pref(&self) -> CodecPref; fn set_codec_pref(&mut self, codec: CodecPref); fn gamepad_type(&self) -> GamepadType; @@ -41,6 +48,17 @@ pub trait NxSettings { } impl NxSettings for Settings { + fn save_battery(&self) -> bool { + self.extra + .get(SAVE_BATTERY_KEY) + .and_then(serde_json::Value::as_bool) + .unwrap_or(false) + } + + fn set_save_battery(&mut self, on: bool) { + self.extra.insert(SAVE_BATTERY_KEY.into(), serde_json::Value::Bool(on)); + } + fn codec_pref(&self) -> CodecPref { local_codec(&self.codec) } @@ -100,6 +118,16 @@ mod tests { assert_eq!(back.gamepad_type(), GamepadType::JoyConPair); } + #[test] + fn save_battery_starts_off_and_round_trips() { + let mut s = default_document(); + assert!(!s.save_battery()); + s.set_save_battery(true); + let back: Settings = serde_json::from_value(serde_json::to_value(&s).unwrap()).unwrap(); + assert!(back.save_battery()); + assert_eq!(back.extra[SAVE_BATTERY_KEY], serde_json::Value::Bool(true)); + } + #[test] fn clamp_keeps_hdr_and_narrows_channels() { let mut s = default_document(); diff --git a/crates/pf-nx-app/src/platform/mod.rs b/crates/pf-nx-app/src/platform/mod.rs index 3a152b3..7c9aee1 100644 --- a/crates/pf-nx-app/src/platform/mod.rs +++ b/crates/pf-nx-app/src/platform/mod.rs @@ -414,6 +414,8 @@ impl SocketCalls { pub enum ClockStage { Menu, Stream, + /// Save Battery: the system's own clocks, the title holds none. + System, } /// The rates a stage holds, in Hz. `None` leaves that clock to the system. @@ -440,6 +442,11 @@ impl ClockStage { gpu_hz: None, emc_hz: Some(1_600_000_000), }, + Self::System => ClockTargets { + cpu_hz: None, + gpu_hz: None, + emc_hz: None, + }, } } } @@ -487,4 +494,12 @@ mod clock_tests { assert_eq!(stream.emc_hz, Some(1_600_000_000)); } } + + #[test] + fn save_battery_holds_nothing() { + for mode in [OperationMode::Handheld, OperationMode::Docked] { + let system = ClockStage::System.targets(mode); + assert_eq!((system.cpu_hz, system.gpu_hz, system.emc_hz), (None, None, None)); + } + } } diff --git a/crates/pf-nx-app/src/runtime/menu.rs b/crates/pf-nx-app/src/runtime/menu.rs index 5e4c38c..7c32339 100644 --- a/crates/pf-nx-app/src/runtime/menu.rs +++ b/crates/pf-nx-app/src/runtime/menu.rs @@ -149,6 +149,9 @@ pub(super) fn run(app: &mut App, notice: Option) -> Result { } service.tick(); + // Save Battery takes effect as the player flips it. + app.save_battery = store.with(|s| s.settings.save_battery()); + app.hold_clocks(crate::platform::ClockStage::Menu); while let Some(action) = console.take_action() { match action { diff --git a/crates/pf-nx-app/src/runtime/mod.rs b/crates/pf-nx-app/src/runtime/mod.rs index 6548d5a..1ebce62 100644 --- a/crates/pf-nx-app/src/runtime/mod.rs +++ b/crates/pf-nx-app/src/runtime/mod.rs @@ -33,9 +33,23 @@ pub(crate) struct App { /// A scripted run from `test-run.json`, taken at start-up. pub test_run: Option, pub device: crate::platform::DeviceInfo, + /// The player's Save Battery, as the menu last read it. + pub save_battery: bool, + /// The stage last handed to the lifecycle. + pub clock_stage: ClockStage, } impl App { + /// Holds the clocks for `stage`, or leaves them to the system while Save Battery is on. + /// Asks the lifecycle only on a change. + fn hold_clocks(&mut self, stage: ClockStage) { + let stage = if self.save_battery { ClockStage::System } else { stage }; + if stage != self.clock_stage { + self.clock_stage = stage; + self.lifecycle.set_clock_stage(stage); + } + } + /// System events since the last call. `Suspend` also sets [`SUSPENDED`]. fn system_events(&mut self) -> Vec { let mut events = Vec::new(); @@ -132,7 +146,16 @@ pub fn run(platform: Platform) -> ! { ); tracing::info!("language {language} for the system's {:?}", device.languages); punktfunk_core::client::set_client_label(&client_label(&device)); - lifecycle.set_clock_stage(ClockStage::Menu); + let save_battery = { + use crate::core::settings::NxSettings; + store::load().settings.save_battery() + }; + let clock_stage = if save_battery { + ClockStage::System + } else { + ClockStage::Menu + }; + lifecycle.set_clock_stage(clock_stage); crate::core::caps::install(video.caps()); // ureq's agents resolve their provider from the process default and panic without one. punktfunk_core::tls::install_default_provider(); @@ -144,6 +167,8 @@ pub fn run(platform: Platform) -> ! { identity: (String::new(), String::new()), test_run: testrun::take(), device, + save_battery, + clock_stage, }; let plan = match store::load_or_create_identity() { Ok(identity) => { @@ -196,10 +221,10 @@ fn alternate(app: &mut App) -> Option { match outcome { UiOutcome::Quit(plan) => return plan, UiOutcome::Launch(launch) => { - app.lifecycle.set_clock_stage(ClockStage::Stream); + app.hold_clocks(ClockStage::Stream); match stream::run(app, *launch) { StreamOutcome::ReturnToMenu(why) => { - app.lifecycle.set_clock_stage(ClockStage::Menu); + app.hold_clocks(ClockStage::Menu); notice = why; } StreamOutcome::Quit(plan) => return plan, diff --git a/crates/pf-nx-platform/src/console/clocks.rs b/crates/pf-nx-platform/src/console/clocks.rs index 6f62acd..0b1ca46 100644 --- a/crates/pf-nx-platform/src/console/clocks.rs +++ b/crates/pf-nx-platform/src/console/clocks.rs @@ -107,6 +107,14 @@ impl ClockHold { pub fn set_stage(&mut self, stage: ClockStage) { tracing::info!("clocks: {stage:?}"); + if stage == ClockStage::System { + // Found first, so a module's hold from a crash is let go too; with no stage the + // title stops asking again. + module(); + release(); + self.stage = None; + return; + } self.stage = Some(stage); self.apply(); } From ca107874fb5d857918c228315c857f0a26ad1570 Mon Sep 17 00:00:00 2001 From: Gava <21977618+broslife@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:57:28 -0300 Subject: [PATCH 6/9] feat: Automatic smoothness takes one frame on the Switch The shared rule resolves an Automatic buffer to two frames. On the console one frame presents as many pictures a second as two, a refresh sooner: 15-23 ms decode to present against 31-40 on 2026-10-31, and 21-25 ms end to end against a 23-36 ms swing in issue 30's run on another network. A buffer the player picks still stands. Co-Authored-By: Claude Opus 5.5 --- crates/pf-nx-app/src/core/settings.rs | 27 ++++++++++++++++++++++++- crates/pf-nx-app/src/runtime/connect.rs | 2 +- docs/improvements.md | 9 +++++---- 3 files changed, 32 insertions(+), 6 deletions(-) diff --git a/crates/pf-nx-app/src/core/settings.rs b/crates/pf-nx-app/src/core/settings.rs index 56d2443..7b4e6e9 100644 --- a/crates/pf-nx-app/src/core/settings.rs +++ b/crates/pf-nx-app/src/core/settings.rs @@ -2,7 +2,7 @@ //! the one settings type it stores and edits. Every row here is a shared field but Save Battery, //! which only the console has and which lives in `extra` under an `nx.` prefix. -use pf_client_core::trust::Settings; +use pf_client_core::trust::{PresentPriority, Settings}; use punktfunk_core::config::GamepadPref; use crate::core::model::{CodecPref, GamepadType}; @@ -36,6 +36,9 @@ pub trait NxSettings { /// the player turns it on. fn save_battery(&self) -> bool; fn set_save_battery(&mut self, on: bool); + /// The shared rule but for Automatic smoothness, which takes one frame here, not two: on the + /// console one frame presents as many pictures as two, a refresh sooner. + fn nx_present_priority(&self) -> PresentPriority; fn codec_pref(&self) -> CodecPref; fn set_codec_pref(&mut self, codec: CodecPref); fn gamepad_type(&self) -> GamepadType; @@ -59,6 +62,13 @@ impl NxSettings for Settings { self.extra.insert(SAVE_BATTERY_KEY.into(), serde_json::Value::Bool(on)); } + fn nx_present_priority(&self) -> PresentPriority { + match self.present_priority() { + PresentPriority::Smooth { .. } if self.smooth_buffer == 0 => PresentPriority::Smooth { buffer: 1 }, + shared => shared, + } + } + fn codec_pref(&self) -> CodecPref { local_codec(&self.codec) } @@ -128,6 +138,21 @@ mod tests { assert_eq!(back.extra[SAVE_BATTERY_KEY], serde_json::Value::Bool(true)); } + #[test] + fn automatic_smoothness_takes_one_frame() { + let mut s = default_document(); + s.present_priority = "smooth".into(); + s.smooth_buffer = 0; + assert_eq!(s.nx_present_priority(), PresentPriority::Smooth { buffer: 1 }); + for buffer in 1..=3 { + s.smooth_buffer = buffer; + assert_eq!(s.nx_present_priority(), PresentPriority::Smooth { buffer }); + } + s.present_priority = "latency".into(); + s.smooth_buffer = 0; + assert_eq!(s.nx_present_priority(), PresentPriority::Latency); + } + #[test] fn clamp_keeps_hdr_and_narrows_channels() { let mut s = default_document(); diff --git a/crates/pf-nx-app/src/runtime/connect.rs b/crates/pf-nx-app/src/runtime/connect.rs index f2c324c..0c683e9 100644 --- a/crates/pf-nx-app/src/runtime/connect.rs +++ b/crates/pf-nx-app/src/runtime/connect.rs @@ -125,7 +125,7 @@ pub(super) fn spawn( // Pad-only: the host draws the cursor. cursor_capture: true, pad_audio_caps: 0, - present_priority: settings.present_priority(), + present_priority: settings.nx_present_priority(), // A spelling the wire can't carry is no wish. screen_wish: ScreenWish::parse(&settings.host_screen), }, diff --git a/docs/improvements.md b/docs/improvements.md index 57c648a..ec048a0 100644 --- a/docs/improvements.md +++ b/docs/improvements.md @@ -154,10 +154,11 @@ the first frame and adds a stream period for each further one (`session/timeline console, one frame presented 59 to 60 pictures a second at 15 to 23 ms decode to present; two frames presented the same at 31 to 40 ms (NOTES, 2026-10-31). -**The proposal.** Automatic picks one frame on the Switch, either through a per-platform default -in the shared crate (section 1 would carry it) or an override here. **Needs the maintainer's -yes**: it changes what a player sees by default. **Open:** one tester's Wi-Fi so far; a busier -network may want the second frame back. +**Done.** Automatic picks one frame on the Switch, through an override here +(`NxSettings::nx_present_priority`); the shared rule still gives two everywhere else. A second +network agrees: issue 30's tester saw Automatic swing between about 23 and 36 ms end to end where +one frame held 21 to 25 ms, with the same pictures presented. **Open:** a busier network may want +the second frame back, which the player can still pick. ### Other later work From 1f5d501684aca9c12b4eaed50f6d88cdb6654ef2 Mon Sep 17 00:00:00 2001 From: Gava <21977618+broslife@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:16:14 -0300 Subject: [PATCH 7/9] feat(vk): the latency intent's take follows the arrivals The host's frame clock and the panel's drift apart, so the pictures' arrivals walk through the refresh, about 0.8 ms a minute in issue 30's logs. Newest wins took at a fixed 10 ms after the vblank, and once the band of arrivals straddled it, up to 150 pictures a window went unseen for minutes. Under the latency intent the take now sits 2 ms past the latest usual arrival, within the GPU budget. It moves at once when the band comes within 1 ms, moves earlier when that saves over 3 ms, and goes to the start of the next refresh when the band runs past the budget. The present line reports the band, the take and the moves. Smoothness keeps its fixed late take. Co-Authored-By: Claude Opus 5.5 --- crates/pf-nx-vk/src/lib.rs | 1 + crates/pf-nx-vk/src/pacing.rs | 45 ++++- crates/pf-nx-vk/src/picture.rs | 21 ++- crates/pf-nx-vk/src/presenter.rs | 5 + crates/pf-nx-vk/src/steer.rs | 276 +++++++++++++++++++++++++++++++ docs/improvements.md | 12 ++ 6 files changed, 351 insertions(+), 9 deletions(-) create mode 100644 crates/pf-nx-vk/src/steer.rs diff --git a/crates/pf-nx-vk/src/lib.rs b/crates/pf-nx-vk/src/lib.rs index ac66978..7ce2ada 100644 --- a/crates/pf-nx-vk/src/lib.rs +++ b/crates/pf-nx-vk/src/lib.rs @@ -15,6 +15,7 @@ pub mod pipelines; pub mod presenter; #[cfg(feature = "pyrowave")] pub mod pyro; +mod steer; mod timer; pub mod ui; pub mod util; diff --git a/crates/pf-nx-vk/src/pacing.rs b/crates/pf-nx-vk/src/pacing.rs index 64dbb1d..99b837f 100644 --- a/crates/pf-nx-vk/src/pacing.rs +++ b/crates/pf-nx-vk/src/pacing.rs @@ -9,7 +9,9 @@ //! of them, every frame after. //! //! [`Pacing::Late`] also sleeps into the refresh before the picture is taken, leaving the GPU's -//! slowest recent frame plus `MARGIN` before the vblank. +//! slowest recent frame plus `MARGIN` before the vblank. Under the latency intent the take +//! follows the pictures' arrivals within that budget (`steer`), so the band of arrivals never +//! straddles it. //! //! Only a stream paces on the vblank. The menu paces on the acquire: its frames carry no picture //! whose lateness counts, and the two frames queued hide the slow ones a tab change draws, which @@ -22,6 +24,7 @@ use std::time::{Duration, Instant}; use crate::device::Vsync; +use crate::steer::Steer; /// How the loop meets the vblank. Without a vsync event every mode paces on the acquire. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -75,6 +78,10 @@ pub(crate) struct Pace { quiet: u32, /// Quick acquires since a stall emptied the queue, while the run lasts. burst: Option, + /// Where the latency intent takes its picture. + steer: Steer, + /// The slot runs the latency intent: the take follows the arrivals. + steering: bool, window: Window, } @@ -113,6 +120,8 @@ impl Pace { drains: true, quiet: 0, burst: None, + steer: Steer::new(), + steering: false, window: Window { wait: samples(), acquire: samples(), @@ -134,6 +143,7 @@ impl Pace { self.drain = false; self.drained = false; self.burst = None; + self.steer.reset(); if let Some(v) = self.vsync.filter(|_| self.pacing != Pacing::Acquire) { (v.clear)(); } @@ -234,14 +244,28 @@ impl Pace { quick } - /// Late pacing: sleeps until the composition's budget before the vblank after `vblank`. Notes - /// where in the refresh the picture is taken either way. + /// The pictures that reached the slot since the last take, against the vblank at `vblank`. + /// `latency`: the slot runs newest wins, and the take follows them. + pub fn arrived(&mut self, vblank: Instant, period: Duration, arrivals: &[Instant], latency: bool) { + self.steering = latency; + if latency { + self.steer.note(vblank, period, arrivals); + } + } + + /// Late pacing: sleeps until the composition's budget before the vblank after `vblank`, or, + /// under the latency intent, to where the steer puts the take within it. Notes where in the + /// refresh the picture is taken either way. pub fn take(&mut self, vblank: Instant, period: Duration) { if self.pacing == Pacing::Late { - if let Some(rest) = self - .late_offset(period) - .and_then(|at| (vblank + at).checked_duration_since(Instant::now())) - { + let at = self.late_offset(period).map(|max| { + if self.steering { + self.steer.offset(max, period) + } else { + max + } + }); + if let Some(rest) = at.and_then(|at| (vblank + at).checked_duration_since(Instant::now())) { std::thread::sleep(rest); } } @@ -289,12 +313,17 @@ impl Pace { (Some(_), Pacing::Late) => "on the vblank, taken late", (Some(_), _) => "on the vblank", }; + let steered = self + .steering + .then(|| self.steer.summary()) + .flatten() + .map_or_else(String::new, |s| format!("; steered: {s}")); let w = &mut self.window; let b = w.bursts; let line = format!( "present[{}s]: {} frames {mode}; vblank wait {}, {} timed out; acquire {}, {} under 1 ms; present {}; \ {} found a frame queued, {} drained; picture taken {} after the vblank; quick acquires after a stall \ - 0:{} 1:{} 2:{} 3:{} {}+:{}", + 0:{} 1:{} 2:{} 3:{} {}+:{}{steered}", WINDOW.as_secs(), w.frames, spread(&mut w.wait), diff --git a/crates/pf-nx-vk/src/picture.rs b/crates/pf-nx-vk/src/picture.rs index 75c4208..cf465b3 100644 --- a/crates/pf-nx-vk/src/picture.rs +++ b/crates/pf-nx-vk/src/picture.rs @@ -75,7 +75,20 @@ impl VideoSlot { /// Queues `picture`; under the latency intent it replaces whatever was not taken yet. pub fn publish(&self, picture: Picture) { let due = picture.due; - self.lock().push(due, Arc::new(picture)); + let mut q = self.lock(); + if q.arrivals.len() < MAX_ARRIVALS { + q.arrivals.push(Instant::now()); + } + q.push(due, Arc::new(picture)); + } + + /// Moves into `out` when each picture since the last call reached the slot. `true` under the + /// latency intent. + pub fn drain_arrivals(&self, out: &mut Vec) -> bool { + out.clear(); + let mut q = self.lock(); + out.append(&mut q.arrivals); + q.smoothing == 0 } /// The picture for the vblank at `latch`, if a new one is due by then. @@ -117,6 +130,8 @@ const SMOOTHING_SLACK: usize = 2; const STANDING_TAKES: u32 = 30; /// The most pictures the slot ever holds. const MAX_QUEUED: usize = MAX_SMOOTHING + SMOOTHING_SLACK; +/// Arrival times the slot keeps between takes; a stall past this many keeps the first. +const MAX_ARRIVALS: usize = 64; /// Pictures the slot dropped without showing them, the figure the smoothness intent exists to /// keep at zero. @@ -213,11 +228,14 @@ struct Queue { standing: u32, /// Smoothing only: the takes since the last report. window: Window, + /// When each picture since the presenter last looked reached the slot. + arrivals: Vec, } impl Default for Queue { fn default() -> Self { Self { + arrivals: Vec::with_capacity(MAX_ARRIVALS), items: VecDeque::with_capacity(MAX_QUEUED + 1), smoothing: 0, drops: Drops::default(), @@ -281,6 +299,7 @@ impl Queue { fn clear(&mut self) { self.items.clear(); + self.arrivals.clear(); self.standing = 0; } diff --git a/crates/pf-nx-vk/src/presenter.rs b/crates/pf-nx-vk/src/presenter.rs index 141061c..1348ea7 100644 --- a/crates/pf-nx-vk/src/presenter.rs +++ b/crates/pf-nx-vk/src/presenter.rs @@ -64,6 +64,8 @@ pub struct Presenter { /// The UI layer is drawn and blended; a stream with an empty overlay turns it off. ui_on: bool, slot: Arc, + /// The slot's arrival times, drained at each take. + arrivals: Vec, current: Option>, stream: Option, last_present: Option, @@ -182,6 +184,7 @@ impl Presenter { ui, ui_on: true, slot, + arrivals: Vec::with_capacity(64), current: None, stream: None, last_present: None, @@ -582,6 +585,8 @@ impl Display for Presenter { // acquire that blocked, at the vblank a refresh from here. let latch = match vblank.filter(|_| quick) { Some(at) => { + let latency = self.slot.drain_arrivals(&mut self.arrivals); + self.pace.arrived(at, period, &self.arrivals, latency); self.pace.take(at, period); at + period } diff --git a/crates/pf-nx-vk/src/steer.rs b/crates/pf-nx-vk/src/steer.rs new file mode 100644 index 0000000..f996960 --- /dev/null +++ b/crates/pf-nx-vk/src/steer.rs @@ -0,0 +1,276 @@ +//! Where in the refresh the latency intent takes its picture. +//! +//! Newest wins: a picture that lands just after the take waits a whole refresh, and the one after +//! it lands before the next take and replaces it unseen. The host's frame clock and the panel's +//! drift apart, so the arrivals walk through the refresh, about 0.8 ms a minute in issue 30's run. +//! A take at a fixed point is crossed every twenty minutes or so, and while the band of arrivals +//! straddles it, up to a third of the pictures go unseen for minutes. +//! +//! The steer follows the arrivals instead. It places the take [`GUARD`] past the latest usual +//! arrival, within what the GPU budget allows. It moves at once when the arrivals come within +//! [`UNSAFE`] of the take, and moves earlier when that would cut the wait by more than [`SLACK`]. +//! A band that runs past the budget is taken at the start of the next refresh. + +use std::time::{Duration, Instant}; + +/// Arrivals the band is read over: about two seconds at 60 pictures a second. +const ARRIVALS: usize = 128; +/// Arrivals between looks at the take: about a second. +const EVERY: usize = 60; +/// Room the take leaves past the latest usual arrival. +const GUARD: Duration = Duration::from_millis(2); +/// A take this close to the latest usual arrival moves at once. +const UNSAFE: Duration = Duration::from_millis(1); +/// A take that could wait this much less moves earlier. +const SLACK: Duration = Duration::from_millis(3); +/// Arrivals the band holds, in percent of the window; the rest are a late burst it lets go. +const BAND_PCT: usize = 98; + +pub(crate) struct Steer { + /// Each arrival's place in the refresh, µs after the vblank, the last [`ARRIVALS`]. + phases: [u32; ARRIVALS], + n: usize, + /// Arrivals since the last look. + since: usize, + /// The take's place in the refresh; `None` until the first look, which starts from the budget. + at: Option, + /// The band at the last look: its centre and its width. + band: Option<(Duration, Duration)>, + /// Moves since the last report. + moves: u32, +} + +/// A band of arrivals, in µs: where its earliest usual arrival sits and how wide it runs. +struct Band { + earliest: u64, + width: u64, + centre: u64, +} + +impl Steer { + pub fn new() -> Self { + Self { + phases: [0; ARRIVALS], + n: 0, + since: 0, + at: None, + band: None, + moves: 0, + } + } + + /// Forgets the arrivals: a new stream, a new host clock. + pub fn reset(&mut self) { + *self = Self::new(); + } + + /// Notes `arrivals` against the vblank at `vblank`, `period` apart. + pub fn note(&mut self, vblank: Instant, period: Duration, arrivals: &[Instant]) { + let p = period.as_micros() as i64; + if p == 0 { + return; + } + for &a in arrivals { + let off = if a >= vblank { + (a - vblank).as_micros() as i64 + } else { + -((vblank - a).as_micros() as i64) + }; + self.phases[self.n % ARRIVALS] = off.rem_euclid(p) as u32; + self.n += 1; + self.since += 1; + } + } + + /// The take's place in the refresh, at most `max`, the GPU budget's latest. + pub fn offset(&mut self, max: Duration, period: Duration) -> Duration { + if self.n >= EVERY && self.since >= EVERY { + self.since = 0; + self.look(max, period); + } + self.at.unwrap_or(max).min(max) + } + + fn look(&mut self, max: Duration, period: Duration) { + let p = period.as_micros() as u64; + let held = self.n.min(ARRIVALS); + let Some(band) = band(&self.phases[..held], p) else { + return; + }; + self.band = Some((Duration::from_micros(band.centre), Duration::from_micros(band.width))); + let (guard, unsafe_, slack) = (us(GUARD), us(UNSAFE), us(SLACK)); + if band.width + 2 * guard >= p { + // No point in the refresh clears the band: leave the take where it is. + return; + } + let max = us(max).min(p - 1); + // How far past the band's latest usual arrival a take at `t` sits; 0 inside the band. + let margin = |t: u64| ((t + p - band.earliest) % p).saturating_sub(band.width); + let want = (band.earliest + band.width + guard) % p; + let target = if want <= max { want } else { 0 }; + let cur = self.at.map_or(max, |d| us(d).min(max)); + let cur_margin = margin(cur); + let move_now = cur_margin < unsafe_ || (self.at.is_none() && cur != target); + let saves = cur_margin.saturating_sub(margin(target)) > slack; + if (move_now || saves) && cur != target { + self.moves += u32::from(self.at.is_some()); + self.at = Some(Duration::from_micros(target)); + } else if self.at.is_none() { + self.at = Some(Duration::from_micros(cur)); + } + } + + /// `arrivals at … ms, band … ms, take … ms, … moves`, then a fresh count; `None` before the + /// first look. + pub fn summary(&mut self) -> Option { + let (centre, width) = self.band?; + let at = self.at?; + let ms = |d: Duration| d.as_secs_f64() * 1e3; + let line = format!( + "arrivals at {:.1} ms in a {:.1} ms band, take at {:.1} ms, {} moves", + ms(centre), + ms(width), + ms(at), + self.moves + ); + self.moves = 0; + Some(line) + } +} + +fn us(d: Duration) -> u64 { + d.as_micros() as u64 +} + +/// The band the arrivals' `phases` (µs into a `p` µs refresh) make: its centre by the circular +/// mean, then the spread around it that holds [`BAND_PCT`] of them. +fn band(phases: &[u32], p: u64) -> Option { + if phases.is_empty() || p == 0 { + return None; + } + let tau = std::f64::consts::TAU; + let (mut s, mut c) = (0.0, 0.0); + for &ph in phases { + let a = f64::from(ph) / p as f64 * tau; + s += a.sin(); + c += a.cos(); + } + let centre = (s.atan2(c).rem_euclid(tau) / tau * p as f64) as i64; + let half = (p / 2) as i64; + let mut devs: Vec = phases + .iter() + .map(|&ph| (i64::from(ph) - centre + half).rem_euclid(p as i64) - half) + .collect(); + devs.sort_unstable(); + let cut = |pct: usize| devs[((devs.len() - 1) * pct) / 100]; + let (lo, hi) = (cut(100 - BAND_PCT), cut(BAND_PCT)); + Some(Band { + earliest: (centre + lo).rem_euclid(p as i64) as u64, + width: (hi - lo) as u64, + centre: centre.rem_euclid(p as i64) as u64, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + const PERIOD: Duration = Duration::from_nanos(16_666_667); + const MAX: Duration = Duration::from_millis(10); + + /// One second of arrivals around `centre_us` into the refresh, spread over ±`jitter_us`. + fn second(steer: &mut Steer, centre_us: u64, jitter_us: u64) { + let vblank = Instant::now() + Duration::from_secs(1); + let arrivals: Vec = (0..EVERY as u64) + .map(|i| { + let j = if jitter_us == 0 { + 0 + } else { + (i * 7919) % (2 * jitter_us + 1) + }; + vblank + Duration::from_micros(centre_us + j) - Duration::from_micros(jitter_us) + }) + .collect(); + steer.note(vblank, PERIOD, &arrivals); + } + + fn ms(steer: &mut Steer) -> f64 { + steer.offset(MAX, PERIOD).as_secs_f64() * 1e3 + } + + /// Until the first look the take is the budget's; then it sits the guard past the band. + #[test] + fn the_take_starts_at_the_budget_then_follows_the_band() { + let mut s = Steer::new(); + assert_eq!(s.offset(MAX, PERIOD), MAX); + second(&mut s, 3_000, 500); + let at = ms(&mut s); + assert!((5.3..=5.7).contains(&at), "{at}"); + } + + /// A band that walks through the refresh, earlier as in issue 30's run or later, never comes + /// within the unsafe distance of the take, and the take steps after it. + #[test] + fn a_drifting_band_never_reaches_the_take() { + for step in [-13, 13] { + drift(step); + } + } + + /// Twenty-five minutes of a band walking `step` µs a second, about a refresh and a half. + fn drift(step: i64) { + let mut s = Steer::new(); + let mut centre: i64 = 8_000; + let mut moves = 0; + for _ in 0..1_500 { + let c = centre.rem_euclid(16_667) as u64; + second(&mut s, c, 800); + let before = s.at; + let at = us(s.offset(MAX, PERIOD)) as i64; + moves += u32::from(before.is_some() && before != s.at); + // The latest arrival of all, against the take: the band's edge holds 98 of 100, so + // the take keeps at least half the unsafe distance from the very last. + let latest = (c as i64 + 800).rem_euclid(16_667); + let gap = (at - latest).rem_euclid(16_667); + assert!(gap >= us(UNSAFE) as i64 / 2, "take {at} µs, latest arrival {latest} µs"); + centre += step; // 0.78 ms a minute + } + assert!(moves > 0 && moves < 60, "{moves} moves at {step} µs a second"); + } + + /// A band past the budget's latest point is taken at the start of the next refresh. + #[test] + fn a_band_past_the_budget_is_taken_at_the_next_refresh() { + let mut s = Steer::new(); + second(&mut s, 12_000, 500); + assert_eq!(s.offset(MAX, PERIOD), Duration::ZERO); + } + + /// A band that comes up on the take moves it at once; a calm one leaves it. + #[test] + fn the_take_moves_only_when_unsafe_or_wasteful() { + let mut s = Steer::new(); + second(&mut s, 3_000, 300); + let first = s.offset(MAX, PERIOD); + second(&mut s, 3_500, 300); + assert_eq!(s.offset(MAX, PERIOD), first, "half a millisecond is not worth a move"); + second(&mut s, 5_000, 300); + assert!(s.offset(MAX, PERIOD) > first, "the band reached the take"); + } + + /// No point clears a band nearly a refresh wide: the take stays. + #[test] + fn a_band_too_wide_leaves_the_take() { + let mut s = Steer::new(); + second(&mut s, 8_000, 7_500); + assert_eq!(s.offset(MAX, PERIOD), MAX); + } + + /// A band across the vblank reads as one band, not two halves. + #[test] + fn a_band_across_the_vblank_is_one_band() { + let b = band(&[16_500, 16_600, 100, 200], 16_667).unwrap(); + assert!(b.width < 1_000, "{}", b.width); + assert!(b.earliest >= 16_400, "{}", b.earliest); + } +} diff --git a/docs/improvements.md b/docs/improvements.md index ec048a0..18ab6a3 100644 --- a/docs/improvements.md +++ b/docs/improvements.md @@ -160,6 +160,18 @@ network agrees: issue 30's tester saw Automatic swing between about 23 and 36 ms one frame held 21 to 25 ms, with the same pictures presented. **Open:** a busier network may want the second frame back, which the player can still pick. +### Lowest latency: the take follows the arrivals + +Issue 30's logs (run2, 11:25 to 11:34) show the arrivals walking through the refresh at about +0.8 ms a minute, with a band of 1 to 2 ms. Once the band reached the fixed take at 10 ms after +the vblank, newest wins dropped up to 150 pictures a window. Under the latency intent the take +now sits 2 ms past the latest usual arrival (98 of 100 over the last two seconds), inside the GPU +budget. It moves at once when the band comes within 1 ms of it and moves earlier when that saves +over 3 ms; a band past the budget is taken at the start of the next refresh (`pf-nx-vk` +`steer.rs`). Smoothness keeps its fixed late take. **Test:** Lowest latency for ten minutes or +more, handheld. `present[10s]` adds `steered: arrivals at … ms in a … ms band, take at … ms, +… moves`; `unseen (replaced)` should stay near zero through the whole run. + ### Other later work - **PyroWave on NVK.** The lane is lifted but off. A 256-core Maxwell GPU at 307 to 460 MHz has From b57976e3430136428b14f77665ee21f97a7e6a78 Mon Sep 17 00:00:00 2001 From: Gava <21977618+broslife@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:29:12 -0300 Subject: [PATCH 8/9] fix(platform): ask for the clocks again at events, not every second With no overclock module the title read the clocks every second to see whether the system had put its own back. The system does that at a wake, a return from HOME and a dock change (NOTES, 2026-11-07), and the title hears each of them. It now asks again at those events, and once more half a second later in case the system moved the clocks after the event. Between events it reads nothing. Co-Authored-By: Claude Opus 5.5 --- crates/pf-nx-platform/src/console/clocks.rs | 61 +++++++++++-------- .../pf-nx-platform/src/console/lifecycle.rs | 25 +++++--- 2 files changed, 54 insertions(+), 32 deletions(-) diff --git a/crates/pf-nx-platform/src/console/clocks.rs b/crates/pf-nx-platform/src/console/clocks.rs index 0b1ca46..6c97b93 100644 --- a/crates/pf-nx-platform/src/console/clocks.rs +++ b/crates/pf-nx-platform/src/console/clocks.rs @@ -2,7 +2,9 @@ //! //! A running overclock module takes the ask: it keeps the rates through sleep on its own, and //! puts back whatever clkrst sets (with no profile, Horizon OC resets the clock in 100-300 ms). -//! Without one the title sets clkrst itself and asks again when the system moves the clocks. +//! Without one the title sets clkrst itself. The system puts its own rates back on a wake, on a +//! return from HOME and on a dock change (NOTES, 2026-11-07), so the title asks again at those +//! events, and once more [`AGAIN_AFTER`] later in case the system moved them after the event. //! A module's hold outlives the title, so the first stage replaces whatever a crash left, and //! [`release`] runs on every way out. @@ -14,9 +16,9 @@ use pf_nx_app::platform::{ClockStage, OperationMode}; use pf_nx_sys::ocmod::{self, OcModule}; use pf_nx_sys::{clk, result_code}; -/// Between looks at the clocks when no module holds them. -const KEEP_EVERY: Duration = Duration::from_secs(1); -/// Log lines for clocks asked again, so a clock the system never leaves cannot fill the log. +/// After an event that moves the clocks, how long until the title asks once more. +const AGAIN_AFTER: Duration = Duration::from_millis(500); +/// Log lines for clocks asked again, so a console that wakes all day cannot fill the log. const KEEP_LINES: u32 = 20; /// CPU, GPU and memory: the module's id, then clkrst's. @@ -85,10 +87,9 @@ pub fn release() { pub struct ClockHold { stage: Option, mode: OperationMode, - /// What the clocks read after the last ask, with no module. - applied: Option, - looked: Instant, - /// The console changed mode, so the system's rates did too; read them at the next look. + /// With no module: when to ask once more after an event that moves the clocks. + again: Option, + /// The console changed mode, so the system's rates did too; read them before the next ask. restock: bool, keep_lines: u32, } @@ -98,8 +99,7 @@ impl ClockHold { Self { stage: None, mode, - applied: None, - looked: Instant::now(), + again: None, restock: false, keep_lines: 0, } @@ -119,31 +119,46 @@ impl ClockHold { self.apply(); } + /// A dock change. With no module the system's rates change with it: they are read once the + /// system has set them, at the performance-mode message or [`AGAIN_AFTER`] from here. pub fn mode_changed(&mut self, mode: OperationMode) { self.mode = mode; if module().is_some() { self.apply(); - } else { + } else if self.stage.is_some() { self.restock = true; + self.again = Some(Instant::now() + AGAIN_AFTER); } } - /// Once a frame: with no module, sleep and dock changes put the clocks back under the title. - pub fn keep(&mut self) { - if self.stage.is_none() || self.looked.elapsed() < KEEP_EVERY || module().is_some() { + /// The system may have put its own clocks back: a wake, a return to focus, a new performance + /// mode. With no module the title asks again now and once more [`AGAIN_AFTER`] later. + pub fn system_moved(&mut self, why: &str) { + if self.stage.is_none() || module().is_some() { return; } - self.looked = Instant::now(); - let now = clk::clocks(); + if self.keep_lines < KEEP_LINES { + self.keep_lines += 1; + tracing::info!("clocks: {why}, asking again"); + } + self.reask(); + self.again = Some(Instant::now() + AGAIN_AFTER); + } + + /// Once a frame: the second ask after an event, when it is due. Reads no clock otherwise. + pub fn tick(&mut self) { + if self.again.is_some_and(|at| Instant::now() >= at) { + self.again = None; + self.reask(); + } + } + + /// Asks again, reading the system's rates first after a dock change. + fn reask(&mut self) { if std::mem::take(&mut self.restock) { - if let Some(c) = now { + if let Some(c) = clk::clocks() { store_stock(&[c.cpu_hz, c.gpu_hz, c.emc_hz]); } - } else if now == self.applied { - return; - } else if self.keep_lines < KEEP_LINES { - self.keep_lines += 1; - tracing::info!("clocks: moved under the title, asking again"); } self.apply(); } @@ -169,7 +184,5 @@ impl ClockHold { tracing::warn!("clocks: clkrst refused {id:#x}: {}", result_code(rc)); } } - self.applied = clk::clocks(); - self.looked = Instant::now(); } } diff --git a/crates/pf-nx-platform/src/console/lifecycle.rs b/crates/pf-nx-platform/src/console/lifecycle.rs index 7c45104..3a634ea 100644 --- a/crates/pf-nx-platform/src/console/lifecycle.rs +++ b/crates/pf-nx-platform/src/console/lifecycle.rs @@ -62,7 +62,7 @@ impl Lifecycle for NxLifecycle { .map_or_else(|| "unreadable".to_string(), |c| c.to_string()) ); } - self.hold.keep(); + self.hold.tick(); // `appletMainLoop` in its halves, so every message is logged: no hook event and no // operation-mode change has reached a log yet, the dock change included. if let Some(msg) = applet::take_message() { @@ -77,22 +77,31 @@ impl Lifecycle for NxLifecycle { for event in self.events.try_iter() { match event { HookEvent::FocusState => out.push(match applet::focus_state() { - FocusState::InFocus => SystemEvent::FocusGained, + FocusState::InFocus => { + self.hold.system_moved("back in focus"); + SystemEvent::FocusGained + } FocusState::OutOfFocus => SystemEvent::FocusLost, FocusState::Background => SystemEvent::Suspend, }), - HookEvent::Resume => out.push(SystemEvent::Resume), + HookEvent::Resume => { + self.hold.system_moved("awake"); + out.push(SystemEvent::Resume); + } HookEvent::OperationMode => { let mode = super::operation_mode(); self.hold.mode_changed(mode); out.push(SystemEvent::OperationMode(mode)); } // The system moved the title to another clock configuration (WP5's question). - HookEvent::PerformanceMode => tracing::info!( - "lifecycle: performance mode changed, clocks {}", - self.clocks() - .map_or_else(|| "unreadable".to_string(), |c| c.to_string()) - ), + HookEvent::PerformanceMode => { + tracing::info!( + "lifecycle: performance mode changed, clocks {}", + self.clocks() + .map_or_else(|| "unreadable".to_string(), |c| c.to_string()) + ); + self.hold.system_moved("new performance mode"); + } HookEvent::Exit => {} } } From ae6f1701343d97f8f68db809b6f94a007c6f7934 Mon Sep 17 00:00:00 2001 From: Gava <21977618+broslife@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:48:13 -0300 Subject: [PATCH 9/9] fix(platform): the clock hold only raises a clock The hold asked for its rates whatever the console ran. On issue 30's console that would drop a memory clock the player runs at 2400 to 1600 at runtime, and docked it would pull a 2397 CPU profile down to 1785. Each clock is now held only where the rate the system or the player's profile runs is below the stage's. Those rates are read before the title asks for anything: under a module the first stage lets go of a crash's hold and reads them once the module has put its own back, and a dock change does the same for the new mode. A wake, a return to focus and a new performance mode ask again with a module too. Each ask logs what it holds and what it leaves. Co-Authored-By: Claude Opus 5.5 --- crates/pf-nx-app/src/platform/mod.rs | 61 +++++++++++- crates/pf-nx-platform/src/console/clocks.rs | 104 +++++++++++++------- 2 files changed, 126 insertions(+), 39 deletions(-) diff --git a/crates/pf-nx-app/src/platform/mod.rs b/crates/pf-nx-app/src/platform/mod.rs index 7c9aee1..a373069 100644 --- a/crates/pf-nx-app/src/platform/mod.rs +++ b/crates/pf-nx-app/src/platform/mod.rs @@ -451,6 +451,40 @@ impl ClockStage { } } +impl ClockTargets { + /// Only the rates above what the system or the player's profile runs: the title raises a + /// clock and never lowers one. An unknown rate (0) is held. + pub fn above(self, running: Clocks) -> Self { + let raise = |want: Option, run: u32| want.filter(|&hz| run == 0 || run < hz); + Self { + cpu_hz: raise(self.cpu_hz, running.cpu_hz), + gpu_hz: raise(self.gpu_hz, running.gpu_hz), + emc_hz: raise(self.emc_hz, running.emc_hz), + } + } + + /// `holds cpu 1785.0; leaves gpu at 384.0, emc at 2400.0 MHz`, for the log. + pub fn describe(self, running: Clocks) -> String { + let mhz = |hz: u32| f64::from(hz) / 1e6; + let rows = [ + ("cpu", self.cpu_hz, running.cpu_hz), + ("gpu", self.gpu_hz, running.gpu_hz), + ("emc", self.emc_hz, running.emc_hz), + ]; + let join = |v: Vec| if v.is_empty() { "none".to_string() } else { v.join(", ") }; + let holds = rows + .iter() + .filter_map(|(n, hz, _)| hz.map(|hz| format!("{n} {:.1}", mhz(hz)))) + .collect(); + let leaves = rows + .iter() + .filter(|(_, hz, _)| hz.is_none()) + .map(|(n, _, run)| format!("{n} at {:.1}", mhz(*run))) + .collect(); + format!("holds {}; leaves {} MHz", join(holds), join(leaves)) + } +} + /// The CPU, GPU and memory clocks, in Hz. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Clocks { @@ -474,7 +508,7 @@ impl std::fmt::Display for Clocks { #[cfg(test)] mod clock_tests { - use super::{ClockStage, OperationMode}; + use super::{ClockStage, Clocks, OperationMode}; #[test] fn the_menu_raises_the_gpu_only_in_handheld() { @@ -495,6 +529,31 @@ mod clock_tests { } } + /// A rate the profile already runs at or above the stage's is left; a lower one is raised. + #[test] + fn the_title_only_raises_a_clock() { + let mhz = |m: u32| m * 1_000_000; + let run = |cpu, gpu, emc| Clocks { + cpu_hz: mhz(cpu), + gpu_hz: mhz(gpu), + emc_hz: mhz(emc), + }; + let stream = ClockStage::Stream.targets(OperationMode::Handheld); + let governed = stream.above(run(612, 384, 2400)); + assert_eq!( + (governed.cpu_hz, governed.gpu_hz, governed.emc_hz), + (Some(mhz(1785)), None, None), + "the governor's 612 is raised, a 2400 memory clock left" + ); + let profile = stream.above(run(2397, 768, 1600)); + assert_eq!((profile.cpu_hz, profile.gpu_hz, profile.emc_hz), (None, None, None)); + assert_eq!(stream.above(Clocks::default()), stream, "an unknown rate is held"); + assert_eq!( + governed.describe(run(612, 384, 2400)), + "holds cpu 1785.0; leaves gpu at 384.0, emc at 2400.0 MHz" + ); + } + #[test] fn save_battery_holds_nothing() { for mode in [OperationMode::Handheld, OperationMode::Docked] { diff --git a/crates/pf-nx-platform/src/console/clocks.rs b/crates/pf-nx-platform/src/console/clocks.rs index 6c97b93..2afc8f6 100644 --- a/crates/pf-nx-platform/src/console/clocks.rs +++ b/crates/pf-nx-platform/src/console/clocks.rs @@ -1,22 +1,30 @@ //! The clocks the title holds for each [`ClockStage`], and the way back to the system's own. //! +//! The title only raises a clock. Each one runs at the rate the system or the player's overclock +//! profile set, read before the title asks for anything; a stage holds a clock only where that +//! rate is below the stage's. A memory clock a player runs at 2400 stays there (issue 30's +//! console froze on a runtime memory change). +//! //! A running overclock module takes the ask: it keeps the rates through sleep on its own, and //! puts back whatever clkrst sets (with no profile, Horizon OC resets the clock in 100-300 ms). //! Without one the title sets clkrst itself. The system puts its own rates back on a wake, on a //! return from HOME and on a dock change (NOTES, 2026-11-07), so the title asks again at those -//! events, and once more [`AGAIN_AFTER`] later in case the system moved them after the event. -//! A module's hold outlives the title, so the first stage replaces whatever a crash left, and -//! [`release`] runs on every way out. +//! events, with a module too, and once more [`AGAIN_AFTER`] later in case the system moved them +//! after the event. Between events it reads nothing. +//! +//! A module's hold outlives the title, so the first stage lets go of whatever a crash left and +//! reads the rates once the module has put its own back. [`release`] runs on every way out. use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::OnceLock; use std::time::{Duration, Instant}; -use pf_nx_app::platform::{ClockStage, OperationMode}; +use pf_nx_app::platform::{ClockStage, Clocks, OperationMode}; use pf_nx_sys::ocmod::{self, OcModule}; use pf_nx_sys::{clk, result_code}; -/// After an event that moves the clocks, how long until the title asks once more. +/// After an event that moves the clocks, how long until the title asks once more. Also how long +/// a module takes to put its own rates back once a hold is let go (about 0.3 s, NOTES). const AGAIN_AFTER: Duration = Duration::from_millis(500); /// Log lines for clocks asked again, so a console that wakes all day cannot fill the log. const KEEP_LINES: u32 = 20; @@ -30,15 +38,14 @@ const CLOCKS: [(u32, u32); 3] = [ /// The module found at the first stage. Statics, so a panic on any thread can reach them. static MODULE: OnceLock> = OnceLock::new(); -/// The system's own rates in [`CLOCKS`]' order, for a title with no module; 0 is unknown. +/// The rates the system or the player's profile runs, in [`CLOCKS`]' order; 0 is unknown. static STOCK: [AtomicU32; 3] = [AtomicU32::new(0), AtomicU32::new(0), AtomicU32::new(0)]; fn module() -> Option { *MODULE.get_or_init(|| { - // The first read comes before any ask, so it is what the system chose. - if let Some(c) = clk::clocks() { - store_stock(&[c.cpu_hz, c.gpu_hz, c.emc_hz]); - } + // The first read comes before any ask, so it is what the system chose. Under a module it + // may be a crash's hold, so the first stage reads again once that is let go. + read_stock(); match OcModule::find() { Ok(Some(module)) => { tracing::info!("clocks: asking {}", module.service()); @@ -56,6 +63,12 @@ fn module() -> Option { }) } +fn read_stock() { + if let Some(c) = clk::clocks() { + store_stock(&[c.cpu_hz, c.gpu_hz, c.emc_hz]); + } +} + fn store_stock(rates: &[u32; 3]) { for (slot, hz) in STOCK.iter().zip(rates) { slot.store(*hz, Ordering::Relaxed); @@ -87,9 +100,12 @@ pub fn release() { pub struct ClockHold { stage: Option, mode: OperationMode, - /// With no module: when to ask once more after an event that moves the clocks. + /// The first stage has run: a crash's hold is let go and the rates are being read. + started: bool, + /// When to ask once more after an event that moves the clocks. again: Option, - /// The console changed mode, so the system's rates did too; read them before the next ask. + /// The rates the system or the profile runs changed (a dock change, the first stage under a + /// module), so the next ask reads them first and nothing is asked before it. restock: bool, keep_lines: u32, } @@ -99,6 +115,7 @@ impl ClockHold { Self { stage: None, mode, + started: false, again: None, restock: false, keep_lines: 0, @@ -107,41 +124,49 @@ impl ClockHold { pub fn set_stage(&mut self, stage: ClockStage) { tracing::info!("clocks: {stage:?}"); + if !std::mem::replace(&mut self.started, true) && module().is_some() { + // A hold a crash left would read as the profile's rate: let go of it, then read. + release(); + self.restock = true; + self.again = Some(Instant::now() + AGAIN_AFTER); + } if stage == ClockStage::System { - // Found first, so a module's hold from a crash is let go too; with no stage the - // title stops asking again. - module(); + // With no stage the title stops asking again. release(); self.stage = None; return; } self.stage = Some(stage); - self.apply(); + if !self.restock { + self.apply(); + } } - /// A dock change. With no module the system's rates change with it: they are read once the - /// system has set them, at the performance-mode message or [`AGAIN_AFTER`] from here. + /// A dock change: the rates the system or the profile runs change with it. A module's holds + /// are let go so it can put the new ones back, and they are read [`AGAIN_AFTER`] from here. pub fn mode_changed(&mut self, mode: OperationMode) { self.mode = mode; + if self.stage.is_none() { + return; + } if module().is_some() { - self.apply(); - } else if self.stage.is_some() { - self.restock = true; - self.again = Some(Instant::now() + AGAIN_AFTER); + release(); } + self.restock = true; + self.again = Some(Instant::now() + AGAIN_AFTER); } /// The system may have put its own clocks back: a wake, a return to focus, a new performance - /// mode. With no module the title asks again now and once more [`AGAIN_AFTER`] later. + /// mode. The title asks again now and once more [`AGAIN_AFTER`] later. pub fn system_moved(&mut self, why: &str) { - if self.stage.is_none() || module().is_some() { + if self.stage.is_none() || self.restock { return; } if self.keep_lines < KEEP_LINES { self.keep_lines += 1; tracing::info!("clocks: {why}, asking again"); } - self.reask(); + self.apply(); self.again = Some(Instant::now() + AGAIN_AFTER); } @@ -149,24 +174,27 @@ impl ClockHold { pub fn tick(&mut self) { if self.again.is_some_and(|at| Instant::now() >= at) { self.again = None; - self.reask(); - } - } - - /// Asks again, reading the system's rates first after a dock change. - fn reask(&mut self) { - if std::mem::take(&mut self.restock) { - if let Some(c) = clk::clocks() { - store_stock(&[c.cpu_hz, c.gpu_hz, c.emc_hz]); + if std::mem::take(&mut self.restock) { + read_stock(); } + self.apply(); } - self.apply(); } fn apply(&mut self) { let Some(stage) = self.stage else { return }; let targets = stage.targets(self.mode); - let wanted = [targets.cpu_hz, targets.gpu_hz, targets.emc_hz]; + let stock = STOCK.each_ref().map(|s| s.load(Ordering::Relaxed)); + let running = Clocks { + cpu_hz: stock[0], + gpu_hz: stock[1], + emc_hz: stock[2], + }; + let held = targets.above(running); + if self.keep_lines < KEEP_LINES { + tracing::info!("clocks: {stage:?} {}", held.describe(running)); + } + let wanted = [held.cpu_hz, held.gpu_hz, held.emc_hz]; if let Some(module) = module() { for ((id, _), hz) in CLOCKS.into_iter().zip(wanted) { if let Err(rc) = module.hold(id, hz.unwrap_or(0)) { @@ -175,8 +203,8 @@ impl ClockHold { } return; } - for (((_, id), hz), stock) in CLOCKS.into_iter().zip(wanted).zip(&STOCK) { - let hz = hz.unwrap_or_else(|| stock.load(Ordering::Relaxed)); + for (((_, id), hz), stock) in CLOCKS.into_iter().zip(wanted).zip(stock) { + let hz = hz.unwrap_or(stock); if hz == 0 { continue; }