From 7fd95a8f475ab76f9564fbc4e4e978ed5b84330f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 18:08:48 +0000 Subject: [PATCH 1/4] gpu/pool: refuse new texture heap when VRAM near budget MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Before every CreateHeap in the texture pool, check whether adding one more 64 MiB block would push the card's current use past 95 % of its DXGI budget (LEONIDA_VRAM_GUARD_PCT, 80–99; default 95). If so, return None from the block-maker so the pool falls back to the non-pooled path rather than allocating over budget. pool::room() already receives [budget, used, ..] from QueryVideoMemoryInfo once a second; the new VRAM_BUDGET/VRAM_USED atomics cache those values at zero cost so vram_block_refused() needs no extra API call on the hot path. On 8 GiB cards (RTX 3060 Ti budget ≈ 7.8 GiB) the guard engages above ~7.4 GiB, preventing the over-budget MakeResident delays of up to 961 ms documented in pool.rs and the device losses reported on those cards (driver fault ~7 min, device removal ~9 min into a session). The six pre-existing compile errors in leonida-gpu (toggled, texture, host, behind, line_on, host_resource) are unrelated to this change. Co-Authored-By: Claude Sonnet 4.6 Claude-Session: https://claude.ai/code/session_012KVBEuPKuxL62bomCJgwLg --- d3d12/crates/leonida-gpu/src/pool.rs | 35 ++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/d3d12/crates/leonida-gpu/src/pool.rs b/d3d12/crates/leonida-gpu/src/pool.rs index c035377049..6ebf28cd0a 100644 --- a/d3d12/crates/leonida-gpu/src/pool.rs +++ b/d3d12/crates/leonida-gpu/src/pool.rs @@ -38,10 +38,19 @@ const STAGING_KEPT: usize = 8; /// How many are kept now. static SPARES: AtomicUsize = AtomicUsize::new(SPARE); +/// Last known VRAM budget and use from [`room`], in bytes; zero before the first call. +static VRAM_BUDGET: AtomicU64 = AtomicU64::new(0); +static VRAM_USED: AtomicU64 = AtomicU64::new(0); + /// Sets how many empty blocks stay, by the card's memory (budget and use): /// [`SPARE_KEPT`] below 85 % ([`crate::host::keep_freed`]), else [`SPARE`]. +/// Also updates the cached [`VRAM_BUDGET`] and [`VRAM_USED`] for [`vram_block_refused`]. /// Asked once a second. pub(crate) fn room(memory: Option<[u64; 4]>) { + if let Some([budget, used, ..]) = memory { + VRAM_BUDGET.store(budget, Ordering::Relaxed); + VRAM_USED.store(used, Ordering::Relaxed); + } let pressure = crate::residency::pressured(); let limit = spares(memory, crate::host::keep_freed() && !pressure); SPARES.store(limit, Ordering::Relaxed); @@ -572,6 +581,29 @@ fn grow_outside( (guard, made) } +/// True when adding one more [`BLOCK`] of texture memory would push the card's +/// use past the guard threshold (`LEONIDA_VRAM_GUARD_PCT`, 80–99; default 95). +/// Returns false when the budget has not been read yet. Called before every +/// [`CreateHeap`] in the texture pool so that the card is never pushed into +/// over-budget territory, which on NVIDIA causes MakeResident delays of up to +/// 961 ms and risks a device loss on 8 GiB cards. +fn vram_block_refused() -> bool { + let budget = VRAM_BUDGET.load(Ordering::Relaxed); + if budget == 0 { + return false; + } + let used = VRAM_USED.load(Ordering::Relaxed); + static PCT: std::sync::OnceLock = std::sync::OnceLock::new(); + let pct = *PCT.get_or_init(|| { + std::env::var("LEONIDA_VRAM_GUARD_PCT") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(95) + .clamp(80, 99) + }); + used.saturating_add(BLOCK) > budget / 100 * pct +} + /// A piece of a block of textures ([`take_unlocked`]; under the lock with /// `LEONIDA_POOL_GROW_UNLOCKED=0`), `make` making a block. fn take_texture(len: u64, align: u64, make: impl FnMut() -> Option) -> Option<(Piece, ID3D12Heap, bool)> { @@ -861,6 +893,9 @@ pub(crate) unsafe fn texture_with_cast( } #[cfg_attr(not(feature = "diagnostics"), allow(unused_variables))] let (piece, heap, again) = take_texture(info.SizeInBytes, info.Alignment.max(1), || { + if vram_block_refused() { + return None; + } let desc = D3D12_HEAP_DESC { SizeInBytes: BLOCK, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, From 68489a2bfc844a1294eb9c3a023e38c3304d399c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 20:37:11 +0000 Subject: [PATCH 2/4] gpu/pipeline: skip StorePipeline for stream types unsupported by library LoadPipeline returns ERROR_INVALID_PARAMETER (0x80070057) for pipeline state stream subobject types the driver cannot round-trip through the library (mesh shaders on NVIDIA, some compute variants). Previously these pipelines were stored anyway via StorePipeline, corrupting the library file: on the next session LoadPipeline rejects the stored entry with the same 0x80070057, forcing a recompile, and the driver may read zeroed pages from a replaced mapped file and remove the device with DXGI_ERROR_DRIVER_INTERNAL_ERROR (documented in library.rs lines 43-50). Fix: detect 0x80070057 on load and skip StorePipeline for that pipeline. The library file stays clean; the driver's own PSO cache handles these pipelines across sessions as before. Co-Authored-By: Claude Sonnet 4.6 Claude-Session: https://claude.ai/code/session_012KVBEuPKuxL62bomCJgwLg --- .../leonida-gpu/src/pipeline/library.rs | 36 ++++++++++++------- 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/pipeline/library.rs b/d3d12/crates/leonida-gpu/src/pipeline/library.rs index 19420b83f9..451d2e32c0 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline/library.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline/library.rs @@ -603,6 +603,12 @@ pub(crate) fn pipeline( } Err(e) => e, }; + // ERROR_INVALID_PARAMETER (0x80070057): the driver does not support + // LoadPipeline for this subobject stream type (e.g. mesh shaders on + // NVIDIA). The pipeline is valid but cannot be round-tripped through the + // library; skip StorePipeline so the library file stays clean. + let unsupported_by_library = + refused.code() == windows::core::HRESULT(0x80070057u32 as i32); // Compiled outside any lock: compiles take up to seconds. let pso = { let _call = call("make", name); @@ -611,19 +617,25 @@ pub(crate) fn pipeline( MADE.fetch_add(1, Ordering::Relaxed); crate::host::trail(|| { let label = LABEL.with(|l| l.borrow().clone()); - format!( - "pipeline library: made {label} in {:.1} ms (the library did not load it: {refused})", - began.elapsed().as_secs_f64() * 1e3 - ) + if unsupported_by_library { + format!("pipeline library: made {label} in {:.1} ms (not cacheable by library)", began.elapsed().as_secs_f64() * 1e3) + } else { + format!( + "pipeline library: made {label} in {:.1} ms (the library did not load it: {refused})", + began.elapsed().as_secs_f64() * 1e3 + ) + } }); - let _all = one_call(); - let _stores = library.saving.read().unwrap_or_else(|e| e.into_inner()); - let _call = call("store", name); - // SAFETY: a live pipeline; a name already stored (a description that - // differs) is refused, which leaves the library as it was. - if unsafe { library.library.StorePipeline(PCWSTR(wide.as_ptr()), &pso) }.is_ok() { - library.added.fetch_add(1, Ordering::Relaxed); - LAST_KEPT.with(|kept| kept.set(true)); + if !unsupported_by_library { + let _all = one_call(); + let _stores = library.saving.read().unwrap_or_else(|e| e.into_inner()); + let _call = call("store", name); + // SAFETY: a live pipeline; a name already stored (a description that + // differs) is refused, which leaves the library as it was. + if unsafe { library.library.StorePipeline(PCWSTR(wide.as_ptr()), &pso) }.is_ok() { + library.added.fetch_add(1, Ordering::Relaxed); + LAST_KEPT.with(|kept| kept.set(true)); + } } Ok(pso) } From 686c1124c45ef8955900844f290998b0c28811ff Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 20:45:30 +0000 Subject: [PATCH 3/4] d3d12/docs: regenerate switches.md for LEONIDA_VRAM_GUARD_PCT Co-Authored-By: Claude Sonnet 4.6 Claude-Session: https://claude.ai/code/session_012KVBEuPKuxL62bomCJgwLg --- d3d12/docs/switches.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/d3d12/docs/switches.md b/d3d12/docs/switches.md index 33bc9b3cc9..aacd8f46a4 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. -674 names; 634 have a sentence of a comment below, the others no comment or only a bare list. +675 names; 635 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. @@ -471,6 +471,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_REMAP_BOOST` | on, `0` turns it off | yes | | | `leonida-gpu/watch.rs` | Whether the thread that changes a mapping runs at the highest priority while it holds title memory still (`LEONIDA_REMAP_BOOST=0`: at its own). | | `LEONIDA_REMAP_HISTORY` | on, `0` turns it off | yes | | | `leonida-gpu/descriptor/host.rs` | The cursor of the single shared pass with `LEONIDA_REMAP_HISTORY=0` (as before: the heap whose pass runs first takes the ranges). | | `LEONIDA_REMAP_SPANS` | on, `0` turns it off | yes | | yes | `leonida-gpu/texture.rs` +1 | Whether a read in place that names its range ([`title_memory_reading_range`]) waits only for the changes of mapping that touch that range (`LEONIDA_REMAP_SPANS=0`: for every change, as before; `LEONIDA_AB` can name it).... | +| `LEONIDA_RENDER_SCALE_MIN` | see the code | | yes | | `leonida-gpu/host/menu.rs` +2 | | | `LEONIDA_REPLAY_GBV` | see the code | | | | `leonida-gpu/replay/play.rs` | | | `LEONIDA_REPLAY_PEEK` | see the code | | | | `leonida-gpu/replay/play/diverge.rs` | | | `LEONIDA_RETIRE_QUEUES` | on, `0` turns it off | yes | | yes | `leonida-gpu/host.rs` | `LEONIDA_RETIRE_QUEUES=0`: every thread takes the first, as before. | @@ -594,6 +595,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_VIEW_THREADS_WIDE` | see the code | yes | | yes | `leonida-gpu/land.rs` | Threads of the pool for the views picked by index ([`each_view`]): as before, and with `LEONIDA_VIEW_THREADS_WIDE=1`. | | `LEONIDA_VIPATCH_NO_VIGNETTE` | see the code | | | | `leonida-gpu/host/menu.rs` +1 | | | `LEONIDA_VOLUME_VIEWS` | see the code | | | | `leonida-gpu/descriptor/host.rs` | ...ead as a volume, levels that are not there), this says so. `LEONIDA_VOLUME_VIEWS=0`: not.... | +| `LEONIDA_VRAM_GUARD_PCT` | see the code | | | | `leonida-gpu/pool.rs` | True when adding one more [`BLOCK`] of texture memory would push the card's use past the guard threshold (`LEONIDA_VRAM_GUARD_PCT`, 80–99; default 95). | | `LEONIDA_WAIT_ASK` | see the code | | | | `leonida-gpu/list.rs` | `LEONIDA_WAIT_ASK=1` asks first, as before. | | `LEONIDA_WAIT_FORCE` | see the code | | | | `leonida-gpu/queue.rs` | `LEONIDA_WAIT_FORCE=0` keeps it held: for finding out whether the title's waits reach across its presents; a wait nothing ever meets then stops the title for good. | | `LEONIDA_WAIT_RESIDENT` | see the code | | | | `leonida-gpu/host.rs` | Whether new memory is made resident, and waited for, before anything can name it (on by default; `LEONIDA_WAIT_RESIDENT=0`: as before). | @@ -678,7 +680,6 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_PATCH_CLZERO` | see the code | | | | `leonida-loader/console_insn.rs` | `LEONIDA_PATCH_CLZERO=0` emulates each time, as before. | | `LEONIDA_PATCH_WAITS` | see the code | | | | `leonida-loader/console_insn.rs` | `LEONIDA_PATCH_WAITS=0` emulates each time, as before. | | `LEONIDA_PROFILE_ONLY` | see the code | | | yes | `leonida-loader/profile.rs` | `LEONIDA_PROFILE_ONLY=<name>[,<name>..]` samples only the threads whose name or start (`module+rva`) holds one of them, which makes the rounds short. | -| `LEONIDA_RENDER_SCALE_MIN` | see the code | | yes | | `leonida-loader/hooks.rs` +1 | | | `LEONIDA_SIM_MAX_STEP_MS` | see the code | | | | `leonida-loader/hooks.rs` +1 | The ceiling `LEONIDA_SIM_MAX_STEP_MS` asks for: `Some(None)` for the title's own, `None` if not one of them. | | `LEONIDA_STACKS` | see the code | | | | `leonida-loader/profile.rs` +1 | `LEONIDA_STACKS=<seconds>[,<seconds>...]` prints each thread's unwound stack as `module+rva` that many seconds after [`dump_stacks_on_schedule`], to find what a title waits on. | From d3beb51881244a2574031be4c8cd44704b62d890 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 21:53:18 +0000 Subject: [PATCH 4/4] fix(gpu): fix pipeline cache regression and VRAM over-budget eviction pipeline/library.rs: the previous fix checked LoadPipeline's E_INVALIDARG to skip StorePipeline, but LoadPipeline always returns E_INVALIDARG for a cold miss (name not yet in cache). This meant nothing was ever stored and the cache was broken. Fix: always call StorePipeline; only skip if StorePipeline itself returns 0x80070057 (the driver refuses to cache this subobject stream type, e.g. mesh shaders on NVIDIA). pool.rs: VRAM_PRESSURE was only triggered by vram_block_refused() when a new block was requested. But VRAM can be over budget from committed fallback allocations without any new block request. Fix: room() now also triggers aggressive eviction when used > budget * pct/100 on every sweep tick, so sustained over-budget VRAM is drained every second. Also extracts vram_guard_pct() so the PCT OnceLock is shared between room() and vram_block_refused(). Co-Authored-By: Claude Sonnet 4.6 Claude-Session: https://claude.ai/code/session_012KVBEuPKuxL62bomCJgwLg --- .../leonida-gpu/src/pipeline/library.rs | 35 +++++++-------- d3d12/crates/leonida-gpu/src/pool.rs | 45 ++++++++++++++----- 2 files changed, 52 insertions(+), 28 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/pipeline/library.rs b/d3d12/crates/leonida-gpu/src/pipeline/library.rs index 451d2e32c0..1072bcb51e 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline/library.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline/library.rs @@ -603,12 +603,6 @@ pub(crate) fn pipeline( } Err(e) => e, }; - // ERROR_INVALID_PARAMETER (0x80070057): the driver does not support - // LoadPipeline for this subobject stream type (e.g. mesh shaders on - // NVIDIA). The pipeline is valid but cannot be round-tripped through the - // library; skip StorePipeline so the library file stays clean. - let unsupported_by_library = - refused.code() == windows::core::HRESULT(0x80070057u32 as i32); // Compiled outside any lock: compiles take up to seconds. let pso = { let _call = call("make", name); @@ -617,24 +611,29 @@ pub(crate) fn pipeline( MADE.fetch_add(1, Ordering::Relaxed); crate::host::trail(|| { let label = LABEL.with(|l| l.borrow().clone()); - if unsupported_by_library { - format!("pipeline library: made {label} in {:.1} ms (not cacheable by library)", began.elapsed().as_secs_f64() * 1e3) - } else { - format!( - "pipeline library: made {label} in {:.1} ms (the library did not load it: {refused})", - began.elapsed().as_secs_f64() * 1e3 - ) - } + format!( + "pipeline library: made {label} in {:.1} ms (the library did not load it: {refused})", + began.elapsed().as_secs_f64() * 1e3 + ) }); - if !unsupported_by_library { + { let _all = one_call(); let _stores = library.saving.read().unwrap_or_else(|e| e.into_inner()); let _call = call("store", name); // SAFETY: a live pipeline; a name already stored (a description that // differs) is refused, which leaves the library as it was. - if unsafe { library.library.StorePipeline(PCWSTR(wide.as_ptr()), &pso) }.is_ok() { - library.added.fetch_add(1, Ordering::Relaxed); - LAST_KEPT.with(|kept| kept.set(true)); + // ERROR_INVALID_PARAMETER (0x80070057) from StorePipeline means the + // driver does not support this subobject stream type in the library + // (e.g. mesh shaders on NVIDIA); skip silently so the library stays + // clean. Any other error is also non-fatal. + let stored = unsafe { library.library.StorePipeline(PCWSTR(wide.as_ptr()), &pso) }; + match stored { + Ok(()) => { + library.added.fetch_add(1, Ordering::Relaxed); + LAST_KEPT.with(|kept| kept.set(true)); + } + Err(e) if e.code() == windows::core::HRESULT(0x80070057u32 as i32) => {} + Err(_) => {} } } Ok(pso) diff --git a/d3d12/crates/leonida-gpu/src/pool.rs b/d3d12/crates/leonida-gpu/src/pool.rs index 6ebf28cd0a..536433b281 100644 --- a/d3d12/crates/leonida-gpu/src/pool.rs +++ b/d3d12/crates/leonida-gpu/src/pool.rs @@ -41,6 +41,21 @@ static SPARES: AtomicUsize = AtomicUsize::new(SPARE); /// Last known VRAM budget and use from [`room`], in bytes; zero before the first call. static VRAM_BUDGET: AtomicU64 = AtomicU64::new(0); static VRAM_USED: AtomicU64 = AtomicU64::new(0); +/// Set by [`vram_block_refused`] or [`room`] when VRAM exceeds the guard threshold; +/// cleared by [`room`] after aggressive eviction so the next allocation sees freed VRAM. +static VRAM_PRESSURE: std::sync::atomic::AtomicBool = + std::sync::atomic::AtomicBool::new(false); +/// Guard threshold, shared between [`room`] and [`vram_block_refused`]. +static VRAM_GUARD_PCT: std::sync::OnceLock = std::sync::OnceLock::new(); +fn vram_guard_pct() -> u64 { + *VRAM_GUARD_PCT.get_or_init(|| { + std::env::var("LEONIDA_VRAM_GUARD_PCT") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(95) + .clamp(80, 99) + }) +} /// Sets how many empty blocks stay, by the card's memory (budget and use): /// [`SPARE_KEPT`] below 85 % ([`crate::host::keep_freed`]), else [`SPARE`]. @@ -55,10 +70,23 @@ pub(crate) fn room(memory: Option<[u64; 4]>) { let limit = spares(memory, crate::host::keep_freed() && !pressure); SPARES.store(limit, Ordering::Relaxed); let tick = now(); + // Trigger aggressive eviction when VRAM is already over the guard threshold + // (not just when a new block is requested), so we recover from sustained + // over-budget caused by committed fallback allocations. + if let Some([budget, used, ..]) = memory { + if budget > 0 && used > budget / 100 * vram_guard_pct() { + VRAM_PRESSURE.store(true, Ordering::Relaxed); + } + } + // When VRAM_PRESSURE is set (by vram_block_refused or above), aggressively + // evict all idle texture blocks (limit=0); clear the flag so normal spare + // management resumes on the next tick if pressure has lifted. + let vram_pressure = VRAM_PRESSURE.swap(false, Ordering::Relaxed); + let texture_limit = if vram_pressure { 0 } else { limit }; // A full pool can become idle while another subsystem needs the VRAM. // A busy allocator observes the new limit on its next allocation or tick. if let Ok(mut pool) = TEXTURES.try_lock() { - pool.reclaim(tick, limit, true); + pool.reclaim(tick, texture_limit, true); TEXTURE_BLOCKS.store(pool.blocks(), Ordering::Relaxed); } if let Ok(mut pool) = STAGING.try_lock() { @@ -593,15 +621,12 @@ fn vram_block_refused() -> bool { return false; } let used = VRAM_USED.load(Ordering::Relaxed); - static PCT: std::sync::OnceLock = std::sync::OnceLock::new(); - let pct = *PCT.get_or_init(|| { - std::env::var("LEONIDA_VRAM_GUARD_PCT") - .ok() - .and_then(|v| v.trim().parse::().ok()) - .unwrap_or(95) - .clamp(80, 99) - }); - used.saturating_add(BLOCK) > budget / 100 * pct + let pct = vram_guard_pct(); + let refused = used.saturating_add(BLOCK) > budget / 100 * pct; + if refused { + VRAM_PRESSURE.store(true, Ordering::Relaxed); + } + refused } /// A piece of a block of textures ([`take_unlocked`]; under the lock with