From 16a1260803b90328e1938a6d52775001f32809fd Mon Sep 17 00:00:00 2001 From: Gava <21977618+broslife@users.noreply.github.com> Date: Mon, 2 Nov 2026 17:55:26 -0300 Subject: [PATCH] feat(threads): the 10 s summaries say which core each thread runs on Every thread the threadCreate wrapper starts registers with the core it woke up on; main registers at the first report. Each menu and stream summary is followed by a `threads:` line: the process's core mask, each core's load from the title's threads, and for each thread its start core, core mask, priority and share of each core. The spawners of the video, audio and input threads name them in the registry. This is the probe before any thread is placed on another core. Co-Authored-By: Claude Opus 5.5 --- crates/pf-nx-app/src/platform/mod.rs | 37 +++ crates/pf-nx-app/src/runtime/menu.rs | 3 + crates/pf-nx-app/src/runtime/mod.rs | 3 + crates/pf-nx-app/src/runtime/stream.rs | 4 + crates/pf-nx-app/src/session/audio_out.rs | 1 + crates/pf-nx-app/src/session/pipeline.rs | 1 + crates/pf-nx-app/src/session/pump.rs | 1 + .../pf-nx-platform/src/console/lifecycle.rs | 77 +++++- crates/pf-nx-sys/src/rt.rs | 14 ++ crates/pf-nx-sys/src/thread.rs | 226 ++++++++++++++++++ 10 files changed, 365 insertions(+), 2 deletions(-) diff --git a/crates/pf-nx-app/src/platform/mod.rs b/crates/pf-nx-app/src/platform/mod.rs index 1401bfa..3962370 100644 --- a/crates/pf-nx-app/src/platform/mod.rs +++ b/crates/pf-nx-app/src/platform/mod.rs @@ -334,6 +334,43 @@ pub trait Lifecycle { fn keyboard(&mut self) -> Option { None } + + /// Where the title's threads run, for the logs. `None` where nothing tracks them. + fn thread_probe(&self) -> Option> { + None + } +} + +/// Which core each of the title's threads runs on and how busy it keeps it. +pub trait ThreadProbe: Send + Sync { + /// A thread its spawner just started: `pthread` is std's `as_pthread_t`. + fn spawned(&self, pthread: usize, name: &str); + /// One line on every thread, with its share of each core since the last call. + fn report(&self) -> String; +} + +static THREAD_PROBE: std::sync::OnceLock> = std::sync::OnceLock::new(); + +/// Publishes the platform's probe. Call once, before the first thread spawns. +pub fn install_thread_probe(probe: Arc) { + let _ = THREAD_PROBE.set(probe); +} + +/// Tells the probe the name of the thread `handle` joins. The spawner calls it: a thread is never +/// named from inside itself. +pub fn thread_spawned(handle: &std::thread::JoinHandle) { + #[cfg(unix)] + if let (Some(probe), Some(name)) = (THREAD_PROBE.get(), handle.thread().name()) { + use std::os::unix::thread::JoinHandleExt; + probe.spawned(handle.as_pthread_t() as usize, name); + } + #[cfg(not(unix))] + let _ = handle; +} + +/// The probe's line for a 10 s summary, `None` without one. +pub fn thread_report() -> Option { + THREAD_PROBE.get().map(|probe| probe.report()) } /// The CPU, GPU and memory clocks, in Hz. diff --git a/crates/pf-nx-app/src/runtime/menu.rs b/crates/pf-nx-app/src/runtime/menu.rs index 8127425..d3b1e8d 100644 --- a/crates/pf-nx-app/src/runtime/menu.rs +++ b/crates/pf-nx-app/src/runtime/menu.rs @@ -223,6 +223,9 @@ pub(super) fn run(app: &mut App, notice: Option) -> Result { frames += 1; if let Some(report) = perf.frame(before_draw + drew, art_snapshot()) { tracing::info!("{}{}", report.line(), app.clocks_suffix()); + if let Some(threads) = crate::platform::thread_report() { + tracing::info!("threads: {threads}"); + } } if let Some(done) = testrun::menu_step(app, frames) { break 'ui done; diff --git a/crates/pf-nx-app/src/runtime/mod.rs b/crates/pf-nx-app/src/runtime/mod.rs index c7dccac..a274d03 100644 --- a/crates/pf-nx-app/src/runtime/mod.rs +++ b/crates/pf-nx-app/src/runtime/mod.rs @@ -99,6 +99,9 @@ pub fn run(platform: Platform) -> ! { log, device, } = platform; + if let Some(probe) = lifecycle.thread_probe() { + crate::platform::install_thread_probe(probe); + } 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(); diff --git a/crates/pf-nx-app/src/runtime/stream.rs b/crates/pf-nx-app/src/runtime/stream.rs index 92f20e5..f80d406 100644 --- a/crates/pf-nx-app/src/runtime/stream.rs +++ b/crates/pf-nx-app/src/runtime/stream.rs @@ -65,6 +65,7 @@ impl InputThread { .name("pf-input".into()) .spawn(move || input_loop(pads, &input, kind, output, &thread_stop, &rx, &tx)) .expect("spawn the input thread"); + crate::platform::thread_spawned(&handle); Self { stop, to, from, handle } } @@ -426,6 +427,9 @@ fn stream( if let Some(core) = hud.refresh(connected, decoder) { tracing::info!("stats: {} | {core}{}", perf.take_window(), app.clocks_suffix()); + if let Some(threads) = crate::platform::thread_report() { + tracing::info!("threads: {threads}"); + } } hud.local = vec![format!( "present: {} frames, {} missed{}", diff --git a/crates/pf-nx-app/src/session/audio_out.rs b/crates/pf-nx-app/src/session/audio_out.rs index 5b33dae..938e1c6 100644 --- a/crates/pf-nx-app/src/session/audio_out.rs +++ b/crates/pf-nx-app/src/session/audio_out.rs @@ -148,6 +148,7 @@ impl AudioOutSink { .name("pf-audio-out".into()) .spawn(move || write_loop(&thread_shared, port, usize::from(channels))) .context("spawn audio writer")?; + crate::platform::thread_spawned(&writer); Ok(Self { shared, channels, diff --git a/crates/pf-nx-app/src/session/pipeline.rs b/crates/pf-nx-app/src/session/pipeline.rs index 4045cef..aaff68f 100644 --- a/crates/pf-nx-app/src/session/pipeline.rs +++ b/crates/pf-nx-app/src/session/pipeline.rs @@ -188,4 +188,5 @@ fn spawn_video_thread( video_pump(client, stage, first, opener, stop, stats, is_hdr); }) .context("spawn video thread") + .inspect(crate::platform::thread_spawned) } diff --git a/crates/pf-nx-app/src/session/pump.rs b/crates/pf-nx-app/src/session/pump.rs index cc3bde4..33f2531 100644 --- a/crates/pf-nx-app/src/session/pump.rs +++ b/crates/pf-nx-app/src/session/pump.rs @@ -514,6 +514,7 @@ pub fn spawn_audio_feed( .name("pf-audio-pump".into()) .spawn(move || audio_pump(&client, &mut stage, &stop)) .context("spawn audio thread") + .inspect(crate::platform::thread_spawned) } /// One cadence series for the heartbeat: how many intervals, which way they ran, how irregular they diff --git a/crates/pf-nx-platform/src/console/lifecycle.rs b/crates/pf-nx-platform/src/console/lifecycle.rs index cad21be..fb9b8f6 100644 --- a/crates/pf-nx-platform/src/console/lifecycle.rs +++ b/crates/pf-nx-platform/src/console/lifecycle.rs @@ -7,9 +7,13 @@ use std::sync::mpsc; use std::time::{Duration, Instant}; -use pf_nx_app::platform::{Clocks, Lifecycle, SystemEvent}; +use std::fmt::Write as _; +use std::sync::Arc; + +use pf_nx_app::platform::{Clocks, Lifecycle, SystemEvent, ThreadProbe}; use pf_nx_sys::applet::{self, FocusState, HookEvent}; -use pf_nx_sys::{clk, mem, rt, socket, swkbd}; +use pf_nx_sys::thread::{ThreadSample, CORES}; +use pf_nx_sys::{clk, mem, rt, socket, swkbd, thread}; pub struct NxLifecycle { events: mpsc::Receiver, @@ -103,6 +107,10 @@ impl Lifecycle for NxLifecycle { } } + fn thread_probe(&self) -> Option> { + Some(Arc::new(NxThreads)) + } + /// 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. fn exit(&self) -> ! { @@ -113,6 +121,71 @@ impl Lifecycle for NxLifecycle { } } +/// `pf-nx-sys`'s thread registry: every thread `threadCreate` started, numbered in creation order. +struct NxThreads; + +impl ThreadProbe for NxThreads { + fn spawned(&self, pthread: usize, name: &str) { + // SAFETY: std's `as_pthread_t` of a thread whose handle its spawner still holds. + unsafe { thread::name_spawned(pthread, name) }; + } + + /// `proc 0x7 | cores 0:62% 1:0% 2:0% 3:0% | #3 pf-video-pump s0 m0x1 p0x2c 0:31% | gone #9 …`: + /// for each thread its start core, core mask, priority and share of each core it ran on. + fn report(&self) -> String { + let report = thread::report(); + let mut line = match report.process_mask { + Some(mask) => format!("proc {mask:#x}"), + None => "proc ?".to_string(), + }; + let mut cores = [0f32; CORES]; + for t in &report.threads { + for (sum, busy) in cores.iter_mut().zip(t.busy) { + *sum += busy.unwrap_or(0.0); + } + } + line.push_str(" | cores"); + for (core, busy) in cores.iter().enumerate() { + let _ = write!(line, " {core}:{:.0}%", busy * 100.0); + } + if let Some(rc) = report.tick_error { + let _ = write!(line, " (ticks refused {})", pf_nx_sys::result_code(rc)); + } + for t in &report.threads { + line.push_str(" | "); + describe(&mut line, t); + } + for t in &report.gone { + line.push_str(" | gone "); + describe(&mut line, t); + } + line + } +} + +fn describe(line: &mut String, t: &ThreadSample) { + let unknown = || "?".to_string(); + let _ = write!( + line, + "#{} {} s{} m{} p{}", + t.seq, + t.name.as_deref().unwrap_or("?"), + t.start_core.map_or_else(unknown, |c| c.to_string()), + t.mask.map_or_else(unknown, |m| format!("{m:#x}")), + t.priority.map_or_else(unknown, |p| format!("{p:#x}")), + ); + // The preferred core only where it is not the one the thread started on. + let start = t.start_core.and_then(|s| i32::try_from(s).ok()); + if let Some(preferred) = t.preferred.filter(|&p| Some(p) != start) { + let _ = write!(line, " pref{preferred}"); + } + for (core, busy) in t.busy.iter().enumerate() { + if let Some(busy) = busy.filter(|b| *b >= 0.005) { + let _ = write!(line, " {core}:{:.0}%", busy * 100.0); + } + } +} + /// How long the exit waits for detached threads to end, and again for services to unmap their /// transfer memory (`socketExit` does not wait for it). const RELEASE_WAIT: Duration = Duration::from_secs(1); diff --git a/crates/pf-nx-sys/src/rt.rs b/crates/pf-nx-sys/src/rt.rs index bf00c8f..e3b93ae 100644 --- a/crates/pf-nx-sys/src/rt.rs +++ b/crates/pf-nx-sys/src/rt.rs @@ -110,6 +110,10 @@ pub unsafe extern "C" fn __wrap_threadCreate( if rc != 0 { // SAFETY: no thread was created, so `start` is still only ours. drop(unsafe { Box::from_raw(start) }); + } else { + // SAFETY: libnx filled `t`, whose first field is the new thread's handle; the thread + // waits for `threadStart`, so it is numbered before it runs. + crate::thread::created(unsafe { t.cast::().read() }); } rc } @@ -117,9 +121,19 @@ pub unsafe extern "C" fn __wrap_threadCreate( unsafe extern "C" fn thread_start(start: *mut c_void) { set_thread_pointer(); // SAFETY: `start` is the box `__wrap_threadCreate` leaked for this thread alone. + unsafe { run_entry(start) }; +} + +/// The thread's entry between its registry's start and finish, apart from `thread_start`, which +/// must not touch a thread-local before the pointer is set. +#[inline(never)] +unsafe fn run_entry(start: *mut c_void) { + // SAFETY: as `thread_start`. let (entry, arg) = *unsafe { Box::from_raw(start.cast::<(ThreadFunc, *mut c_void)>()) }; + crate::thread::started(); // SAFETY: the entry and argument the thread's creator passed to `threadCreate`. unsafe { entry(arg) }; + crate::thread::finished(); } // std detaches a thread whenever its `JoinHandle` drops unjoined (tokio's blocking pool, the diff --git a/crates/pf-nx-sys/src/thread.rs b/crates/pf-nx-sys/src/thread.rs index e983fa9..db20f39 100644 --- a/crates/pf-nx-sys/src/thread.rs +++ b/crates/pf-nx-sys/src/thread.rs @@ -11,6 +11,9 @@ mod ffi { pub fn threadGetCurHandle() -> u32; pub fn svcSetThreadPriority(handle: u32, priority: u32) -> u32; pub fn svcGetThreadCoreMask(preferred_core: *mut i32, affinity_mask: *mut u64, handle: u32) -> u32; + pub fn svcGetThreadPriority(priority: *mut i32, handle: u32) -> u32; + pub fn svcGetCurrentProcessorNumber() -> u32; + pub fn svcGetInfo(out: *mut u64, id0: u32, handle: u32, id1: u64) -> u32; } } @@ -42,3 +45,226 @@ pub fn core_mask() -> u64 { 0 } } + +// The thread registry: every thread `rt`'s `threadCreate` wrapper starts, and main, with the +// core each first ran on, so a log can say where the title's threads run and how busy each core +// is. A thread only records where it woke up; its spawner names it. + +/// Cores 0-2 run applications; core 3 is the system's, counted to show whether it stays unused. +pub const CORES: usize = 4; + +/// One live thread as the registry last saw it. +#[derive(Clone, Debug, Default)] +pub struct ThreadSample { + /// Creation order since launch. + pub seq: u32, + /// The name its spawner gave, once one has told the registry. + pub name: Option, + /// The core it first ran on; `None` before it has. + pub start_core: Option, + /// Its preferred core and the cores it may run on, `None` where the kernel refused. + pub preferred: Option, + pub mask: Option, + pub priority: Option, + /// The share of the window it ran on each core; `None` on the first report, or where the + /// kernel refused the count. + pub busy: [Option; CORES], +} + +/// What `report` found. +#[derive(Clone, Debug, Default)] +pub struct ThreadReport { + /// The cores the process may run threads on. + pub process_mask: Option, + pub threads: Vec, + /// Threads that started and ended since the last report, never seen live in one. + pub gone: Vec, + /// The first refused tick count's `Result`. + pub tick_error: Option, +} + +#[cfg(target_os = "horizon")] +mod registry { + use std::sync::{Mutex, MutexGuard, PoisonError}; + use std::time::Instant; + + use super::{ffi, ThreadReport, ThreadSample, CORES}; + + /// `svcGetInfo`'s ticks run at 19.2 MHz. + const TICK_HZ: f64 = 19_200_000.0; + /// `InfoType_CoreMask` and `InfoType_ThreadTickCount` (svc.h). + const INFO_CORE_MASK: u32 = 0; + const INFO_THREAD_TICK_COUNT: u32 = 0xF000_0002; + /// `CUR_PROCESS_HANDLE`. + const CUR_PROCESS: u32 = 0xFFFF_8001; + const GONE_MAX: usize = 16; + + struct Entry { + handle: u32, + sample: ThreadSample, + /// CPU ticks per core at the last report. + ticks: [Option; CORES], + reported: bool, + } + + struct Registry { + live: Vec, + gone: Vec, + next_seq: u32, + last_report: Option, + } + + impl Registry { + fn entry(&mut self, handle: u32) -> &mut Entry { + if let Some(i) = self.live.iter().position(|e| e.handle == handle) { + return &mut self.live[i]; + } + let seq = self.next_seq; + self.next_seq += 1; + self.live.push(Entry { + handle, + sample: ThreadSample { + seq, + ..ThreadSample::default() + }, + ticks: [None; CORES], + reported: false, + }); + self.live.last_mut().expect("just pushed") + } + } + + static REGISTRY: Mutex = Mutex::new(Registry { + live: Vec::new(), + gone: Vec::new(), + next_seq: 0, + last_report: None, + }); + + fn registry() -> MutexGuard<'static, Registry> { + REGISTRY.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// The calling thread's handle and the core it runs on now. + fn here() -> (u32, u32) { + // SAFETY: no arguments; the calling thread's own handle and core. + unsafe { (ffi::threadGetCurHandle(), ffi::svcGetCurrentProcessorNumber()) } + } + + /// A thread was created, suspended, with `handle`: it takes the next number. + pub(crate) fn created(handle: u32) { + registry().entry(handle); + } + + /// The calling thread is running: it records the core it woke up on. + pub(crate) fn started() { + let (handle, core) = here(); + registry().entry(handle).sample.start_core = Some(core); + } + + /// The calling thread's entry returned: it leaves the registry before its handle closes. + pub(crate) fn finished() { + let (handle, _) = here(); + let mut registry = registry(); + if let Some(i) = registry.live.iter().position(|e| e.handle == handle) { + let mut entry = registry.live.swap_remove(i); + // Short-lived threads between two reports, as many as a line can carry. + if !entry.reported && registry.gone.len() < GONE_MAX { + (entry.sample.preferred, entry.sample.mask) = core_mask_of(handle); + registry.gone.push(entry.sample); + } + } + } + + /// Names the thread behind `pthread`, as its spawner knows it. + /// + /// # Safety + /// `pthread` is a pthread newlib created (std's `JoinHandleExt::as_pthread_t`), not yet + /// joined. + pub unsafe fn name_spawned(pthread: usize, name: &str) { + // newlib's `THRD_MAIN_HANDLE` is no pthread. + if pthread == 0 || pthread == usize::MAX { + return; + } + // SAFETY: the caller's live pthread, whose first field is libnx's `Thread`, whose first + // is the handle. + let handle = unsafe { (pthread as *const u32).read() }; + registry().entry(handle).sample.name = Some(name.to_string()); + } + + fn core_mask_of(handle: u32) -> (Option, Option) { + let (mut preferred, mut mask) = (0i32, 0u64); + // SAFETY: both out-pointers are locals; a live thread's handle. + let rc = unsafe { ffi::svcGetThreadCoreMask(&mut preferred, &mut mask, handle) }; + if rc == 0 { + (Some(preferred), Some(mask)) + } else { + (None, None) + } + } + + /// The process's allowed cores (`InfoType_CoreMask`). + pub fn process_core_mask() -> Option { + let mut mask = 0u64; + // SAFETY: a local out-pointer; the process's own pseudo-handle. + let rc = unsafe { ffi::svcGetInfo(&mut mask, INFO_CORE_MASK, CUR_PROCESS, 0) }; + (rc == 0).then_some(mask) + } + + /// Every live thread's cores, priority and share of each core since the last call, and the + /// threads that came and went in between. The first call opens the window and names its + /// caller `main` (the run loop's thread, which `rt` never starts), whose start core is + /// where it runs then. + pub fn report() -> ThreadReport { + let now = Instant::now(); + let (caller, core) = here(); + let mut registry = registry(); + let window = match registry.last_report.replace(now) { + Some(last) => Some(now.duration_since(last).as_secs_f64() * TICK_HZ), + None => { + let main = registry.entry(caller); + main.sample.name.get_or_insert_with(|| "main".to_string()); + main.sample.start_core.get_or_insert(core); + None + } + }; + let mut report = ThreadReport { + process_mask: process_core_mask(), + gone: std::mem::take(&mut registry.gone), + ..ThreadReport::default() + }; + for entry in &mut registry.live { + entry.reported = true; + let handle = entry.handle; + (entry.sample.preferred, entry.sample.mask) = core_mask_of(handle); + let mut priority = 0i32; + // SAFETY: a local out-pointer; a live thread's handle. + let rc = unsafe { ffi::svcGetThreadPriority(&mut priority, handle) }; + entry.sample.priority = (rc == 0).then_some(priority); + for core in 0..CORES { + let mut ticks = 0u64; + // SAFETY: a local out-pointer; a live thread's handle and a core id. + let rc = unsafe { ffi::svcGetInfo(&mut ticks, INFO_THREAD_TICK_COUNT, handle, core as u64) }; + if rc != 0 { + report.tick_error.get_or_insert(rc); + } + let ticks = (rc == 0).then_some(ticks); + entry.sample.busy[core] = match (window, entry.ticks[core], ticks) { + (Some(window), Some(before), Some(after)) if window > 0.0 => { + Some((after.saturating_sub(before) as f64 / window) as f32) + } + _ => None, + }; + entry.ticks[core] = ticks; + } + report.threads.push(entry.sample.clone()); + } + report.threads.sort_by_key(|t| t.seq); + report + } +} + +#[cfg(target_os = "horizon")] +pub(crate) use registry::{created, finished, started}; +#[cfg(target_os = "horizon")] +pub use registry::{name_spawned, process_core_mask, report};