From b01594d34fd320194a4e469d82251a49d2da03ea Mon Sep 17 00:00:00 2001 From: Valdi320 <61891540+Valdi320@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:52:54 +0100 Subject: [PATCH] d3d12: adapt large shader compile concurrency to available memory --- docs/ENVIRONMENT.md | 2 +- runtime/d3d12/Cargo.toml | 1 + runtime/d3d12/src/compile_gate.rs | 74 +++++++++++++++++++++---- runtime/d3d12/src/tests/compile_gate.rs | 64 +++++++++++++++++++-- 4 files changed, 124 insertions(+), 17 deletions(-) diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.md index 53d81bdf..6ad906f1 100644 --- a/docs/ENVIRONMENT.md +++ b/docs/ENVIRONMENT.md @@ -45,7 +45,7 @@ The launcher sets these for a Proton or Wine launch. A value you set yourself is | `TUXBOX_SHADER_PREP` | `chase` | Frosty preparation: `0`, `1`, `menu` or `chase` | | `TUXBOX_SHADER_PREP_UI` | on for ProjectScarlett | `1` shows a desktop progress window | | `TUXBOX_SCARLETT_SEED_PACK` | off | `1` prepares every shader in `shaders.rpf` | -| `TUXBOX_LARGE_COMPILES` | `4` | Large compute pipelines compiling at once; `0` removes the limit | +| `TUXBOX_LARGE_COMPILES` | Automatic (1–4) | Large compute pipelines compiling at once; the automatic policy uses available memory, reserving 2 GiB plus 2 GiB per compile, and always permits one compile. If the memory query fails, use four. An explicit number overrides the policy; `0` removes the limit. | | `TUXBOX_PIPELINE_DEADLINE` | `20` | Seconds before a large compile gets an empty stand-in; `0` waits | | `TUXBOX_NULL_PIPELINES` | on | `0` fails unsupported pipelines instead of giving empty stand-ins | | `TUXBOX_PROGRESS_OVERLAY` | `auto` | `always` or `0` for the progress panel | diff --git a/runtime/d3d12/Cargo.toml b/runtime/d3d12/Cargo.toml index dae7380f..e8139a6b 100644 --- a/runtime/d3d12/Cargo.toml +++ b/runtime/d3d12/Cargo.toml @@ -26,6 +26,7 @@ windows = { workspace = true, features = [ "Win32_System_Kernel", "Win32_System_Performance", "Win32_System_Memory", + "Win32_System_SystemInformation", "Win32_System_LibraryLoader", "Win32_System_Threading", "Win32_Graphics_Gdi", diff --git a/runtime/d3d12/src/compile_gate.rs b/runtime/d3d12/src/compile_gate.rs index d8c23c32..23d36b30 100644 --- a/runtime/d3d12/src/compile_gate.rs +++ b/runtime/d3d12/src/compile_gate.rs @@ -14,19 +14,62 @@ use std::sync::{Condvar, LazyLock, Mutex}; const LARGE_BYTES: usize = 512 << 10; const DEFAULT_SLOTS: usize = 4; -/// `TUXBOX_LARGE_COMPILES`: how many large compiles may run at once. `0` -/// removes the limit. +/// Leave room for the running title, and conservatively budget 2 GiB for +/// each large driver compile (measured allocations have been around 1 GiB). +const GIB: u64 = 1 << 30; +const RESERVED_BYTES: u64 = 2 * GIB; +const BYTES_PER_COMPILE: u64 = 2 * GIB; + +/// `TUXBOX_LARGE_COMPILES` overrides the memory-based policy. `0` is unlimited. static LARGE: LazyLock = LazyLock::new(|| { - Gate::new(parse_slots(std::env::var("TUXBOX_LARGE_COMPILES").ok().as_deref())) + let value = std::env::var("TUXBOX_LARGE_COMPILES").ok(); + Gate::with_limit(parse_slots(value.as_deref()) + .map_or(Limit::Adaptive(available_memory), Limit::Fixed)) }); -fn parse_slots(value: Option<&str>) -> usize { - value.and_then(|text| text.trim().parse().ok()).unwrap_or(DEFAULT_SLOTS) +fn parse_slots(value: Option<&str>) -> Option { + value.and_then(|text| text.trim().parse().ok()) +} + +#[cfg(windows)] +fn available_memory() -> Option { + use windows::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + let mut status = MEMORYSTATUSEX { + dwLength: std::mem::size_of::() as u32, + ..Default::default() + }; + // SAFETY: the initialized structure is writable for the duration of the call. + unsafe { GlobalMemoryStatusEx(&mut status) }.ok()?; + Some(status.ullAvailPhys.min(status.ullAvailPageFile)) +} + +#[cfg(not(windows))] +fn available_memory() -> Option { None } + +fn memory_slots(available: Option) -> usize { + available.map_or(DEFAULT_SLOTS, |bytes| { + // Always allow one compile to make progress, even under pressure. + (bytes.saturating_sub(RESERVED_BYTES) / BYTES_PER_COMPILE) + .clamp(1, DEFAULT_SLOTS as u64) as usize + }) +} + +enum Limit { + Fixed(usize), + Adaptive(fn() -> Option), +} + +impl Limit { + fn slots(&self) -> usize { + match self { + Self::Fixed(slots) => *slots, + Self::Adaptive(available) => memory_slots(available()), + } + } } pub(crate) struct Gate { - /// Zero means unlimited. - slots: usize, + limit: Limit, running: Mutex, freed: Condvar, } @@ -35,18 +78,27 @@ pub(crate) struct Gate { pub(crate) struct Slot<'a>(&'a Gate); impl Gate { + #[cfg(test)] fn new(slots: usize) -> Self { - Self { slots, running: Mutex::new(0), freed: Condvar::new() } + Self::with_limit(Limit::Fixed(slots)) + } + + fn with_limit(limit: Limit) -> Self { + Self { limit, running: Mutex::new(0), freed: Condvar::new() } } /// Block until a slot is free. `waiting` is called once, with the slot /// count, if the caller has to wait. fn acquire(&self, waiting: impl FnOnce(usize)) -> Slot<'_> { let mut running = self.running.lock().unwrap_or_else(|e| e.into_inner()); - if self.slots != 0 && *running >= self.slots { - waiting(self.slots); - while *running >= self.slots { + let mut slots = self.limit.slots(); + if slots != 0 && *running >= slots { + waiting(slots); + while slots != 0 && *running >= slots { running = self.freed.wait(running).unwrap_or_else(|e| e.into_inner()); + // Re-evaluate only after a running compile completes. The + // minimum of one ensures that memory pressure cannot deadlock. + slots = self.limit.slots(); } } *running += 1; diff --git a/runtime/d3d12/src/tests/compile_gate.rs b/runtime/d3d12/src/tests/compile_gate.rs index 438038b2..dd853444 100644 --- a/runtime/d3d12/src/tests/compile_gate.rs +++ b/runtime/d3d12/src/tests/compile_gate.rs @@ -71,9 +71,63 @@ fn small_shaders_never_take_a_slot() { #[test] fn slot_count_comes_from_the_environment_value() { - assert_eq!(parse_slots(None), DEFAULT_SLOTS); - assert_eq!(parse_slots(Some("2")), 2); - assert_eq!(parse_slots(Some(" 0 ")), 0); - assert_eq!(parse_slots(Some("many")), DEFAULT_SLOTS); - assert_eq!(parse_slots(Some("-1")), DEFAULT_SLOTS); + assert_eq!(parse_slots(None), None); + assert_eq!(parse_slots(Some("2")), Some(2)); + assert_eq!(parse_slots(Some(" 0 ")), Some(0)); + assert_eq!(parse_slots(Some("many")), None); + assert_eq!(parse_slots(Some("-1")), None); +} + + +#[test] +fn memory_budget_leaves_room_and_never_disables_progress() { + for (available, slots) in [(0, 1), (2, 1), (4, 1), (6, 2), (8, 3), (10, 4), (32, 4)] { + assert_eq!(memory_slots(Some(available * GIB)), slots); + } + assert_eq!(memory_slots(None), DEFAULT_SLOTS); +} + +#[test] +fn memory_pressure_serializes_large_compiles() { + let low = Gate::with_limit(Limit::Adaptive(|| Some(3 * GIB))); + let medium = Gate::with_limit(Limit::Adaptive(|| Some(6 * GIB))); + let high = Gate::with_limit(Limit::Adaptive(|| Some(16 * GIB))); + assert_eq!(peak(&low, 6), 1); + assert_eq!(peak(&medium, 6), 2); + assert_eq!(peak(&high, 6), 4); +} + +#[test] +fn adaptive_gate_rechecks_memory_after_a_slot_is_freed() { + use std::sync::atomic::AtomicU64; + static AVAILABLE: AtomicU64 = AtomicU64::new(16 * GIB); + let gate = Gate::with_limit(Limit::Adaptive(|| Some(AVAILABLE.load(SeqCst)))); + let first = gate.acquire(|_| panic!("first must proceed")); + let second = gate.acquire(|_| panic!("second must proceed")); + AVAILABLE.store(3 * GIB, SeqCst); + let waited = AtomicUsize::new(0); + let (entered, received) = std::sync::mpsc::channel(); + let (early, eventually) = std::thread::scope(|scope| { + scope.spawn(|| { + let _slot = gate.acquire(|slots| { waited.store(slots, SeqCst); }); + entered.send(()).unwrap(); + }); + while waited.load(SeqCst) == 0 { std::thread::yield_now(); } + drop(first); + let early = received.recv_timeout(Duration::from_millis(100)).is_ok(); + drop(second); + (early, early || received.recv_timeout(Duration::from_secs(2)).is_ok()) + }); + assert_eq!(waited.load(SeqCst), 1); + assert!(!early && eventually); +} + + +#[cfg(windows)] +#[test] +fn host_memory_query_is_available() { + let bytes = available_memory().expect("GlobalMemoryStatusEx failed"); + let slots = memory_slots(Some(bytes)); + println!("host memory available={} MiB, adaptive slots={slots}", bytes >> 20); + assert!((1..=DEFAULT_SLOTS).contains(&slots)); }