diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index b1fd4c2255..46c1c56533 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -75,7 +75,14 @@ fn build(p: &Arc, job: Job, preload: bool) { unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL) }; } } - complete(p, job()); + GAVE_UP.with(|g| g.set(false)); + let real = job(); + // the driver worked on a build ahead and ran out of memory: it would come back every run + // (not when a title thread came to wait for it meanwhile: its wanted build may have run beside it) + if preload && real == 0 && GAVE_UP.with(|g| g.get()) && !p.demand.lock().unwrap().wanted && used::skip(p.key) { + crate::xlog_warn!("D3D12.X: the driver gave up on a pipeline built ahead (shaders {:016x}): not built again", p.key); + } + complete(p, real); if preload { // (under the lock: `want` does not raise this thread after it) let mut d = p.demand.lock().unwrap(); @@ -360,6 +367,13 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { demand: Default::default(), }); PENDING.lock().unwrap().get_or_insert_with(HashMap::new).insert(standin, p.clone()); + if used::is_skipped(key) { + // the driver gave up on it in an earlier run: the stand-in, as when that build failed, + // instead of the same minute and tens of GB again (in the background or at a bind) + drop(p.job.lock().unwrap().take()); + complete(&p, 0); + return; + } static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| { crate::xlog_info!("D3D12.X: pipelines whose shaders are not compiled yet get a stand-in and are built in the background"); @@ -397,6 +411,8 @@ mod used { struct Used { earlier: RwLock>, now: Mutex<(HashSet, Option)>, + /// keys whose build the driver gave up on (`skip`, `!` lines) + skipped: RwLock>, } /// The keys in a `used-pipelines.txt` (lines that are not a hexadecimal key are passed over). @@ -404,15 +420,27 @@ mod used { text.lines().filter_map(|l| u64::from_str_radix(l.trim(), 16).ok()).filter(|&k| k != 0).collect() } + /// The keys a `!` line marks: the driver gave up on their build in an earlier run + /// (`skip`). Older builds pass over these lines. + pub fn skipped(text: &str) -> HashSet { + text.lines().filter_map(|l| l.trim().strip_prefix('!')).filter_map(|k| u64::from_str_radix(k, 16).ok()).filter(|&k| k != 0).collect() + } + fn get() -> &'static Used { static U: OnceLock = OnceLock::new(); U.get_or_init(|| { // (a test neither reads nor writes the user's file) if cfg!(test) { - return Used { earlier: RwLock::new(HashSet::new()), now: Mutex::new((HashSet::new(), None)) }; + return Used { earlier: RwLock::new(HashSet::new()), now: Mutex::new((HashSet::new(), None)), skipped: RwLock::new(HashSet::new()) }; } let path = crate::gpu::recomp::dxc::cache_dir().join("used-pipelines.txt"); - let earlier = parse(&std::fs::read_to_string(&path).unwrap_or_default()); + let text = std::fs::read_to_string(&path).unwrap_or_default(); + let used = parse(&text); + let skip = skipped(&text); + if !skip.is_empty() { + crate::xlog_info!("D3D12.X: {} shader sets the driver gave up on in an earlier run are not built again (stand-ins; delete their ! lines in used-pipelines.txt to retry)", skip.len()); + } + let earlier: HashSet = used.difference(&skip).copied().collect(); if !earlier.is_empty() { crate::xlog_info!("D3D12.X: the pipelines of {} shader sets an earlier run used are built ahead of their first use", earlier.len()); } @@ -420,7 +448,8 @@ mod used { let _ = std::fs::create_dir_all(dir); } let file = std::fs::OpenOptions::new().create(true).append(true).open(&path).ok(); - Used { now: Mutex::new((earlier.clone(), file)), earlier: RwLock::new(earlier) } + // (`now` keeps the skipped keys too, or `note` would add them again every run) + Used { now: Mutex::new((used, file)), earlier: RwLock::new(earlier), skipped: RwLock::new(skip) } }) } @@ -442,6 +471,26 @@ mod used { } } + /// The driver gave up on a pipeline of these shaders: it is not built again, in this run (a + /// title may make the same pipeline twice) or later ones (a `!` line). False: marked already. + pub fn skip(key: u64) -> bool { + if key == 0 || !get().skipped.write().unwrap().insert(key) { + return false; + } + get().earlier.write().unwrap().remove(&key); + let mut g = get().now.lock().unwrap(); + if let Some(f) = g.1.as_mut() { + // one write: two runs may append at once + let _ = f.write_all(format!("!{key:016x}\n").as_bytes()); + } + true + } + + /// The driver gave up on a pipeline of these shaders (`skip`). + pub fn is_skipped(key: u64) -> bool { + key != 0 && get().skipped.read().unwrap().contains(&key) + } + /// (tests) This run used a pipeline of these shaders. #[cfg(test)] pub fn noted(key: u64) -> bool { @@ -463,6 +512,21 @@ struct Preload { cv: Condvar, } +/// The driver "gave up" on a build (`note_driver_gave_up`): out of memory after at least this +/// long in it. A failure at once (a removed device fails every build) is tried again next run. +pub(super) const DRIVER_GAVE_UP_AFTER: std::time::Duration = std::time::Duration::from_secs(1); + +thread_local! { + static GAVE_UP: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Whether the driver gave up on the build this thread is running (out of memory after working +/// on it `DRIVER_GAVE_UP_AFTER` or longer, in its big-compile turn): a build ahead marks its +/// shaders `used::skip`. Each attempt sets it, so a retry that fails otherwise does not mark. +pub(super) fn note_driver_gave_up(gave_up: bool) { + GAVE_UP.with(|g| g.set(gave_up)); +} + fn preload() -> Option<&'static Preload> { static Q: OnceLock> = OnceLock::new(); static STARTED: std::sync::Once = std::sync::Once::new(); @@ -500,6 +564,12 @@ fn preload() -> Option<&'static Preload> { // (None: a bind took it and builds it itself) let job = p.job.lock().unwrap().take(); if let Some(job) = job { + // (another pipeline of the same shaders the driver gave up on meanwhile) + if used::is_skipped(p.key) { + drop(job); + complete(&p, 0); + continue; + } build(&p, job, true); let n = DONE.fetch_add(1, Ordering::Relaxed) + 1; if n.is_power_of_two() { @@ -696,6 +766,93 @@ mod used_tests { assert!(keys.contains(&0xff) && keys.contains(&0x1a2b)); } + #[test] + fn a_skipped_key_is_read_from_the_file() { + let text = "ff\n!00000000000000ff\n !1a2b \n!zz\n!\n!0\n"; + assert_eq!(used::skipped(text), [0xff, 0x1a2b].into_iter().collect()); + assert_eq!(used::parse(text), [0xff].into_iter().collect(), "what an older build reads"); + } + + fn wait_built(standin: usize) { + let start = std::time::Instant::now(); + while is_pending(standin) && start.elapsed() < std::time::Duration::from_secs(10) { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + } + + /// A pipeline whose build ahead the driver gave up on is not built again: a later pipeline + /// of the same shaders is the stand-in at once, neither built ahead nor at its first bind. + #[test] + fn a_pipeline_the_driver_gave_up_on_is_not_built_again() { + let (a, b) = (0x7E57_9001usize, 0x7E57_9002usize); + let key = 0x5EED_0011u64; + used::earlier_run_used(key); + submit_lazy(a, true, Box::new(|| { + note_driver_gave_up(true); + 0 + }), key); + wait_built(a); + assert_eq!(resolve(a), a, "failed: the stand-in"); + assert!(used::is_skipped(key)); + let ran = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let r = ran.clone(); + submit_lazy(b, true, Box::new(move || { + r.store(true, Ordering::Relaxed); + 0x4325 + }), key); + assert!(!is_pending(b), "done at once"); + assert_eq!(resolve_wait_for(b, None), b, "a bind gets the stand-in"); + assert!(!ran.load(Ordering::Relaxed), "never built"); + released(a); + released(b); + } + + /// A build ahead that fails otherwise (a removed device fails every build, or a retry after + /// the driver gave up fails for another reason) is tried again. + #[test] + fn a_build_ahead_that_fails_otherwise_is_tried_again() { + let (a, b) = (0x7E57_9003usize, 0x7E57_9004usize); + let key = 0x5EED_0012u64; + used::earlier_run_used(key); + // (a first attempt the driver gave up on, then a retry in the switch form that failed otherwise) + submit_lazy(a, true, Box::new(|| { + note_driver_gave_up(true); + note_driver_gave_up(false); + 0 + }), key); + wait_built(a); + assert!(!used::is_skipped(key)); + submit_lazy(b, true, Box::new(|| 0x4326), key); + wait_built(b); + assert!(!is_pending(b), "built ahead again"); + assert_eq!(resolve(b), 0x4326); + released(a); + released(b); + // the driver gave up while a title thread waited for the build: tried again too + let (c, key) = (0x7E57_9005usize, 0x5EED_0013u64); + used::earlier_run_used(key); + let (started, wanted) = (Arc::new(std::sync::atomic::AtomicBool::new(false)), Arc::new(std::sync::atomic::AtomicBool::new(false))); + let (s, w) = (started.clone(), wanted.clone()); + submit_lazy(c, true, Box::new(move || { + s.store(true, Ordering::Release); + note_driver_gave_up(true); + let start = std::time::Instant::now(); + while !build_is_wanted() && start.elapsed() < std::time::Duration::from_secs(10) { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + w.store(build_is_wanted(), Ordering::Relaxed); + 0 + }), key); + let start = std::time::Instant::now(); + while !started.load(Ordering::Acquire) && start.elapsed() < std::time::Duration::from_secs(10) { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert_eq!(resolve_wait_for(c, None), c, "failed: the stand-in"); + assert!(wanted.load(Ordering::Relaxed), "built ahead, then waited for"); + assert!(!used::is_skipped(key)); + released(c); + } + /// A lazy pipeline of shaders an earlier run used is built without a bind; another one is /// built only at its first use, and that use is kept for the next run. #[test] diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 4ea6374885..c3cbea667d 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4013,11 +4013,19 @@ fn pso_trace() -> bool { /// `driver_compile`, with the console record's hash (`fnv64` of the shader container, as in /// `[SHADER]` lines and `xcl shaders --measure-pso`) and whether a driver blob was supplied. -/// Also returns the time spent in the driver alone (not waiting for a slot). -fn driver_compile_identified(kind: &str, bytes: usize, gate: bool, record: Option<(u64, bool)>, build: impl FnOnce() -> R) -> (R, std::time::Duration) { +/// Also returns the time spent in the driver alone (not waiting for a slot), and whether it had +/// its turn (a slot with the commit free, no title thread waiting for it). +fn driver_compile_identified(kind: &str, bytes: usize, gate: bool, record: Option<(u64, bool)>, build: impl FnOnce() -> R) -> (R, std::time::Duration, bool) { let huge = gate && bytes >= huge_pso_bytes() && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); let waited = std::time::Instant::now(); - let _slot = huge.then(|| big_compile_turn(compile_slots(bytes), || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted)); + // its turn: the slot came with the commit free, not to a title thread waiting for it + // (`big_compile_turn` asks for the commit only when nobody waits, and takes the slot when it is free) + let turn = std::cell::Cell::new(false); + let commit_free = || { + turn.set(big_compile_commit_free(big_compile_headroom(bytes))); + turn.get() + }; + let _slot = huge.then(|| big_compile_turn(compile_slots(bytes), commit_free, super::pso_async::build_is_wanted)); let waited = waited.elapsed(); static SEQUENCE: AtomicU64 = AtomicU64::new(0); let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed) + 1; @@ -4034,7 +4042,7 @@ fn driver_compile_identified(kind: &str, bytes: usize, gate: bool, record: Op if log { crate::xlog_info!("D3D12.X: driver compile finish #{sequence}: {kind} PSO, {bytes} B DXIL, {} ms{}", took.as_millis(), gate_note(bytes >= huge_pso_bytes(), huge, waited)); } - (r, took) + (r, took, turn.get()) } /// How a logged driver compile went through the huge-pipeline gate. @@ -4046,6 +4054,13 @@ fn gate_note(huge_size: bool, gated: bool, waited: std::time::Duration) -> Strin } } +/// The driver gave up on a compute build: out of memory after working on it a while, in its +/// own turn with the commit free (not next to a title that waits for it). The preload does not +/// try such a pipeline again (`pso_async::note_driver_gave_up`). +fn driver_gave_up(hr: HRESULT, turn: bool, took: std::time::Duration) -> bool { + hr == E_OUTOFMEMORY && turn && took >= super::pso_async::DRIVER_GAVE_UP_AFTER +} + /// A cached-blob attempt should be quick and must not take a cold-compile slot. Its retry /// without the rejected blob is a cold compile and does take one. fn gate_compute_driver_compile(has_cached_blob: bool) -> bool { @@ -4206,6 +4221,16 @@ mod big_compile_tests { assert!(gate_compute_driver_compile(false), "a cold attempt, including a retry, is gated"); } + #[test] + fn only_a_long_out_of_memory_in_its_turn_is_giving_up() { + let long = super::super::pso_async::DRIVER_GAVE_UP_AFTER; + assert!(driver_gave_up(E_OUTOFMEMORY, true, long)); + assert!(!driver_gave_up(E_OUTOFMEMORY, false, long * 60), "next to a title that waits for it, or cached"); + assert!(!driver_gave_up(E_OUTOFMEMORY, true, long - std::time::Duration::from_millis(1)), "at once: a removed device"); + assert!(!driver_gave_up(E_INVALIDARG, true, long * 60), "another failure"); + assert!(!driver_gave_up(0, true, long * 60)); + } + #[test] fn the_concurrency_limit_holds_and_all_finish() { use std::sync::atomic::AtomicUsize; @@ -4285,6 +4310,8 @@ unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_voi unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option> { use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; + // (a retry in the switch form is judged on its own) + super::pso_async::note_driver_gave_up(false); if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { return None; } @@ -4388,13 +4415,14 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; } // in the background, a few at a time and within the commit headroom the program asks for - let (mut hr, mut in_driver) = driver_compile_identified( + let (mut hr, mut in_driver, turn) = driver_compile_identified( "compute", dxil.len(), gate_compute_driver_compile(cached.is_some()), Some((record, cached.is_some())), || finish_pso(this, f, © as *const _ as *const c_void, riid, ppv), ); + super::pso_async::note_driver_gave_up(driver_gave_up(hr, turn, in_driver)); if hr < 0 && cached.is_some() { // a blob the driver does not take (another root signature at the same address…): compiled forget_compute_blob(key); @@ -4402,7 +4430,7 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL driver_cache::note(false, disk.as_deref()); } copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); - let (retried, took) = driver_compile_identified( + let (retried, took, turn) = driver_compile_identified( "compute retry", dxil.len(), gate_compute_driver_compile(false), @@ -4411,6 +4439,7 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL ); hr = retried; in_driver += took; + super::pso_async::note_driver_gave_up(driver_gave_up(hr, turn, took)); } let reused = hr >= 0 && cached.is_some() && copy.CachedPSO.CachedBlobSizeInBytes != 0; if hr >= 0 && !reused { @@ -5158,7 +5187,10 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const driver_cache::note(false, disk.as_deref()); } }, - |label, has_cached, f| driver_compile_identified(label, bytes, gate_compute_driver_compile(has_cached), Some((ps_hash, has_cached)), f), + |label, has_cached, f| { + let (r, took, _) = driver_compile_identified(label, bytes, gate_compute_driver_compile(has_cached), Some((ps_hash, has_cached)), f); + (r, took) + }, |c| finish_pso(this, f, c as *const _ as *const c_void, riid, ppv), ); let hr = build.hr; @@ -5835,7 +5867,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: } let iid = pc_iid(Kind::PipelineState); let mut compute: *mut c_void = std::ptr::null_mut(); - let (mut hc, mut cin_driver) = driver_compile_identified("compute pass", tp.cs.len(), false, None, || { + let (mut hc, mut cin_driver, _) = driver_compile_identified("compute pass", tp.cs.len(), false, None, || { driver_pso(fc, this, &cdesc as *const _ as *const c_void, &iid, &mut compute) }); if hc < 0 && ccached.is_some() { @@ -5845,7 +5877,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: } cdesc.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); compute = std::ptr::null_mut(); - let (retried, took) = driver_compile_identified("compute pass retry", tp.cs.len(), false, None, || { + let (retried, took, _) = driver_compile_identified("compute pass retry", tp.cs.len(), false, None, || { driver_pso(fc, this, &cdesc as *const _ as *const c_void, &iid, &mut compute) }); hc = retried;