From a59fe074029887b6d6768030ed2e6212bbcfad49 Mon Sep 17 00:00:00 2001 From: OreoFR <29048345+OreoFR@users.noreply.github.com> Date: Tue, 1 Dec 2026 04:56:34 +0100 Subject: [PATCH] gpu: the split list ahead's textures half runs on one thread kept for the run (LEONIDA_AHEAD_KEPT_THREAD, on) With LEONIDA_AHEAD_SPLIT, record_ahead_split made a new OS thread with an 8 MiB stack every frame for the textures' half of the list ahead, chose the fast cores for it and logged a line, all on the path of the line's thread, which waits for that half (14,271 such lines in about 2.5 minutes of play on an RTX 4070 Laptop / Core Ultra 7 155H). One thread is now kept for it (queue::beside::Kept, made at the first split, pinned once); each frame's half is handed to it and waited for, with the same panic and fallback behaviour. LEONIDA_AHEAD_KEPT_THREAD=0 brings back the per-frame thread, and LEONIDA_AB can switch it. Measured with LEONIDA_AB every 10 s on that machine (18 steady phases a side): the line's thread stood 2.5 ms a frame for the list ahead with it, 5.2 ms without; the frame median moved 55.6 -> 54.4 ms, within its spread. switches.md regenerated (it also picks up two rows main had stale). Co-Authored-By: Claude Opus 5.5 --- d3d12/crates/leonida-gpu/src/queue.rs | 142 +++++++++++++++++++++++--- d3d12/docs/switches.md | 10 +- 2 files changed, 136 insertions(+), 16 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/queue.rs b/d3d12/crates/leonida-gpu/src/queue.rs index 6c095d2544..a180097fe3 100644 --- a/d3d12/crates/leonida-gpu/src/queue.rs +++ b/d3d12/crates/leonida-gpu/src/queue.rs @@ -566,21 +566,43 @@ fn record_ahead_split() -> std::thread::Result> { // (as `Ahead` hands it on). unsafe impl Send for Sent {} let began = std::time::Instant::now(); - let (buffers, textures) = std::thread::scope(|scope| { - let beside = std::thread::Builder::new().name("leonida-ahead-textures".into()).stack_size(8 << 20).spawn_scoped(scope, || { - crate::cores::keep_on_fast_cores("leonida-ahead-textures"); - // As the thread it helps: the line waits for it, so it does not wait for the line. - behind::no_drain_here(); - catch_unwind(AssertUnwindSafe(|| Sent(crate::list::ahead_of_frame_part(AheadPart::Textures)))) - }); + let (buffers, textures) = if ahead_kept_thread() { + // Leonida: the textures' half on the thread kept for it ([`AHEAD_BESIDE`]). + let pending = AHEAD_BESIDE + .get_or_init(|| { + beside::Kept::new("leonida-ahead-textures", || { + crate::cores::keep_on_fast_cores("leonida-ahead-textures"); + // As the thread it helps: the line waits for it, so it does not wait for the line. + behind::no_drain_here(); + }) + .ok() + }) + .as_ref() + .and_then(|kept| kept.start(|| Sent(crate::list::ahead_of_frame_part(AheadPart::Textures)))); let buffers = catch_unwind(AssertUnwindSafe(|| crate::list::ahead_of_frame_part(AheadPart::Buffers))); - let textures = match beside { - Ok(thread) => thread.join().and_then(|r| r).map(|sent| sent.0), - // No thread: here, after the buffers. - Err(_) => catch_unwind(AssertUnwindSafe(|| crate::list::ahead_of_frame_part(AheadPart::Textures))), + let textures = match pending.and_then(|done| done.recv().ok()) { + Some(result) => result.map(|sent| sent.0), + // No kept thread: here, after the buffers. + None => catch_unwind(AssertUnwindSafe(|| crate::list::ahead_of_frame_part(AheadPart::Textures))), }; (buffers, textures) - }); + } else { + std::thread::scope(|scope| { + let beside = std::thread::Builder::new().name("leonida-ahead-textures".into()).stack_size(8 << 20).spawn_scoped(scope, || { + crate::cores::keep_on_fast_cores("leonida-ahead-textures"); + // As the thread it helps: the line waits for it, so it does not wait for the line. + behind::no_drain_here(); + catch_unwind(AssertUnwindSafe(|| Sent(crate::list::ahead_of_frame_part(AheadPart::Textures)))) + }); + let buffers = catch_unwind(AssertUnwindSafe(|| crate::list::ahead_of_frame_part(AheadPart::Buffers))); + let textures = match beside { + Ok(thread) => thread.join().and_then(|r| r).map(|sent| sent.0), + // No thread: here, after the buffers. + Err(_) => catch_unwind(AssertUnwindSafe(|| crate::list::ahead_of_frame_part(AheadPart::Textures))), + }; + (buffers, textures) + }) + }; let lists: Vec<_> = buffers?.into_iter().chain(textures?).collect(); if !lists.is_empty() { crate::draw::AHEAD_STATS[0].fetch_add(1, Ordering::Relaxed); @@ -589,6 +611,102 @@ fn record_ahead_split() -> std::thread::Result> { Ok(lists) } +/// Leonida: the thread kept for the textures' half of a split list ahead ([`record_ahead_split`]), +/// made at the first split; `None` if it could not be made (each split then records both halves +/// here, one after the other). +#[cfg(windows)] +static AHEAD_BESIDE: std::sync::OnceLock> = std::sync::OnceLock::new(); + +/// Leonida: `LEONIDA_AHEAD_KEPT_THREAD` (on; `0`: off, `LEONIDA_AB` can switch it): the textures' +/// half of a split list ahead ([`crate::draw::ahead_split`]) is recorded by one thread kept for the +/// run ([`AHEAD_BESIDE`]), instead of by a thread made for it each frame. Each of those was a new +/// OS thread with an 8 MiB stack, a choice of the fast cores for it and a line in the log, on the +/// path of the line's thread, which waits for that half: 14,271 such lines in some 2.5 minutes of +/// play on an RTX 4070 Laptop with a Core Ultra 7 155H (2026-12-01). There, with `LEONIDA_AB` +/// turning it every 10 s (18 steady phases a side), the line's thread stood 2.5 ms a frame for the +/// list ahead with it, 5.2 ms without. +#[cfg(windows)] +fn ahead_kept_thread() -> bool { + crate::toggled!("LEONIDA_AHEAD_KEPT_THREAD") +} + +/// Leonida: a thread kept for work handed to it one piece at a time, each waited for by the one +/// that handed it ([`Kept::start`]). +#[cfg(windows)] +mod beside { + use std::panic::{AssertUnwindSafe, catch_unwind}; + use std::sync::{Mutex, mpsc}; + + type Job = Box; + + pub(super) struct Kept { + jobs: Mutex>, + } + + impl Kept { + /// Makes the thread, named `name`, with an 8 MiB stack (as the threads made for each piece + /// had); `start` runs on it once, before any piece. + pub(super) fn new(name: &str, start: fn()) -> std::io::Result { + let (jobs, taken) = mpsc::channel::(); + std::thread::Builder::new().name(name.into()).stack_size(8 << 20).spawn(move || { + start(); + for job in taken { + job(); + } + })?; + Ok(Kept { jobs: Mutex::new(jobs) }) + } + + /// Hands `piece` to the thread and returns at once; what it returns (or how it panicked) + /// comes back on the receiver. `None` if the thread is gone, and then `piece` has not run. + pub(super) fn start( + &self, + piece: impl FnOnce() -> R + Send + 'static, + ) -> Option>> { + let (done, wait) = mpsc::sync_channel(1); + let job: Job = Box::new(move || { + // A panic stays in the piece: the thread goes on for the next one. + let _ = done.send(catch_unwind(AssertUnwindSafe(piece))); + }); + self.jobs.lock().unwrap_or_else(|e| e.into_inner()).send(job).ok()?; + Some(wait) + } + } + + #[cfg(test)] + mod tests { + use super::Kept; + use std::sync::atomic::{AtomicUsize, Ordering::Relaxed}; + + static STARTED: AtomicUsize = AtomicUsize::new(0); + + /// Every piece runs on the one thread kept, made once (its start runs once), and a piece + /// that panics leaves the thread there for the next. + #[test] + fn pieces_run_on_one_thread_made_once_and_a_panic_stays_in_its_piece() { + let kept = Kept::new("test-beside", || { + STARTED.fetch_add(1, Relaxed); + }) + .expect("the thread"); + let ids: Vec<_> = (0..200) + .map(|i| { + let wait = kept.start(move || (std::thread::current().id(), i)).expect("handed"); + let (id, got) = wait.recv().expect("an answer").expect("no panic"); + assert_eq!(got, i); + id + }) + .collect(); + assert_ne!(ids[0], std::thread::current().id(), "not on the caller's thread"); + assert!(ids.iter().all(|id| *id == ids[0]), "one thread for all the pieces"); + assert_eq!(STARTED.load(Relaxed), 1, "made once"); + let panicked = kept.start(|| -> u32 { panic!("a piece that panics") }).expect("handed").recv().expect("an answer"); + assert!(panicked.is_err(), "the panic comes back to the one that waits"); + let after = kept.start(|| std::thread::current().id()).expect("handed").recv().expect("an answer").expect("no panic"); + assert_eq!(after, ids[0], "the same thread after a panicking piece"); + } + } +} + /// The line's thread is at a present, with everything of that frame sent: the /// list ahead of the next one is recorded from now on, by a thread of its own, /// beside the present and whatever comes before the next frame's first diff --git a/d3d12/docs/switches.md b/d3d12/docs/switches.md index 1fe9306d6d..7ad6503faa 100644 --- a/d3d12/docs/switches.md +++ b/d3d12/docs/switches.md @@ -6,7 +6,7 @@ It says which names exist and what the code's own comments say of them. It is ** settings and says nothing of what a switch gains: for that read [findings.md](findings.md) first, and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. -652 names; 612 have a sentence of a comment below, the others no comment or only a bare list. +654 names; 614 have a sentence of a comment below, the others no comment or only a bare list. - **Kind**: how the code reads it, where that can be told. "see the code" is a number, a path, a list or a switch read some other way; its default is not given here. @@ -21,7 +21,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | Name | Kind | A/B | L | F | Named in | In the code's words | |---|---|---|---|---|---|---| -| `LEONIDA_AB` | see the code | | | yes | `leonida/leonida.rs` +37 | `LEONIDA_AB=<seconds>,<switch>[,<switch>..]`: every so many seconds, at a present, the next phase begins; switch number n is on in the phases whose number has bit n, so that all combinations come one after another, again... | +| `LEONIDA_AB` | see the code | | | yes | `leonida/leonida.rs` +38 | `LEONIDA_AB=<seconds>,<switch>[,<switch>..]`: every so many seconds, at a present, the next phase begins; switch number n is on in the phases whose number has bit n, so that all combinations come one after another, again... | | `LEONIDA_AUDIO_CAPTURE` | see the code | | | | `leonida/main.rs` +1 | `LEONIDA_AUDIO_CAPTURE=<file.wav>` records what the title plays, 48 kHz stereo 16-bit, through process loopback: our own process tree only, never the rest of the host's mix. | | `LEONIDA_CAPTURE` | see the code | | yes | | `leonida/leonida.rs` +4 | Presented frames written to PNG files, to see what reaches the screen: with `LEONIDA_CAPTURE=<folder>`, every frame whose number is a power of two (the frames the log reports) is saved as `frame-<n>.png`, at half size. | | `LEONIDA_CARD_AWAKE` | see the code | yes | yes | yes | `leonida/replay.rs` +4 | Keeps the card's clocks up between submissions (`LEONIDA_CARD_AWAKE=1`; off by default). | @@ -112,6 +112,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_ACTIVATE_RAYS` | see the code | | yes | | `leonida-gpu/pipeline/make.rs` +1 | | | `LEONIDA_ADAPTER` | see the code | | yes | | `leonida-gpu/host.rs` +3 | LOCAL: the card `LEONIDA_ADAPTER` names, for a PC with more than one. | | `LEONIDA_AHEAD_INDEX` | on, `0` turns it off | yes | | | `leonida-gpu/watch.rs` | Whether the page ranges asked ahead ([`Journal::ahead`]) are kept in order, so that the one that holds a range is found in a few steps (`LEONIDA_AHEAD_INDEX=0`: a list looked through from its start, as before). | +| `LEONIDA_AHEAD_KEPT_THREAD` | on, `0` turns it off | yes | | | `leonida-gpu/queue.rs` | `LEONIDA_AHEAD_KEPT_THREAD` (on; `0`: off, `LEONIDA_AB` can switch it): the textures' half of a split list ahead ([`crate::draw::ahead_split`]) is recorded by one thread kept for the run ([`AHEAD_BESIDE`]), instead of by... | | `LEONIDA_AHEAD_SPLIT` | off unless set and not `0` | yes | yes | yes | `leonida-gpu/draw.rs` +1 | `LEONIDA_AHEAD_SPLIT=1`: the list ahead of a frame is recorded as two lists by two threads at once, the buffer views' pass and the textures' pass (sent in that order), instead of one after the other into one list. | | `LEONIDA_ALIAS_CAST` | on, `0` turns it off | yes | | yes | `leonida-gpu/descriptor/host.rs` +2 | ..., with no copy on the card and no host texture of its own (`LEONIDA_ALIAS_CAST=0`: copied as before; `LEONIDA_AB` can name it).... | | `LEONIDA_ALIAS_COPY` | see the code | | | | `leonida-gpu/resource.rs` | `LEONIDA_ALIAS_COPY=0`: none is found, as before; `=1`: only textures of one level and one layer, as at first. | @@ -511,7 +512,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_SWEEP_WRAP` | on, `0` turns it off | yes | | | `leonida-gpu/resource.rs` | ...s released) starts again at the first address when `wrap` (`LEONIDA_SWEEP_WRAP=0`: it stayed past the end, as before, and the sweep looked at nothing).... | | `LEONIDA_TABLED_TEXTURES` | see the code | | | | `leonida-gpu/descriptor/host.rs` | `LEONIDA_TABLED_TEXTURES=1` keeps them in it as before. | | `LEONIDA_TABLES_EARLY` | on, `0` turns it off | yes | | | `leonida-gpu/host.rs` | `LEONIDA_TABLES_EARLY=0`: at the end of the landing, as before. | -| `LEONIDA_TAKE_BLOCKS` | on, `0` turns it off | yes | | yes | `leonida-gpu/shadow.rs` | ...ote, and only the 4 KiB that changed go up (on by default; `LEONIDA_TAKE_BLOCKS=0`: the page goes up whole; `LEONIDA_AB` can name it).... | +| `LEONIDA_TAKE_BLOCKS` | on, `0` turns it off | yes | | yes | `leonida-gpu/host.rs` +1 | ...ote, and only the 4 KiB that changed go up (on by default; `LEONIDA_TAKE_BLOCKS=0`: the page goes up whole; `LEONIDA_AB` can name it).... | | `LEONIDA_TAKE_PARTS` | on, `0` turns it off | yes | | | `leonida-gpu/watch.rs` | Of a page taken before, the parts written since, where they are known (`LEONIDA_TAKE_PARTS=0`: the page). | | `LEONIDA_TARGET_VARIANTS` | see the code | | | | `leonida-gpu/pipeline/make.rs` | Whether a draw into views of other formats than its pipeline declares gets a host pipeline for those formats ([`for_formats`]); on unless `LEONIDA_TARGET_VARIANTS=0`. | | `LEONIDA_TEARING` | off unless set and not `0` | | | | `leonida-gpu/host.rs` | `LEONIDA_TEARING=1`, where the system has it; off by default (unset or `0`: presents wait for the refresh, as before). | @@ -586,8 +587,9 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_WAVE_OWN_BITS` | see the code | | | | `leonida-gpu/shader_cache.rs` +2 | `LEONIDA_WAVE_OWN_BITS=0`: a wave OR where not every lane runs is refused as before ([`super::own_bits`]). | | `LEONIDA_WAVE_WIDE` | see the code | | | yes | `leonida-gpu/shader_cache.rs` +1 | So are the switches that pick the form of a wave64 program: without them here a run with `LEONIDA_WAVE_WIDE=0` was served the translations an earlier run of the same executable had cached with the switch unset. | | `LEONIDA_WAVE_WIDE_FOR` | see the code | | | yes | `leonida-gpu/shader_cache.rs` +1 | The programs a `LEONIDA_PAIRED_FOR` or `LEONIDA_WAVE_WIDE_FOR` list names: hashes as the log and the frame listings name shaders (the first 16 hex digits of the container's BLAKE3), or their beginnings from 8 digits on,... | -| `LEONIDA_WC_NO_BACK` | on, `0` turns it off | yes | yes | yes | `leonida-gpu/shadow.rs` +3 | Whether its title memory is write-combined ([`Shadow::write_combined`], `LEONIDA_WC_NO_BACK`): 0 not known yet, 1 no, 2 yes. | +| `LEONIDA_WC_NO_BACK` | on, `0` turns it off | yes | yes | yes | `leonida-gpu/shadow.rs` +3 | Whether its title memory is write-combined ([`Shadow::wc_kind`], `LEONIDA_WC_NO_BACK` / `LEONIDA_WC_SUBRANGE_NO_BACK`): 0 not known yet, 1 none, 2 whole copy, 3 partial (mixed copy with qualifying sub-ranges). | | `LEONIDA_WC_NO_BACK_MIN_KB` | see the code | | | | `leonida-gpu/shadow.rs` | The smallest copy whose shader writes [`wc_no_back`] leaves on the card, in bytes (`LEONIDA_WC_NO_BACK_MIN_KB`, 1024 unless set; 0: all). | +| `LEONIDA_WC_SUBRANGE_NO_BACK` | off unless set and not `0` | yes | | | `leonida-gpu/shadow.rs` | Whether its title memory is write-combined ([`Shadow::wc_kind`], `LEONIDA_WC_NO_BACK` / `LEONIDA_WC_SUBRANGE_NO_BACK`): 0 not known yet, 1 none, 2 whole copy, 3 partial (mixed copy with qualifying sub-ranges). | | `LEONIDA_WIDE_BACK` | see the code | | yes | | `leonida-gpu/host/menu.rs` +3 | Whether the snapshots of a submission's shader-written ranges, and the compare that finds what the shaders wrote, run on several threads across ranges (`LEONIDA_WIDE_BACK=1`; off by default). | | `LEONIDA_WIDE_FILLS` | see the code | | | | `leonida-gpu/host.rs` | Whether the fills of a submission's upload memory are done together on several threads (`LEONIDA_WIDE_FILLS=0`: one after the other, where the lists name them). | | `LEONIDA_WIDE_HALF` | off unless set and not `0` | yes | | yes | `leonida-gpu/shadow.rs` | Whether half of the logical processors help with work spread over threads, not a quarter of them (`LEONIDA_WIDE_HALF=1`; off by default; `LEONIDA_AB` can name it: the threads are all kept then, and half of them are left... |