diff --git a/crates/pf-nx-app/src/platform/mod.rs b/crates/pf-nx-app/src/platform/mod.rs index 1401bfa..289dd6f 100644 --- a/crates/pf-nx-app/src/platform/mod.rs +++ b/crates/pf-nx-app/src/platform/mod.rs @@ -329,6 +329,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 { @@ -336,6 +342,63 @@ pub trait Lifecycle { } } +/// The console's socket calls since the title started, and the two A/B switches they ran under. +#[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 lean_waker: bool, + pub read_wait_us: u32, +} + +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; + 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 | lean waker {}, read wait {} us", + rate(total), + rate(polls), + rate(reads), + each(datagrams), + each(read_ns) / 1e3, + rate(recvs), + rate(recv_froms), + rate(sends), + rate(send_tos), + if self.lean_waker { "on" } else { "off" }, + self.read_wait_us, + ) + } +} + +/// The read wait a marker file asks for, in microseconds: its text is milliseconds, capped at +/// 5 ms. Anything else is no wait. +pub fn read_wait_us(text: &str) -> u32 { + let text = text.trim_start_matches('\u{feff}').trim().replace(',', "."); + text.parse::() + .ok() + .filter(|ms| ms.is_finite() && *ms > 0.0) + .map_or(0, |ms| (ms.min(5.0) * 1000.0) as u32) +} + /// 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 c7dccac..45f87b1 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 92f20e5..5b32a76 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}"); + } } hud.local = vec![format!( "present: {} frames, {} missed{}", diff --git a/crates/pf-nx-app/tests/seams.rs b/crates/pf-nx-app/tests/seams.rs index 14da33f..9e8e758 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::{read_wait_us, 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,38 @@ 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, and it names both switches. +#[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, + lean_waker: true, + read_wait_us: 1000, + ..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("lean waker on, read wait 1000 us"), "{line}"); +} + +/// A marker holds milliseconds as any text editor writes them. +#[test] +fn a_read_wait_marker_is_milliseconds() { + assert_eq!(read_wait_us("1"), 1000); + assert_eq!(read_wait_us("\u{feff}0,5\r\n"), 500); + assert_eq!(read_wait_us("60"), 5000); + assert_eq!(read_wait_us(""), 0); + assert_eq!(read_wait_us("-1"), 0); +} diff --git a/crates/pf-nx-platform/src/console/lifecycle.rs b/crates/pf-nx-platform/src/console/lifecycle.rs index cad21be..4de58bf 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,23 @@ impl Lifecycle for NxLifecycle { }) } + fn socket_calls(&self) -> Option { + let c = rt::socket_calls(); + let (lean_waker, read_wait_us) = super::socket_switches(); + 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, + lean_waker, + read_wait_us, + }) + } + 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-platform/src/console/mod.rs b/crates/pf-nx-platform/src/console/mod.rs index 066728a..e5b01b0 100644 --- a/crates/pf-nx-platform/src/console/mod.rs +++ b/crates/pf-nx-platform/src/console/mod.rs @@ -9,10 +9,11 @@ mod pads; use std::io::Write; use std::path::{Path, PathBuf}; use std::sync::{Arc, OnceLock}; +use std::time::Duration; use anyhow::{Context, Result}; -use pf_nx_app::platform::{DeviceInfo, Display, OperationMode, Platform, Storage, VideoDecoders}; -use pf_nx_sys::{applet, nvk, setsys, socket, vi}; +use pf_nx_app::platform::{read_wait_us, DeviceInfo, Display, OperationMode, Platform, Storage, VideoDecoders}; +use pf_nx_sys::{applet, nvk, rt, setsys, socket, vi}; use pf_nx_vk::{GpuDevice, Presenter, Target, VideoSlot}; /// Identity, settings, logs and bundles; the NRO itself lives here too (plan D18). @@ -22,6 +23,13 @@ const DATA_DIR: &str = "sdmc:/switch/punktfunk"; /// build A/Bs both routes. const STRAIGHT_MARKER: &str = "vic-direto"; +/// A file of this name in [`DATA_DIR`], read at start, turns the mio leg's lean waker on. +const LEAN_WAKER_MARKER: &str = "despertador-leve"; + +/// A file of this name in [`DATA_DIR`], read at start, makes every batch read wait the +/// milliseconds it holds, so one build A/Bs several waits. +const READ_WAIT_MARKER: &str = "espera-leitura"; + /// The Mesa pin NVK was built from, for the log and the About screen. const MESA_PIN: &str = match option_env!("PF_MESA_PIN") { Some(p) => p, @@ -75,11 +83,31 @@ fn nxlink() -> Option> { up.then(|| Box::new(std::io::stdout()) as Box) } +/// The markers' switches, read once: whether the waker is lean, and the read wait in microseconds. +fn socket_switches() -> (bool, u32) { + static SWITCHES: OnceLock<(bool, u32)> = OnceLock::new(); + *SWITCHES.get_or_init(|| { + let dir = Path::new(DATA_DIR); + let wait = std::fs::read_to_string(dir.join(READ_WAIT_MARKER)).map_or(0, |text| read_wait_us(&text)); + (dir.join(LEAN_WAKER_MARKER).exists(), wait) + }) +} + +/// Applies the markers. Before any thread exists: `set_var` is not thread-safe. +fn apply_socket_switches() { + let (lean_waker, wait_us) = socket_switches(); + if lean_waker { + std::env::set_var("PF_NX_LEAN_WAKER", "1"); + } + rt::set_read_wait(Duration::from_micros(u64::from(wait_us))); +} + /// Builds the console platform. Sockets and nxlink come first, so a display that fails to come /// up is reported; the display comes next, as the step most likely to fail. pub fn platform(kind: DisplayKind) -> Result { let log = nxlink(); std::fs::create_dir_all(DATA_DIR).with_context(|| format!("create {DATA_DIR}"))?; + apply_socket_switches(); let (display, video, gpu, ui): (Box, Arc, String, String) = match kind { DisplayKind::Nvk => { let window = vi::default_window(); diff --git a/crates/pf-nx-sys/src/rt.rs b/crates/pf-nx-sys/src/rt.rs index bf00c8f..b8ee865 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,136 @@ 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); +/// How long a batch read waits for the rest of a burst, in nanoseconds; 0 reads at once. +static READ_WAIT_NS: AtomicU64 = AtomicU64::new(0); +/// The last batch read filled its buffers, so more is queued and waiting would gain nothing. +static BATCH_FULL: AtomicBool = AtomicBool::new(false); + +/// 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), + } +} + +/// Makes every batch read wait this long first, so one call takes more of a burst. +pub fn set_read_wait(wait: Duration) { + READ_WAIT_NS.store(wait.as_nanos() as u64, Ordering::Relaxed); +} + +/// # 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 wait = READ_WAIT_NS.load(Ordering::Relaxed); + if wait != 0 && !BATCH_FULL.load(Ordering::Relaxed) { + // SAFETY: a plain sleep of this thread. + unsafe { svcSleepThread(wait as i64) }; + } + 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); + BATCH_FULL.store(got > 0 && got as u32 == vlen, 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/docs/improvements.md b/docs/improvements.md index c304c33..29320b9 100644 --- a/docs/improvements.md +++ b/docs/improvements.md @@ -81,9 +81,26 @@ already reads up to 32 datagrams a call (`toolchain/patches/quinn-udp`, section is to find what else calls the socket per packet, and to cut it. It is separate from Performance mode and can go in parallel. +**Where the calls go,** read from the code and not yet measured on a console: + +- The shared socket's reader spends a `poll` and a `recvmmsg` per wake, even for one datagram. +- Audio rides QUIC datagrams, one per 5 ms frame, and each can wake tokio from the reader's + thread. That wake is a loopback datagram (the mio leg): a `send`, the driver's `poll`, and two + `recv` to empty the socket. +- Every QUIC ACK, input event and feedback report is its own `sendto`. + +**The A/B build.** The title counts these calls at the link (`--wrap`, `pf-nx-sys::rt`) and logs a +`socket calls` line every 10 s. Two marker files in `/switch/punktfunk/`, read at start, turn the +cuts on: + +- `despertador-leve`: a wake with one on its way sends nothing, and the ack reads once. +- `espera-leitura`, holding milliseconds: each batch read waits that long first, so one call takes + more of a frame's burst. + **Test first.** A Status Monitor screenshot at stock clocks during a stream, to confirm that core -3 is the busy one with the current build. If the remaining calls turn out to sit in -`punktfunk-core`'s receive loop, that part moves to section 1. +3 is the busy one with the current build. What the session's runtime needs from tokio's I/O driver, +the `poll` and `recvmmsg` pair and the ACK rate all sit in `punktfunk-core`: if the counts say they +matter, those parts move to section 1. ### The smoothness buffer's Automatic on the Switch 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", diff --git a/toolchain/patches/mio/LEG.md b/toolchain/patches/mio/LEG.md index cd121f3..f8cdf7e 100644 --- a/toolchain/patches/mio/LEG.md +++ b/toolchain/patches/mio/LEG.md @@ -6,6 +6,9 @@ - `src/sys/unix/waker/udp.rs` (new): the selector's wake fd is a UDP socket connected to itself on loopback; libnx has no `pipe` or `socketpair`. Upstream gives Horizon the single-threaded waker, which cannot wake a thread blocked in `poll`, and no `Waker` at all, which tokio needs. + - `PF_NX_LEAN_WAKER` in the environment makes that waker skip a wake with one on its way and + ack with one read, for an A/B of the title's socket calls. A wake datagram lost across a + console sleep would leave it silent until an ack: unproven, so an A/B round does not sleep. - `Waker` and `Selector::wake` compiled for Horizon (`lib.rs`, `poll.rs`, `sys/unix/selector/poll.rs`); `sys/unix/mod.rs` picks `waker/udp.rs` on `aarch64` Horizon. - `PollFlagInt` is `c_short` on `aarch64` Horizon, as devkitA64's `pollfd` (the libc leg). diff --git a/toolchain/patches/mio/src/sys/unix/waker/udp.rs b/toolchain/patches/mio/src/sys/unix/waker/udp.rs index bb5e3f9..6c1cb51 100644 --- a/toolchain/patches/mio/src/sys/unix/waker/udp.rs +++ b/toolchain/patches/mio/src/sys/unix/waker/udp.rs @@ -1,14 +1,22 @@ use std::io; use std::net::UdpSocket; use std::os::fd::{AsRawFd, RawFd}; +use std::sync::atomic::{AtomicBool, Ordering}; /// Waker backed by a UDP socket connected to itself on loopback (punktfunk's Horizon leg). /// /// libnx has no `pipe(2)` or `socketpair(2)`, but `poll(2)` on a socket works, so the /// selector polls this socket for `POLLIN` and a wake is one datagram to it. +/// +/// `PF_NX_LEAN_WAKER` in the environment saves socket calls, each one an IPC on the console: a +/// wake with one already on its way sends nothing, and the ack reads one datagram rather than +/// reading until the socket is empty. #[derive(Debug)] pub(crate) struct Waker { socket: UdpSocket, + lean: bool, + /// Lean only: a wake was sent and no ack has come. + pending: AtomicBool, } impl Waker { @@ -16,11 +24,22 @@ impl Waker { let socket = UdpSocket::bind("127.0.0.1:0")?; socket.connect(socket.local_addr()?)?; socket.set_nonblocking(true)?; - Ok(Waker { socket }) + Ok(Waker { + socket, + lean: std::env::var_os("PF_NX_LEAN_WAKER").is_some(), + pending: AtomicBool::new(false), + }) } pub(crate) fn wake(&self) -> io::Result<()> { - match self.socket.send(&[1]) { + if self.lean && self.pending.swap(true, Ordering::AcqRel) { + return Ok(()); + } + let sent = self.socket.send(&[1]); + if sent.is_err() { + self.pending.store(false, Ordering::Release); + } + match sent { Ok(_) => Ok(()), Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => { // The receive buffer is full of wakes already: one more changes nothing. @@ -37,6 +56,13 @@ impl Waker { pub(crate) fn ack_and_reset(&self) { let mut buf = [0; 64]; + if self.lean { + // Cleared first: a wake from here on sends, and a datagram left behind only makes + // the next poll return at once. + self.pending.store(false, Ordering::Release); + let _ = self.socket.recv(&mut buf); + return; + } while matches!(self.socket.recv(&mut buf), Ok(n) if n > 0) {} }