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
52 changes: 52 additions & 0 deletions crates/pf-nx-app/src/platform/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -336,13 +336,65 @@ 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<SocketCalls> {
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<String> {
None
}
}

/// 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 {
Expand Down
14 changes: 13 additions & 1 deletion crates/pf-nx-app/src/runtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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<String> {
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.
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 @@ -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 {
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(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) {
Expand Down
28 changes: 27 additions & 1 deletion crates/pf-nx-app/tests/seams.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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}"
);
}
16 changes: 15 additions & 1 deletion crates/pf-nx-platform/src/console/lifecycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down Expand Up @@ -93,6 +93,20 @@ impl Lifecycle for NxLifecycle {
})
}

fn socket_calls(&self) -> Option<SocketCalls> {
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<String> {
match swkbd::ask("Text to type on the PC", "Send") {
Ok(text) => Some(text),
Expand Down
137 changes: 136 additions & 1 deletion crates/pf-nx-sys/src/rt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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" {
Expand All @@ -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);
Expand Down Expand Up @@ -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() {}
Expand Down
2 changes: 1 addition & 1 deletion toolchain/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<crate>/` | 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++. |
Expand Down
8 changes: 7 additions & 1 deletion toolchain/aarch64-nintendo-horizon.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down