From 30f8daa5745609b897a1e49a55b56b1c97c53131 Mon Sep 17 00:00:00 2001 From: Gava <21977618+broslife@users.noreply.github.com> Date: Sat, 7 Nov 2026 12:38:31 -0300 Subject: [PATCH] feat(net): log the title's socket calls every ten seconds The stream's network term holds the console's whole receive path, and core 3 runs near 90 percent at stock clocks. The docked limit follows the CPU clock, so the next change needs the read's own numbers. The link wraps poll, recvmmsg, recv, recvfrom, send and sendto, as in the closed PR 12 but without its A/B switches. A stream logs one line every ten seconds with the rates, datagrams per read, microseconds a datagram and the window's share spent in recvmmsg. Co-Authored-By: Claude Opus 5.5 --- crates/pf-nx-app/src/platform/mod.rs | 52 +++++++ crates/pf-nx-app/src/runtime/mod.rs | 14 +- crates/pf-nx-app/src/runtime/stream.rs | 4 + crates/pf-nx-app/tests/seams.rs | 28 +++- .../pf-nx-platform/src/console/lifecycle.rs | 16 +- crates/pf-nx-sys/src/rt.rs | 137 +++++++++++++++++- toolchain/README.md | 2 +- toolchain/aarch64-nintendo-horizon.json | 8 +- 8 files changed, 255 insertions(+), 6 deletions(-) diff --git a/crates/pf-nx-app/src/platform/mod.rs b/crates/pf-nx-app/src/platform/mod.rs index d3a8460..1e903e9 100644 --- a/crates/pf-nx-app/src/platform/mod.rs +++ b/crates/pf-nx-app/src/platform/mod.rs @@ -336,6 +336,12 @@ pub trait Lifecycle { None } + /// The socket calls made since the title started, for the logs. `None` where nothing counts + /// them: a dev box. + fn socket_calls(&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 { @@ -343,6 +349,52 @@ pub trait Lifecycle { } } +/// The console's socket calls since the title started. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct SocketCalls { + pub polls: u64, + pub batch_reads: u64, + pub batch_datagrams: u64, + pub batch_read_ns: u64, + pub recvs: u64, + pub recv_froms: u64, + pub sends: u64, + pub send_tos: u64, +} + +impl SocketCalls { + /// One summary of the calls since `before`, `secs` ago, as rates a second. + pub fn window(&self, before: &Self, secs: f64) -> String { + let reads = self.batch_reads - before.batch_reads; + let datagrams = self.batch_datagrams - before.batch_datagrams; + let read_ns = self.batch_read_ns - before.batch_read_ns; + let polls = self.polls - before.polls; + let recvs = self.recvs - before.recvs; + let recv_froms = self.recv_froms - before.recv_froms; + let sends = self.sends - before.sends; + let send_tos = self.send_tos - before.send_tos; + let total = polls + reads + recvs + recv_froms + sends + send_tos; + let rate = |n: u64| n as f64 / secs.max(0.001); + let each = |n: u64| n as f64 / reads.max(1) as f64; + let per_datagram_us = read_ns as f64 / datagrams.max(1) as f64 / 1e3; + let read_share = read_ns as f64 / (secs.max(0.001) * 1e7); + format!( + "socket calls {secs:.1}s: {:.0}/s | poll {:.0}, recvmmsg {:.0} ({:.1} datagrams, {:.0} us each), recv {:.0}, \ + recvfrom {:.0}, send {:.0}, sendto {:.0} a second | {per_datagram_us:.0} us a datagram, \ + {read_share:.0}% of the window in recvmmsg", + rate(total), + rate(polls), + rate(reads), + each(datagrams), + each(read_ns) / 1e3, + rate(recvs), + rate(recv_froms), + rate(sends), + rate(send_tos), + ) + } +} + /// The CPU, GPU and memory clocks, in Hz. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Clocks { diff --git a/crates/pf-nx-app/src/runtime/mod.rs b/crates/pf-nx-app/src/runtime/mod.rs index 0054023..df91fd2 100644 --- a/crates/pf-nx-app/src/runtime/mod.rs +++ b/crates/pf-nx-app/src/runtime/mod.rs @@ -13,9 +13,10 @@ pub mod testrun; mod touch; use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Instant; use crate::core::model::bitrate_max_kbps; -use crate::platform::{Display, Lifecycle, Pads, Platform, SystemEvent}; +use crate::platform::{Display, Lifecycle, Pads, Platform, SocketCalls, SystemEvent}; use crate::services::power::ExitPlan; use crate::services::store; use crate::session::{self, Media}; @@ -55,6 +56,17 @@ impl App { .clocks() .map_or_else(String::new, |c| format!(" | clocks {c}")) } + + /// The socket calls since the last call, one summary; the first call only starts the count. + fn socket_window(&self, last: &mut Option<(SocketCalls, Instant)>) -> Option { + let now = self.lifecycle.socket_calls()?; + let at = Instant::now(); + let window = last + .as_ref() + .map(|(before, then)| now.window(before, at.duration_since(*then).as_secs_f64())); + *last = Some((now, at)); + window + } } /// Sleep is on its way: no new session may start. diff --git a/crates/pf-nx-app/src/runtime/stream.rs b/crates/pf-nx-app/src/runtime/stream.rs index d3a67e2..6805fdd 100644 --- a/crates/pf-nx-app/src/runtime/stream.rs +++ b/crates/pf-nx-app/src/runtime/stream.rs @@ -358,6 +358,7 @@ fn stream( let mut last_elapsed = Duration::ZERO; let mut dial_was_open = false; let mut perf = StreamPerf::default(); + let mut sockets = None; let mut last_frame = Instant::now(); let next = loop { @@ -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(line) = app.socket_window(&mut sockets) { + tracing::info!("{line}"); + } } let mut present = pf_l10n::console::console_overlay_present_frames(perf.frames, perf.missed); if connected.stats.holding.load(Ordering::Relaxed) { diff --git a/crates/pf-nx-app/tests/seams.rs b/crates/pf-nx-app/tests/seams.rs index 14da33f..06d43b1 100644 --- a/crates/pf-nx-app/tests/seams.rs +++ b/crates/pf-nx-app/tests/seams.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use pf_nx_app::platform::fake::{FakeAudio, FakeDisplay, FakeLifecycle, FakePads, FakeStorage, FakeVideo}; -use pf_nx_app::platform::{AudioOut, Display, Pads, Platform, Refresh, Storage}; +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. #[test] @@ -90,3 +90,29 @@ fn a_menu_test_run_leaves_a_bundle_and_exits() { assert!(bundle.join("frame-menu.png").exists()); assert!(bundle.join("environment.json").exists()); } + +/// A window's rates come from what changed since the last one. +#[test] +fn a_socket_window_reads_as_rates() { + let before = SocketCalls { + polls: 100, + batch_reads: 50, + batch_datagrams: 200, + ..SocketCalls::default() + }; + let now = SocketCalls { + polls: 300, + batch_reads: 150, + batch_datagrams: 600, + batch_read_ns: 20_000_000, + sends: 40, + ..before + }; + let line = now.window(&before, 10.0); + assert!(line.starts_with("socket calls 10.0s: 34/s"), "{line}"); + assert!(line.contains("recvmmsg 10 (4.0 datagrams, 200 us each)"), "{line}"); + assert!( + line.ends_with("50 us a datagram, 0% of the window in recvmmsg"), + "{line}" + ); +} diff --git a/crates/pf-nx-platform/src/console/lifecycle.rs b/crates/pf-nx-platform/src/console/lifecycle.rs index cad21be..9ec5ba9 100644 --- a/crates/pf-nx-platform/src/console/lifecycle.rs +++ b/crates/pf-nx-platform/src/console/lifecycle.rs @@ -7,7 +7,7 @@ use std::sync::mpsc; use std::time::{Duration, Instant}; -use pf_nx_app::platform::{Clocks, Lifecycle, SystemEvent}; +use pf_nx_app::platform::{Clocks, Lifecycle, SocketCalls, SystemEvent}; use pf_nx_sys::applet::{self, FocusState, HookEvent}; use pf_nx_sys::{clk, mem, rt, socket, swkbd}; @@ -93,6 +93,20 @@ impl Lifecycle for NxLifecycle { }) } + fn socket_calls(&self) -> Option { + let c = rt::socket_calls(); + Some(SocketCalls { + polls: c.polls, + batch_reads: c.batch_reads, + batch_datagrams: c.batch_datagrams, + batch_read_ns: c.batch_read_ns, + recvs: c.recvs, + recv_froms: c.recv_froms, + sends: c.sends, + send_tos: c.send_tos, + }) + } + fn keyboard(&mut self) -> Option { match swkbd::ask("Text to type on the PC", "Send") { Ok(text) => Some(text), diff --git a/crates/pf-nx-sys/src/rt.rs b/crates/pf-nx-sys/src/rt.rs index bf00c8f..f0a4516 100644 --- a/crates/pf-nx-sys/src/rt.rs +++ b/crates/pf-nx-sys/src/rt.rs @@ -6,7 +6,7 @@ use core::arch::asm; use core::ffi::{c_char, c_int, c_long, c_void}; -use core::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering}; +use core::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}; use std::time::{Duration, Instant}; extern "C" { @@ -23,6 +23,26 @@ extern "C" { fn __real_rename(old: *const c_char, new: *const c_char) -> c_int; fn __real_rmdir(path: *const c_char) -> c_int; fn __real_setsockopt(fd: c_int, level: c_int, name: c_int, value: *const c_void, len: u32) -> c_int; + fn __real_poll(fds: *mut c_void, nfds: u32, timeout: c_int) -> c_int; + fn __real_recvmmsg(fd: c_int, msgs: *mut c_void, vlen: u32, flags: c_int, timeout: *mut c_void) -> c_int; + fn __real_recv(fd: c_int, buf: *mut c_void, len: usize, flags: c_int) -> isize; + fn __real_recvfrom( + fd: c_int, + buf: *mut c_void, + len: usize, + flags: c_int, + addr: *mut c_void, + addr_len: *mut u32, + ) -> isize; + fn __real_send(fd: c_int, buf: *const c_void, len: usize, flags: c_int) -> isize; + fn __real_sendto( + fd: c_int, + buf: *const c_void, + len: usize, + flags: c_int, + addr: *const c_void, + addr_len: u32, + ) -> isize; fn __errno() -> *mut c_int; fn threadClose(t: *mut c_void) -> u32; fn __libnx_free(p: *mut c_void); @@ -384,6 +404,121 @@ pub unsafe extern "C" fn __wrap_setsockopt( } } +static POLLS: AtomicU64 = AtomicU64::new(0); +static BATCH_READS: AtomicU64 = AtomicU64::new(0); +static BATCH_DATAGRAMS: AtomicU64 = AtomicU64::new(0); +static BATCH_READ_NS: AtomicU64 = AtomicU64::new(0); +static RECVS: AtomicU64 = AtomicU64::new(0); +static RECV_FROMS: AtomicU64 = AtomicU64::new(0); +static SENDS: AtomicU64 = AtomicU64::new(0); +static SEND_TOS: AtomicU64 = AtomicU64::new(0); + +/// The socket calls made since the title started. Each is one IPC to the `bsd` service, which +/// the system serves on core 3. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct SocketCalls { + pub polls: u64, + pub batch_reads: u64, + pub batch_datagrams: u64, + pub batch_read_ns: u64, + pub recvs: u64, + pub recv_froms: u64, + pub sends: u64, + pub send_tos: u64, +} + +pub fn socket_calls() -> SocketCalls { + let read = |n: &AtomicU64| n.load(Ordering::Relaxed); + SocketCalls { + polls: read(&POLLS), + batch_reads: read(&BATCH_READS), + batch_datagrams: read(&BATCH_DATAGRAMS), + batch_read_ns: read(&BATCH_READ_NS), + recvs: read(&RECVS), + recv_froms: read(&RECV_FROMS), + sends: read(&SENDS), + send_tos: read(&SEND_TOS), + } +} + +/// # Safety +/// As `poll`. +#[no_mangle] +pub unsafe extern "C" fn __wrap_poll(fds: *mut c_void, nfds: u32, timeout: c_int) -> c_int { + POLLS.fetch_add(1, Ordering::Relaxed); + // SAFETY: the caller's arguments. + unsafe { __real_poll(fds, nfds, timeout) } +} + +/// # Safety +/// As `recvmmsg`. +#[no_mangle] +pub unsafe extern "C" fn __wrap_recvmmsg( + fd: c_int, + msgs: *mut c_void, + vlen: u32, + flags: c_int, + timeout: *mut c_void, +) -> c_int { + let start = Instant::now(); + // SAFETY: the caller's arguments. + let got = unsafe { __real_recvmmsg(fd, msgs, vlen, flags, timeout) }; + BATCH_READ_NS.fetch_add(start.elapsed().as_nanos() as u64, Ordering::Relaxed); + BATCH_READS.fetch_add(1, Ordering::Relaxed); + BATCH_DATAGRAMS.fetch_add(got.max(0) as u64, Ordering::Relaxed); + got +} + +/// # Safety +/// As `recv`. +#[no_mangle] +pub unsafe extern "C" fn __wrap_recv(fd: c_int, buf: *mut c_void, len: usize, flags: c_int) -> isize { + RECVS.fetch_add(1, Ordering::Relaxed); + // SAFETY: the caller's arguments. + unsafe { __real_recv(fd, buf, len, flags) } +} + +/// # Safety +/// As `recvfrom`. +#[no_mangle] +pub unsafe extern "C" fn __wrap_recvfrom( + fd: c_int, + buf: *mut c_void, + len: usize, + flags: c_int, + addr: *mut c_void, + addr_len: *mut u32, +) -> isize { + RECV_FROMS.fetch_add(1, Ordering::Relaxed); + // SAFETY: the caller's arguments. + unsafe { __real_recvfrom(fd, buf, len, flags, addr, addr_len) } +} + +/// # Safety +/// As `send`. +#[no_mangle] +pub unsafe extern "C" fn __wrap_send(fd: c_int, buf: *const c_void, len: usize, flags: c_int) -> isize { + SENDS.fetch_add(1, Ordering::Relaxed); + // SAFETY: the caller's arguments. + unsafe { __real_send(fd, buf, len, flags) } +} + +/// # Safety +/// As `sendto`. +#[no_mangle] +pub unsafe extern "C" fn __wrap_sendto( + fd: c_int, + buf: *const c_void, + len: usize, + flags: c_int, + addr: *const c_void, + addr_len: u32, +) -> isize { + SEND_TOS.fetch_add(1, Ordering::Relaxed); + // SAFETY: the caller's arguments. + unsafe { __real_sendto(fd, buf, len, flags, addr, addr_len) } +} + /// libnx's crt0 runs `.init_array` through these; rust-lld links no crti/crtn to define them. #[no_mangle] pub extern "C" fn _init() {} diff --git a/toolchain/README.md b/toolchain/README.md index ea4bd34..ab76c56 100644 --- a/toolchain/README.md +++ b/toolchain/README.md @@ -6,7 +6,7 @@ invocation), `docker/Dockerfile` (devkitA64, libnx, switch-tools and the nightly | Path | What | | --- | --- | -| `aarch64-nintendo-horizon.json` | The target: `os = "horizon"`, `env = "newlib"`, `rust-lld`, the link script that puts libnx's crt0 first, and `--wrap` for `threadCreate`, `fchmod`, `rename`, `rmdir`. | +| `aarch64-nintendo-horizon.json` | The target: `os = "horizon"`, `env = "newlib"`, `rust-lld`, the link script that puts libnx's crt0 first, and `--wrap` for `threadCreate`, `fchmod`, `rename`, `rmdir`, `setsockopt` and the socket calls the title counts. | | `patches//` | The crate legs: crates.io source plus Horizon arms, applied by `.cargo/config.toml`. Each `LEG.md` names the upstream version, the origin and the change. | | `include/` | C headers devkitA64's newlib lacks (`sys/termios.h` for aws-lc). | | `skia/` | What `scripts/build-skia.sh` builds Skia with for the console: the `cc`/`c++` wrappers, `args.gn`, `horizon.patch`, `compat.c` (the `mmap` family over the heap), `include/sys/mman.h`, and `layout-check.py`, which proves bindgen's Linux parse of the headers against devkitA64's G++. | diff --git a/toolchain/aarch64-nintendo-horizon.json b/toolchain/aarch64-nintendo-horizon.json index a97ceaa..2ef6d60 100644 --- a/toolchain/aarch64-nintendo-horizon.json +++ b/toolchain/aarch64-nintendo-horizon.json @@ -29,7 +29,13 @@ "--wrap=fchmod", "--wrap=rename", "--wrap=rmdir", - "--wrap=setsockopt" + "--wrap=setsockopt", + "--wrap=poll", + "--wrap=recvmmsg", + "--wrap=recv", + "--wrap=recvfrom", + "--wrap=send", + "--wrap=sendto" ] }, "relocation-model": "pic",