diff --git a/HANDOFF.md b/HANDOFF.md index a8d8a75c1..c36ce778b 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -1410,7 +1410,12 @@ of the title (it writes to address 0 after a failed D3D12 call: `call 0x14068c76 call; it stays 2 s after the last one). XDefiant from an empty cache: ~1750 shaders in ~2 min 15 s. Before, `dxc::wait_for_memory` held each compile up to a minute while less than 6 GB of commit was left, and with XDefiant's own ~10 GB committed only ~4 GB were: its last ~160 shaders came a few a minute (it looked hung at - ~1600). Now a compile goes at once with 6 GB left, else alone (one at a time). After a cold-cache run + ~1600). Now a compile goes at once with 6 GB left, else alone (one at a time). Since 2026-11-23: at once while + commit covers 6 GB + 300 MB per running compile (their current use is already out of the available commit, so only + their growth is reserved; #113 reserved 1 GB each on top: with 8.1 GB free, Minecraft's 716 programs, 15 threads, + 12.7–15.2 s → 6.4–6.7 s, 5.3–5.6 s with no gate); the count only rises from the value a decision saw (no burst on + one reading); after a minute's wait one compile per minute goes in regardless (it was every waiting one); waiters + wake when a compile ends (`may_start`, `gate_tests`). Driver PSO compiles are still not gated. After a cold-cache run XDefiant's logo / UI text was missing at times. Cold-cache runs (empty `XCL_DXIL_CACHE`, 1 756 shaders) show the logo at ~70 s and the text ~15 s later, by themselves; draws wait for pipelines still being built (`resolve_wait` in `bind::graphics_bound`, 0 draws with stand-ins). The text missing for good (also warm) on @@ -1621,7 +1626,7 @@ of the title (it writes to address 0 after a failed D3D12 call: `call 0x14068c76 - **Ending a run without a stuck process**: a host killed from outside with GPU work in flight stayed in the driver holding 12–16 GB. `XCL_RUN_SECONDS=n` ends the title itself: every fence the title created is signalled to the maximum (GPU waits on future values complete), the queues drain, then TerminateProcess (`real::end_title`). Shader - compiles: at most 6 at once and they wait while the system has < 6 GB of commit left (`dxc::wait_for_memory`). + compiles: `dxc::compile_threads` at once, gated by commit left (`dxc::wait_for_memory`). - **Window**: titles create their window with CreateWindowExA / RegisterClassExA but DefWindowProcW (its title showed as CJK characters); `hle::user` makes them Unicode calls. The window stays white (console titles never paint it). - Diagnostics: `XCL_TRACE_FRAME=1` (what console code does with each presented resource; render-target binds, UAV diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 894a96758..c268e764f 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -130,40 +130,99 @@ pub fn compile_threads() -> usize { }) } -/// Compiles running on the DXC workers (`wait_for_memory` lets them in). -static WORKING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +/// What `wait_for_memory` lets compiles in through: the compiles running, its lock (holding +/// when a compile last went in by waiting `ESCAPE_AFTER`) and the wake-up when one ends. +struct Gate { + running: std::sync::atomic::AtomicUsize, + last_escape: Mutex>, + freed: std::sync::Condvar, +} + +impl Gate { + const fn new() -> Gate { + Gate { running: std::sync::atomic::AtomicUsize::new(0), last_escape: Mutex::new(None), freed: std::sync::Condvar::new() } + } +} + +/// The DXC workers' gate. +static GATE: Gate = Gate::new(); /// A compile let in by `wait_for_memory`, until it is dropped. -pub struct MemorySlot; +pub struct MemorySlot(&'static Gate); impl Drop for MemorySlot { fn drop(&mut self) { - WORKING.fetch_sub(1, std::sync::atomic::Ordering::AcqRel); + self.0.running.fetch_sub(1, std::sync::atomic::Ordering::AcqRel); + // under the gate's lock: a waiter between its decision and its wait does not miss it + let _lock = self.0.last_escape.lock().unwrap_or_else(|e| e.into_inner()); + self.0.freed.notify_all(); } } -/// Before a compile: with 6 GB of commit left or more, plus 1 GB for every compile already -/// running (each can still grow to ~0.7 GB), at once; with less, one compile at a -/// time – it goes when no other is running (and after a minute in any case). Each compile used -/// to wait the minute while commit was short: with XDefiant's own 10 GB committed, 4 GB were -/// left, and its last cold-cache shaders came a few a minute. +/// The system's available commit (None when Windows does not say). +fn available_commit() -> Option { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = std::mem::size_of::() as u32; + (unsafe { GlobalMemoryStatusEx(&mut m) } != 0).then_some(m.ullAvailPageFile) +} + +/// Commit left for the rest of the system (the title above all) while compiles run. +const COMMIT_FLOOR: u64 = 6 << 30; + +/// Commit a running compile may still add: what it already uses is in the system's available +/// commit, so this is only its growth to come – a typical retail compile peaks at 0.1–0.3 GB +/// (#113). It was 1 GB on top of that count: with 8.5 GB of commit free (a desktop with a +/// browser and chat open) about three compiles ran and the other workers polled – Minecraft's +/// 716 programs took 12.5 s on 16 threads instead of 4.9 s. +const COMMIT_PER_COMPILE: u64 = 300 << 20; + +/// A compile that has waited this long goes in even when commit is short – one per interval, +/// so a hung compile cannot stop the others for good but the waiting ones do not all start at +/// once (they did: after a minute every waiting worker went in). +const ESCAPE_AFTER: std::time::Duration = std::time::Duration::from_secs(60); + +/// Whether a compile may start: `avail` the system's available commit (None: unknown), +/// `running` the compiles running now, `waited` how long this one has waited, `escape_free` +/// no other compile went in by waiting `ESCAPE_AFTER` within the last interval. +fn may_start(avail: Option, running: usize, waited: std::time::Duration, escape_free: bool) -> bool { + let Some(avail) = avail else { return true }; + // enough commit for the floor and for what the running ones may still grow; with less, one + // compile at a time (it goes when no other is running) + avail >= COMMIT_FLOOR + COMMIT_PER_COMPILE * running as u64 || running == 0 || (waited >= ESCAPE_AFTER && escape_free) +} + +/// Before a compile: in at once while commit covers `COMMIT_FLOOR` plus `COMMIT_PER_COMPILE` +/// for each compile running; with less, one compile at a time, and a compile that has waited +/// `ESCAPE_AFTER` goes in regardless, one per interval. Each compile used to wait the minute +/// while commit was short: with XDefiant's own 10 GB committed, 4 GB were left, and its last +/// cold-cache shaders came a few a minute. pub fn wait_for_memory() -> MemorySlot { + admit(&GATE, available_commit) +} + +/// `wait_for_memory` through `gate`, with the available commit from `commit` (read again for +/// every decision; a test gives it a fixed one). +fn admit(gate: &'static Gate, commit: impl Fn() -> Option) -> MemorySlot { use std::sync::atomic::Ordering; - use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; let start = std::time::Instant::now(); + let mut last_escape = gate.last_escape.lock().unwrap_or_else(|e| e.into_inner()); loop { - let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; - m.dwLength = std::mem::size_of::() as u32; - let need = (6u64 << 30) + ((WORKING.load(Ordering::Acquire) as u64) << 30); - let plenty = unsafe { GlobalMemoryStatusEx(&mut m) } == 0 || m.ullAvailPageFile >= need; - if plenty || start.elapsed().as_secs() >= 60 { - WORKING.fetch_add(1, Ordering::AcqRel); - return MemorySlot; - } - if WORKING.compare_exchange(0, 1, Ordering::AcqRel, Ordering::Acquire).is_ok() { - return MemorySlot; + let avail = commit(); + let waited = start.elapsed(); + let escape_free = last_escape.is_none_or(|t| t.elapsed() >= ESCAPE_AFTER); + let running = gate.running.load(Ordering::Acquire); + // the count goes up only from the value the decision saw: workers deciding at the same + // moment cannot all go in on one reading of the commit + if may_start(avail, running, waited, escape_free) && gate.running.compare_exchange(running, running + 1, Ordering::AcqRel, Ordering::Acquire).is_ok() { + let plenty = avail.is_none_or(|a| a >= COMMIT_FLOOR + COMMIT_PER_COMPILE * running as u64); + if !plenty && running != 0 { + *last_escape = Some(std::time::Instant::now()); + } + return MemorySlot(gate); } - std::thread::sleep(std::time::Duration::from_millis(50)); + // woken when a compile ends; the commit can also change without one, so look again soon + last_escape = gate.freed.wait_timeout(last_escape, std::time::Duration::from_millis(50)).unwrap_or_else(|e| e.into_inner()).0; } } @@ -607,6 +666,88 @@ pub fn compile_cached(src: &str, entry: &str, profile: &str) -> Result<(Vec, compile_cached_in(&cache_dir(), src, entry, profile) } +#[cfg(test)] +mod gate_tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::time::Duration; + + const GB: u64 = 1 << 30; + + #[test] + fn compiles_start_while_commit_covers_the_floor_and_the_running_ones_growth() { + let now = Duration::ZERO; + // 8.5 GB free (the desktop that #113's 1 GB per compile held to three): eight running + // still leave room for a ninth + let free = 17 * GB / 2; + assert!(may_start(Some(free), 8, now, true)); + assert!(!may_start(Some(free), 9, now, true)); + assert!(may_start(Some(64 * GB), 63, now, true)); + // no reading: in + assert!(may_start(None, 100, now, false)); + } + + #[test] + fn short_commit_lets_one_compile_at_a_time_and_one_escape_per_interval() { + let short = 4 * GB; + assert!(may_start(Some(short), 0, Duration::ZERO, true), "alone, a compile always goes"); + assert!(!may_start(Some(short), 1, Duration::from_secs(10), true)); + assert!(may_start(Some(short), 1, ESCAPE_AFTER, true), "a minute's wait goes in"); + assert!(!may_start(Some(short), 1, ESCAPE_AFTER * 5, false), "but not while another just escaped"); + } + + /// Workers that decide at the same moment do not all go in: the count only rises from + /// the value each decision saw. A gate of its own (other tests' compiles share the real one) + /// and a fixed commit, read at every decision as the real one is: room for exactly three. + #[test] + fn concurrent_admissions_reach_and_never_exceed_what_the_commit_allows() { + static TEST_GATE: Gate = Gate::new(); + let cap = 3; + let commit = || Some(COMMIT_FLOOR + COMMIT_PER_COMPILE * (cap as u64 - 1)); + let (now, peak, filled) = (AtomicUsize::new(0), AtomicUsize::new(0), std::sync::atomic::AtomicBool::new(false)); + std::thread::scope(|s| { + for _ in 0..32 { + s.spawn(|| { + for _ in 0..10 { + let _slot = admit(&TEST_GATE, commit); + let n = now.fetch_add(1, Ordering::SeqCst) + 1; + peak.fetch_max(n, Ordering::SeqCst); + // the first ones in stay until the cap is full: it is reached for sure + let t0 = std::time::Instant::now(); + while !filled.load(Ordering::SeqCst) && now.load(Ordering::SeqCst) < cap && t0.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(1)); + } + filled.store(true, Ordering::SeqCst); + std::thread::sleep(Duration::from_millis(1)); + now.fetch_sub(1, Ordering::SeqCst); + } + }); + } + }); + assert_eq!(peak.into_inner(), cap, "running at once with room for {cap}"); + assert_eq!(TEST_GATE.running.load(Ordering::SeqCst), 0, "every slot given back"); + } + + /// The real gate with the machine's commit: 32 workers through it all finish (no lost + /// wake-up, no slot kept), whatever the commit is. + #[test] + fn the_real_gate_lets_every_worker_through() { + let done = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..32 { + s.spawn(|| { + for _ in 0..5 { + let _slot = wait_for_memory(); + std::thread::sleep(Duration::from_millis(1)); + } + done.fetch_add(1, Ordering::SeqCst); + }); + } + }); + assert_eq!(done.into_inner(), 32); + } +} + #[cfg(test)] mod cache_tests { use super::*; diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 01cff4362..07368aa05 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -6652,3 +6652,152 @@ fn fspx_containers_translate_and_compile() { println!("FSPX: {ok} / {n} translated and compiled"); assert_eq!(ok, n); } + +/// DXC cost of a folder of console shader containers (`XCL_BENCH_DIR`): every program +/// translated (`XCL_BENCH_SPLIT=1`: the split wave64 form, `XCL_BENCH_WINDOWS=n`: n memory windows), then +/// compiled on `XCL_BENCH_THREADS` threads (default: the DXC pool's) with `XCL_DXC_ARGS`. +/// Prints translate time, HLSL bytes and digest, DXC wall time, sum of per-shader times and +/// DXIL bytes. `XCL_BENCH_NO_DXC=1`: translation and digest only. +#[test] +#[ignore] +fn dxc_bench_folder() { + let Ok(dir) = std::env::var("XCL_BENCH_DIR") else { return }; + let split = std::env::var("XCL_BENCH_SPLIT").is_ok_and(|v| v == "1"); + // `XCL_BENCH_WINDOWS=4`: the memory windows of a running title (`Uma::for_runtime`) + let windows = std::env::var("XCL_BENCH_WINDOWS").ok().and_then(|v| v.parse().ok()).unwrap_or(1u32); + let args = std::env::var("XCL_DXC_ARGS").unwrap_or_default(); + let extra: Vec<&str> = args.split_whitespace().collect(); + let mut files: Vec<_> = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.path()).collect(); + files.sort(); + // `XCL_BENCH_SLICE=k/n`: every n-th file from the k-th (processes side by side) + if let Some((k, n)) = std::env::var("XCL_BENCH_SLICE").ok().and_then(|v| v.split_once('/').and_then(|(k, n)| Some((k.parse::().ok()?, n.parse::().ok()?)))) { + files = files.into_iter().skip(k).step_by(n.max(1)).collect(); + } + if let Ok(out) = std::env::var("XCL_BENCH_HLSL_OUT") { + let _ = std::fs::create_dir_all(&out); + } + let t0 = std::time::Instant::now(); + let mut jobs: Vec<(String, String, &'static str)> = Vec::new(); + // `XCL_BENCH_HLSL=1`: the folder holds saved HLSL (`..hlsl`) instead + let hlsl_dir = std::env::var("XCL_BENCH_HLSL").is_ok_and(|v| v == "1"); + for path in files.iter().filter(|_| hlsl_dir) { + let name = path.file_name().unwrap().to_string_lossy().into_owned(); + let profile = ["vs_6_6", "ps_6_6", "cs_6_6"].into_iter().find(|p| name.contains(p)).unwrap_or("cs_6_6"); + let stem = name.strip_suffix(".hlsl").and_then(|n| n.strip_suffix(profile)).and_then(|n| n.strip_suffix('.')).unwrap_or(&name).to_string(); + jobs.push((stem, std::fs::read_to_string(path).unwrap(), profile)); + } + for path in files.iter().filter(|_| !hlsl_dir) { + let Ok(blob) = std::fs::read(path) else { continue }; + let Some(sh) = crate::gpu::xbox::parse(&blob) else { continue }; + for f in &sh.fssm { + let Some(mode) = super::interface(&blob, &sh, f) else { continue }; + let profile = match &mode { + Mode::Vertex(_) => "vs_6_6", + Mode::Pixel(_) => "ps_6_6", + Mode::Compute(_) => "cs_6_6", + _ => continue, + }; + for p in &f.programs { + let code = &f.data[p.offset..p.offset + p.len]; + let opt = Options { mode: mode.clone(), wave64: super::detect_wave64(code), split_wave64: split, mem_windows: windows, ..Default::default() }; + let Ok(t) = translate(code, &opt) else { continue }; + if t.complete() { + let name = path.file_name().unwrap().to_string_lossy().into_owned(); + if let Ok(out) = std::env::var("XCL_BENCH_HLSL_OUT") { + let _ = std::fs::write(std::path::Path::new(&out).join(format!("{name}.{profile}.hlsl")), &t.hlsl); + } + jobs.push((name, t.hlsl, profile)); + } + } + } + } + let translate_s = t0.elapsed().as_secs_f64(); + let mut digest = 0xcbf2_9ce4_8422_2325u64; + for (_, h, p) in &jobs { + for b in h.bytes().chain(p.bytes()).chain([0]) { + digest ^= b as u64; + digest = digest.wrapping_mul(0x100_0000_01b3); + } + } + let bytes: usize = jobs.iter().map(|j| j.1.len()).sum(); + let distinct: std::collections::HashSet<(&str, &str)> = jobs.iter().map(|j| (j.1.as_str(), j.2)).collect(); + println!( + "programs {}, distinct HLSL {}, HLSL {:.1} MB, digest {digest:016x}, translate {translate_s:.2} s (one thread)", + jobs.len(), + distinct.len(), + bytes as f64 / 1048576.0 + ); + if std::env::var("XCL_BENCH_NO_DXC").is_ok() { + return; + } + let threads = std::env::var("XCL_BENCH_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or_else(super::dxc::compile_threads); + let next = std::sync::atomic::AtomicUsize::new(0); + let results: std::sync::Mutex> = Default::default(); + let dxil_digest = std::sync::atomic::AtomicU64::new(0); + let t1 = std::time::Instant::now(); + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| loop { + let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let Some((name, h, p)) = jobs.get(i) else { break }; + let t = std::time::Instant::now(); + let r = super::dxc::compile(h, "main", p, &extra); + let secs = t.elapsed().as_secs_f64(); + let n = r.as_ref().map_or(0, |b| b.len()); + // DXIL digest per program, combined by name below (order-free) + let mut d = 0xcbf2_9ce4_8422_2325u64; + for &b in r.as_deref().unwrap_or(&[]).iter().chain(name.as_bytes()).chain(p.as_bytes()) { + d ^= b as u64; + d = d.wrapping_mul(0x100_0000_01b3); + } + dxil_digest.fetch_xor(d, std::sync::atomic::Ordering::Relaxed); + if let Err(e) = &r { + println!(" {name}: {}", e.lines().find(|l| l.contains("error")).unwrap_or("")); + } + results.lock().unwrap().push((secs, h.len(), n, name.clone())); + }); + } + }); + let wall = t1.elapsed().as_secs_f64(); + if let Ok(out) = std::env::var("XCL_BENCH_TIMES") { + let t: String = results.lock().unwrap().iter().map(|(s, l, _, n)| format!("{n} {s:.4} {l} +")).collect(); + let _ = std::fs::write(out, t); + } + let mut r = results.into_inner().unwrap(); + r.sort_by(|a, b| a.0.total_cmp(&b.0)); + let sum: f64 = r.iter().map(|x| x.0).sum(); + let dxil: usize = r.iter().map(|x| x.2).sum(); + let failed = r.iter().filter(|x| x.2 == 0).count(); + let q = |f: f64| r[((r.len() - 1) as f64 * f) as usize].0; + println!( + "DXC {extra:?} threads {threads}: wall {wall:.2} s, {:.0} programs/s, per-program sum {sum:.1} s (median {:.3}, p90 {:.3}, max {:.2}), DXIL {:.1} MB (digest {:016x}), failed {failed}", + r.len() as f64 / wall, + q(0.5), + q(0.9), + q(1.0), + dxil as f64 / 1048576.0, + dxil_digest.into_inner() + ); + for (secs, len, _, name) in r.iter().rev().take(3) { + println!(" {secs:.2} s, HLSL {} KB: {name}", len / 1024); + } + // cost by size: ms per HLSL KB in size buckets (is DXC linear in the source?) + let mut buckets = std::collections::BTreeMap::::new(); + for (secs, len, _, _) in &r { + let b = buckets.entry((*len / 1024).next_power_of_two()).or_default(); + b.0 += 1; + b.1 += secs; + b.2 += len; + } + for (kb, (n, secs, len)) in buckets { + println!(" size <= {kb} KB: {n} programs, {:.1} ms each, {:.2} ms/KB", secs * 1e3 / n as f64, secs * 1e3 / (len as f64 / 1024.0)); + } + unsafe { + use windows_sys::Win32::System::ProcessStatus::{GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; + let mut c: PROCESS_MEMORY_COUNTERS = std::mem::zeroed(); + c.cb = std::mem::size_of::() as u32; + GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut c, c.cb); + println!(" peak commit {} MB", c.PeakPagefileUsage >> 20); + } +}