Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions crates/pf-nx-app/src/platform/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,43 @@ pub trait Lifecycle {
fn keyboard(&mut self) -> Option<String> {
None
}

/// Where the title's threads run, for the logs. `None` where nothing tracks them.
fn thread_probe(&self) -> Option<Arc<dyn ThreadProbe>> {
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<Arc<dyn ThreadProbe>> = std::sync::OnceLock::new();

/// Publishes the platform's probe. Call once, before the first thread spawns.
pub fn install_thread_probe(probe: Arc<dyn ThreadProbe>) {
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<T>(handle: &std::thread::JoinHandle<T>) {
#[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<String> {
THREAD_PROBE.get().map(|probe| probe.report())
}

/// The CPU, GPU and memory clocks, in Hz.
Expand Down
3 changes: 3 additions & 0 deletions crates/pf-nx-app/src/runtime/menu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,9 @@ pub(super) fn run(app: &mut App, notice: Option<String>) -> Result<UiOutcome> {
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;
Expand Down
3 changes: 3 additions & 0 deletions crates/pf-nx-app/src/runtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
4 changes: 4 additions & 0 deletions crates/pf-nx-app/src/runtime/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
}

Expand Down Expand Up @@ -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{}",
Expand Down
1 change: 1 addition & 0 deletions crates/pf-nx-app/src/session/audio_out.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions crates/pf-nx-app/src/session/pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
1 change: 1 addition & 0 deletions crates/pf-nx-app/src/session/pump.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
77 changes: 75 additions & 2 deletions crates/pf-nx-platform/src/console/lifecycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<HookEvent>,
Expand Down Expand Up @@ -103,6 +107,10 @@ impl Lifecycle for NxLifecycle {
}
}

fn thread_probe(&self) -> Option<Arc<dyn ThreadProbe>> {
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) -> ! {
Expand All @@ -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);
Expand Down
14 changes: 14 additions & 0 deletions crates/pf-nx-sys/src/rt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,16 +110,30 @@ 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::<u32>().read() });
}
rc
}

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
Expand Down
Loading
Loading