Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 19 additions & 8 deletions d3d12/crates/leonida-gpu/src/pipeline/library.rs
Original file line number Diff line number Diff line change
Expand Up @@ -616,14 +616,25 @@ pub(crate) fn pipeline(
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));
{
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.
// 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)
}
Expand Down
62 changes: 61 additions & 1 deletion d3d12/crates/leonida-gpu/src/pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,18 +38,55 @@ 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);
/// 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<u64> = 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::<u64>().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`].
/// 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);
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() {
Expand Down Expand Up @@ -572,6 +609,26 @@ fn grow_outside<B: Clone>(
(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);
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
/// `LEONIDA_POOL_GROW_UNLOCKED=0`), `make` making a block.
fn take_texture(len: u64, align: u64, make: impl FnMut() -> Option<ID3D12Heap>) -> Option<(Piece, ID3D12Heap, bool)> {
Expand Down Expand Up @@ -861,6 +918,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() },
Expand Down
5 changes: 3 additions & 2 deletions d3d12/docs/switches.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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. |
Expand Down Expand Up @@ -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). |
Expand Down Expand Up @@ -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=&lt;name&gt;[,&lt;name&gt;..]` 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=&lt;seconds&gt;[,&lt;seconds&gt;...]` prints each thread's unwound stack as `module+rva` that many seconds after [`dump_stacks_on_schedule`], to find what a title waits on. |

Expand Down