Files
Victory-RTX2080/patches/VIctory-NVIDIA-v2026.11.30.01-rtx3060-v21.patch
GiovannaSGuerrera a8a7f02069 VIctory Engine Deck RTX 2080 Edition (8GB VRAM)
- Rewrote README.md with complete RTX 2080 documentation
- Redesigned ENGINE_PRESETS in core.py with 5 RTX 2080 presets:
  * v21 8GB SEGURO (default), v21 NÍTIDO, v21 MAX FPS, v21 + DLSS FG 2x, v21 ORIGINAL
- Updated LauncherConfig defaults for RTX 2080 8GB
- Added VICTORY_DYNAMIC_SLOTS and VICTORY_L0_MAX_MB to Motor tab in app.py
- Updated tab_image descriptions for RTX 2080
- Added GitHub repo GiovannaSGuerrera/Victory-RTX2080 as default

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-12-04 14:18:25 -03:00

11803 lines
512 KiB
Diff
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

diff --git a/Cargo.toml b/Cargo.toml
index 8d3e714..baa6485 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -82,3 +82,10 @@ codegen-units = 1
# kept in its own folder so it does not evict the plain release build.
[profile.diag]
inherits = "release"
+
+# Fast parallel ThinLTO profile for znver3 + LLVM PGO builds (~3 min, low RAM).
+[profile.turbo]
+inherits = "release"
+lto = "thin"
+codegen-units = 16
+debug = false
diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs
index b7b2a36..855b2f1 100644
--- a/apps/victory/src/run.rs
+++ b/apps/victory/src/run.rs
@@ -777,6 +777,8 @@ pub fn run(
eprintln!("frame rate: invalid VICTORY_TITLE_FPS with {from}={ms} ms");
}
}
+ // SAFETY: the image stays mapped and nothing of it has run yet.
+ unsafe { victory_loader::engine::apply_asked(image.base(), image.info().size_of_image as usize) };
}
if !execute {
println!("not executing (pass --execute to start the title)");
diff --git a/crates/victory-gpu/examples/wc_probe.rs b/crates/victory-gpu/examples/wc_probe.rs
new file mode 100644
index 0000000..56c20cb
--- /dev/null
+++ b/crates/victory-gpu/examples/wc_probe.rs
@@ -0,0 +1,161 @@
+//! What the card's allocations add to the process's write-combined private
+//! memory: buffers, a heap and a texture in the card's own memory, an upload
+//! buffer, a write-back L0 buffer and a GPU_UPLOAD buffer are made one by one,
+//! and after each the process's private bytes and its write-combined private
+//! regions (committed, and in physical memory) are said.
+//!
+//! cargo run --release -p victory-gpu --example wc_probe
+//!
+//! Found with it (2026-11-29, RTX 4060 8 GB, Resizable BAR on, BAR1 8 GiB):
+//! every `DEFAULT` allocation adds its whole size to the private bytes and to
+//! the write-combined regions, and nothing in memory (the driver maps the
+//! card's memory for the CPU); an upload buffer adds its size to both and is
+//! in memory at once; a write-back L0 buffer is private but not
+//! write-combined; a GPU_UPLOAD buffer the CPU wrote is write-combined and in
+//! the working set.
+use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
+use windows::Win32::Graphics::Direct3D12::*;
+use windows::Win32::Graphics::Dxgi::Common::*;
+
+fn private_bytes() -> u64 {
+ use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
+ use windows_sys::Win32::System::Threading::GetCurrentProcess;
+ let mut c = PROCESS_MEMORY_COUNTERS { cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32, ..Default::default() };
+ // SAFETY: our own process and a sized structure.
+ unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) };
+ c.PagefileUsage as u64
+}
+
+/// Write-combined private bytes: committed, in memory, regions.
+fn write_combined() -> (u64, u64, usize) {
+ use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_PRIVATE, MEMORY_BASIC_INFORMATION, PAGE_WRITECOMBINE, VirtualQuery};
+ use windows_sys::Win32::System::ProcessStatus::K32QueryWorkingSetEx;
+ use windows_sys::Win32::System::Threading::GetCurrentProcess;
+ let (mut committed, mut present, mut regions) = (0, 0, 0);
+ let mut at = 0usize;
+ loop {
+ // SAFETY: plain data the query fills in.
+ let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
+ // SAFETY: a query of our own address space.
+ if unsafe { VirtualQuery(at as *const _, &mut info, size_of::<MEMORY_BASIC_INFORMATION>()) } == 0 {
+ break;
+ }
+ at = info.BaseAddress as usize + info.RegionSize;
+ if info.State != MEM_COMMIT || info.Type != MEM_PRIVATE || info.Protect & PAGE_WRITECOMBINE == 0 {
+ continue;
+ }
+ committed += info.RegionSize as u64;
+ regions += 1;
+ let base = info.BaseAddress as usize;
+ let mut asked: Vec<[usize; 2]> = (0..info.RegionSize).step_by(16 << 12).map(|o| [base + o, 0]).collect();
+ // SAFETY: entries of two words, as the call fills them.
+ if unsafe { K32QueryWorkingSetEx(GetCurrentProcess(), asked.as_mut_ptr().cast(), (asked.len() * 16) as u32) } != 0 {
+ present += asked.iter().filter(|a| a[1] & 1 != 0).count() as u64 * (16 << 12);
+ }
+ }
+ (committed, present, regions)
+}
+
+fn say(step: &str) {
+ let (wc, wc_in, n) = write_combined();
+ println!(
+ "{step:48} private {:6} MB; write-combined {:6} MB committed ({:5} MB in memory, {n} regions)",
+ private_bytes() >> 20,
+ wc >> 20,
+ wc_in >> 20
+ );
+}
+
+fn main() -> windows::core::Result<()> {
+ // SAFETY: plain D3D12 calls with valid out pointers; mappings are written
+ // within their size.
+ unsafe {
+ let mut device: Option<ID3D12Device> = None;
+ D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?;
+ let device = device.unwrap();
+ say("device");
+ let buffer = |props: D3D12_HEAP_PROPERTIES, size: u64, state| -> windows::core::Result<ID3D12Resource> {
+ let mut r: Option<ID3D12Resource> = None;
+ let desc = D3D12_RESOURCE_DESC {
+ Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
+ Width: size,
+ Height: 1,
+ DepthOrArraySize: 1,
+ MipLevels: 1,
+ SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+ Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
+ ..Default::default()
+ };
+ device.CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut r)?;
+ Ok(r.unwrap())
+ };
+ let write = |r: &ID3D12Resource, size: usize| -> windows::core::Result<()> {
+ let mut p = std::ptr::null_mut();
+ r.Map(0, None, Some(&mut p))?;
+ std::ptr::write_bytes(p.cast::<u8>(), 1, size);
+ Ok(())
+ };
+ let kind = |t| D3D12_HEAP_PROPERTIES { Type: t, ..Default::default() };
+ let mut card = vec![];
+ for _ in 0..4 {
+ card.push(buffer(kind(D3D12_HEAP_TYPE_DEFAULT), 256 << 20, D3D12_RESOURCE_STATE_COMMON)?);
+ }
+ say("+4 x 256 MiB DEFAULT buffers");
+ let mut heap: Option<ID3D12Heap> = None;
+ device.CreateHeap(
+ &D3D12_HEAP_DESC {
+ SizeInBytes: 512 << 20,
+ Properties: kind(D3D12_HEAP_TYPE_DEFAULT),
+ Alignment: 0,
+ Flags: D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES,
+ },
+ &mut heap,
+ )?;
+ say("+512 MiB DEFAULT heap");
+ let mut texture: Option<ID3D12Resource> = None;
+ device.CreateCommittedResource(
+ &kind(D3D12_HEAP_TYPE_DEFAULT),
+ D3D12_HEAP_FLAG_NONE,
+ &D3D12_RESOURCE_DESC {
+ Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
+ Width: 8192,
+ Height: 8192,
+ DepthOrArraySize: 1,
+ MipLevels: 1,
+ Format: DXGI_FORMAT_R8G8B8A8_UNORM,
+ SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+ ..Default::default()
+ },
+ D3D12_RESOURCE_STATE_COMMON,
+ None,
+ &mut texture,
+ )?;
+ say("+256 MiB DEFAULT texture");
+ let upload = buffer(kind(D3D12_HEAP_TYPE_UPLOAD), 256 << 20, D3D12_RESOURCE_STATE_GENERIC_READ)?;
+ say("+256 MiB UPLOAD buffer, not mapped");
+ write(&upload, 256 << 20)?;
+ say(" mapped and written");
+ let l0 = D3D12_HEAP_PROPERTIES {
+ Type: D3D12_HEAP_TYPE_CUSTOM,
+ CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
+ MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
+ ..Default::default()
+ };
+ let wb = buffer(l0, 256 << 20, D3D12_RESOURCE_STATE_COMMON)?;
+ write(&wb, 256 << 20)?;
+ say("+256 MiB CUSTOM L0 WRITE_BACK, written");
+ match buffer(kind(D3D12_HEAP_TYPE_GPU_UPLOAD), 256 << 20, D3D12_RESOURCE_STATE_COMMON) {
+ Ok(bar) => {
+ write(&bar, 256 << 20)?;
+ say("+256 MiB GPU_UPLOAD, written");
+ card.push(bar);
+ }
+ Err(e) => println!("GPU_UPLOAD refused: {e}"),
+ }
+ drop(card);
+ say("DEFAULT buffers and GPU_UPLOAD gone");
+ drop((heap, texture, upload, wb));
+ say("all gone");
+ }
+ Ok(())
+}
diff --git a/crates/victory-gpu/src/cores.rs b/crates/victory-gpu/src/cores.rs
index 50ca932..e72ed8e 100644
--- a/crates/victory-gpu/src/cores.rs
+++ b/crates/victory-gpu/src/cores.rs
@@ -236,7 +236,13 @@ pub(crate) fn place_process() {
/// `VICTORY_WAIT_SPIN=500`; not shown to help yet.
fn carve_submit_core_alone() {
use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessAffinityMask, SetProcessDefaultCpuSets};
- if submit_core_mode() == SubmitCore::Off || std::env::var_os("VICTORY_SUBMIT_CORE_ALONE").is_none_or(|v| v != "1") {
+ // `VICTORY_THREADS_BY_CORES=1` asks for it too, unless `VICTORY_SUBMIT_CORE_ALONE=0`.
+ let alone = match std::env::var("VICTORY_SUBMIT_CORE_ALONE").ok().as_deref().map(str::trim) {
+ Some("1") => true,
+ Some("0") => false,
+ _ => by_cores(),
+ };
+ if submit_core_mode() == SubmitCore::Off || !alone {
return;
}
let sets = cpu_sets();
@@ -276,6 +282,64 @@ fn carve_submit_core_alone() {
/// Whether [`carve_submit_core_alone`] kept a core for the submitting thread.
static SUBMIT_ALONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
+/// `VICTORY_THREADS_BY_CORES=1` (off by default): our pools are sized by the physical cores the
+/// process's threads may run on ([`pool_cores`]), not by logical processors; on a processor of
+/// one core class with SMT and six cores or more one core is kept for the submitting thread
+/// ([`carve_submit_core_alone`], unless `VICTORY_SUBMIT_CORE_ALONE=0`); and with eight such cores
+/// or fewer the submitting thread runs at "highest" and the list translators at normal at most,
+/// below the helpers the submitting thread waits for (`VICTORY_HELPER_PRIORITY`).
+///
+/// Why: on a Ryzen 5 7600 (6 cores, 12 threads) the defaults, made for logical processors, gave
+/// 8 list translators, 4 wide helpers, 3 landing threads, 6+6+4 for under-writes, records and
+/// views, 8 pipeline workers and 12 DirectStorage workers beside the title's threads; the
+/// translators (`VICTORY_HELPER_PRIORITY=1`) ran at the submitting thread's own priority, and
+/// 653 ms of their time a frame (81405 calls, 8 us each) was spent on 12 logical processors
+/// in a 108 ms frame while the submitting thread was busy 100 ms of it.
+pub(crate) fn by_cores() -> bool {
+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+ *ON.get_or_init(|| {
+ let on = std::env::var_os("VICTORY_THREADS_BY_CORES").is_some_and(|v| v == "1");
+ tracing::info!(on, "our pools sized by physical cores (VICTORY_THREADS_BY_CORES=1: they are)");
+ on
+ })
+}
+
+/// The physical cores among `sets` (`(id, class, logical, core)`) that `allowed` set ids leave
+/// (all of them without), at least one.
+fn cores_in(sets: &[(u32, u8, u8, u8)], allowed: Option<&[u32]>) -> usize {
+ let mut cores: Vec<u8> = sets.iter().filter(|s| allowed.is_none_or(|a| a.contains(&s.0))).map(|s| s.3).collect();
+ cores.sort_unstable();
+ cores.dedup();
+ cores.len().max(1)
+}
+
+/// The physical cores the process's threads run on: those of its default sets where
+/// [`place_process`] or [`carve_submit_core_alone`] set them, else all of group 0's.
+pub(crate) fn pool_cores() -> usize {
+ let sets = cpu_sets();
+ if sets.is_empty() {
+ return std::thread::available_parallelism().map_or(4, |n| n.get());
+ }
+ cores_in(&sets, PROCESS_SETS.get().map(Vec::as_slice))
+}
+
+/// A pool's size: `logical` (as before) unless [`by_cores`], then `by` of [`pool_cores`] (logged).
+pub(crate) fn sized(what: &str, logical: usize, by: impl FnOnce(usize) -> usize) -> usize {
+ if !by_cores() {
+ return logical;
+ }
+ let cores = pool_cores();
+ let threads = by(cores).max(1);
+ tracing::info!(what, cores, threads, was = logical, "a pool sized by physical cores (VICTORY_THREADS_BY_CORES=1)");
+ threads
+}
+
+/// With [`by_cores`]: eight physical cores or fewer, where the submitting thread is put ahead
+/// of the threads that translate lists.
+fn few_cores() -> bool {
+ by_cores() && pool_cores() <= 8
+}
+
/// The runtime's "D3D Background Thread"s (shaders compiled again, for minutes after pipelines are
/// made or loaded) on the other half too: as threads of the process they take its default sets.
fn keep_runtime_compiles_off_the_frames_cores() {
@@ -392,7 +456,10 @@ pub(crate) fn hold_on_fast_cores(hold: bool) {
/// The logical processors [`keep_off_the_frames_cores`] puts a thread on: the other half where
/// the process was placed, else all of them.
pub(crate) fn off_the_frames_cores() -> usize {
- placed().map_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get()), |h| h.1.len())
+ placed().map_or_else(
+ || if by_cores() { pool_cores() } else { std::thread::available_parallelism().map_or(4, |n| n.get()) },
+ |h| h.1.len(),
+ )
}
/// `VICTORY_FAST_CORES`: 0: no thread asks; 1 (the default): the threads a
@@ -411,20 +478,10 @@ fn stage() -> u32 {
/// `VICTORY_SUBMIT_PRIORITY` overrides it).
pub(crate) fn keep_submit_core(what: &str) {
use windows_sys::Win32::System::Threading::{
- GetCurrentThread, SetThreadPriority, SetThreadSelectedCpuSets, THREAD_PRIORITY_ABOVE_NORMAL,
- THREAD_PRIORITY_HIGHEST,
+ GetCurrentThread, SetThreadPriority, SetThreadSelectedCpuSets,
};
keep_on_fast_cores(what);
- let prio = match std::env::var("VICTORY_SUBMIT_PRIORITY").ok().and_then(|v| v.trim().parse::<i32>().ok()) {
- Some(p) => p.clamp(-2, 2),
- None => {
- if PLACED.load(std::sync::atomic::Ordering::Acquire) || SUBMIT_ALONE.load(std::sync::atomic::Ordering::Acquire) {
- THREAD_PRIORITY_HIGHEST
- } else {
- THREAD_PRIORITY_ABOVE_NORMAL
- }
- }
- };
+ let prio = submit_priority();
// SAFETY: our own thread.
unsafe { SetThreadPriority(GetCurrentThread(), prio) };
let id = SUBMIT_SET.load(std::sync::atomic::Ordering::Acquire);
@@ -460,26 +517,86 @@ pub(crate) fn keep_many_on_fast_cores(what: &str) {
}
/// `VICTORY_LIST_PRIORITY` (`-2..=2`) if set; else `BELOW_NORMAL` when placed
-/// on one V-Cache CCD, or `helper_prio` (`VICTORY_HELPER_PRIORITY`) otherwise.
-fn list_priority_for(is_placed: bool, override_val: Option<&str>, helper_prio: Option<i32>) -> Option<i32> {
+/// on one V-Cache CCD, or `helper_prio` (`VICTORY_HELPER_PRIORITY`) otherwise,
+/// normal at most where `few` ([`few_cores`]: below the submitting thread and its helpers).
+fn list_priority_for(is_placed: bool, override_val: Option<&str>, helper_prio: Option<i32>, few: bool) -> Option<i32> {
if let Some(p) = override_val.and_then(|v| v.trim().parse::<i32>().ok()) {
return Some(p.clamp(-2, 2));
}
if is_placed {
Some(windows_sys::Win32::System::Threading::THREAD_PRIORITY_BELOW_NORMAL)
+ } else if few {
+ Some(helper_prio.unwrap_or(0).min(0))
} else {
helper_prio
}
}
+/// The priority `victory-submit` runs at (`VICTORY_SUBMIT_PRIORITY`, else
+/// `HIGHEST` when it has a core of its own, `ABOVE_NORMAL` otherwise).
+fn submit_priority() -> i32 {
+ use windows_sys::Win32::System::Threading::{THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_HIGHEST};
+ match std::env::var("VICTORY_SUBMIT_PRIORITY").ok().and_then(|v| v.trim().parse::<i32>().ok()) {
+ Some(p) => p.clamp(-2, 2),
+ None => {
+ if PLACED.load(std::sync::atomic::Ordering::Acquire)
+ || SUBMIT_ALONE.load(std::sync::atomic::Ordering::Acquire)
+ || few_cores()
+ {
+ THREAD_PRIORITY_HIGHEST
+ } else {
+ THREAD_PRIORITY_ABOVE_NORMAL
+ }
+ }
+ }
+}
+
+/// `VICTORY_LIST_BELOW_SUBMIT` (on unless `0`): a translator priority
+/// (`None`: normal) not below the submitting thread's is put one below it.
+/// With `VICTORY_HELPER_PRIORITY=1` and no placing, the eight translators ran
+/// at `ABOVE_NORMAL`, the submitting thread's own, on a 6-core/12-thread
+/// part: 653 ms of translation a frame, off the frame's path (the
+/// submitting thread worked 99.5 of 108 ms, the title never waited for room
+/// in the line), competing with that thread and its refresh helpers.
+fn below_submit(priority: Option<i32>, submit: i32) -> Option<i32> {
+ if priority.unwrap_or(0) >= submit { Some((submit - 1).max(-2)) } else { priority }
+}
+
+/// The physical cores of group 0's logical processors (0 if not known).
+pub(crate) fn physical_cores() -> usize {
+ let mut cores: Vec<u8> = cpu_sets().iter().map(|s| s.3).collect();
+ cores.sort_unstable();
+ cores.dedup();
+ cores.len()
+}
+
/// Priority and core selection for command-list translators (`victory-list-*`).
/// When placed on one V-Cache CCD, inherits its CPU sets and yields via `BELOW_NORMAL`.
+/// Below the submitting thread ([`below_submit`]) unless `VICTORY_LIST_PRIORITY` says.
pub(crate) fn keep_list_worker(what: &str) {
use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority};
select_fast_cores(what, 3);
let env = std::env::var("VICTORY_LIST_PRIORITY").ok();
let placed_now = PLACED.load(std::sync::atomic::Ordering::Acquire);
- if let Some(priority) = list_priority_for(placed_now, env.as_deref(), helper_priority()) {
+ let mut priority = list_priority_for(placed_now, env.as_deref(), helper_priority(), few_cores());
+ let explicit = env.as_deref().is_some_and(|v| v.trim().parse::<i32>().is_ok());
+ if !explicit && std::env::var_os("VICTORY_LIST_BELOW_SUBMIT").is_none_or(|v| v != "0") {
+ let submit = submit_priority();
+ let capped = below_submit(priority, submit);
+ if capped != priority {
+ static ONCE: std::sync::Once = std::sync::Once::new();
+ ONCE.call_once(|| {
+ tracing::info!(
+ was = priority.unwrap_or(0),
+ now = capped.unwrap_or(0),
+ submit,
+ "list translators run below the submitting thread (VICTORY_LIST_BELOW_SUBMIT=0: as before)"
+ );
+ });
+ priority = capped;
+ }
+ }
+ if let Some(priority) = priority {
// SAFETY: this thread's own priority.
let set = unsafe { SetThreadPriority(GetCurrentThread(), priority) } != 0;
tracing::debug!(what, priority, set, "list translator priority (VICTORY_LIST_PRIORITY)");
@@ -764,16 +881,28 @@ mod tests {
fn list_worker_priority_drops_below_normal_only_when_placed_or_overridden() {
use windows_sys::Win32::System::Threading::THREAD_PRIORITY_BELOW_NORMAL;
// When not placed on one CCD, preserve `VICTORY_HELPER_PRIORITY` behaviour.
- assert_eq!(list_priority_for(false, None, None), None);
- assert_eq!(list_priority_for(false, None, Some(1)), Some(1));
- assert_eq!(list_priority_for(false, Some("-1"), Some(1)), Some(-1));
+ assert_eq!(list_priority_for(false, None, None, false), None);
+ assert_eq!(list_priority_for(false, None, Some(1), false), Some(1));
+ assert_eq!(list_priority_for(false, Some("-1"), Some(1), false), Some(-1));
// When placed on one V-Cache CCD, drop below normal unless explicitly overridden.
- assert_eq!(list_priority_for(true, None, Some(1)), Some(THREAD_PRIORITY_BELOW_NORMAL));
- assert_eq!(list_priority_for(true, None, None), Some(THREAD_PRIORITY_BELOW_NORMAL));
- assert_eq!(list_priority_for(true, Some("0"), Some(1)), Some(0));
- assert_eq!(list_priority_for(true, Some("9"), Some(1)), Some(2));
- assert_eq!(list_priority_for(true, Some("-9"), Some(1)), Some(-2));
- assert_eq!(list_priority_for(true, Some("bad"), Some(1)), Some(THREAD_PRIORITY_BELOW_NORMAL));
+ assert_eq!(list_priority_for(true, None, Some(1), false), Some(THREAD_PRIORITY_BELOW_NORMAL));
+ assert_eq!(list_priority_for(true, None, None, false), Some(THREAD_PRIORITY_BELOW_NORMAL));
+ assert_eq!(list_priority_for(true, Some("0"), Some(1), false), Some(0));
+ assert_eq!(list_priority_for(true, Some("9"), Some(1), false), Some(2));
+ assert_eq!(list_priority_for(true, Some("-9"), Some(1), false), Some(-2));
+ assert_eq!(list_priority_for(true, Some("bad"), Some(1), false), Some(THREAD_PRIORITY_BELOW_NORMAL));
+ // Few physical cores (`VICTORY_THREADS_BY_CORES=1`): normal at most, an override still wins.
+ assert_eq!(list_priority_for(false, None, Some(1), true), Some(0));
+ assert_eq!(list_priority_for(false, None, None, true), Some(0));
+ assert_eq!(list_priority_for(false, None, Some(-1), true), Some(-1));
+ assert_eq!(list_priority_for(false, Some("1"), Some(1), true), Some(1));
+ // Below the submitting thread unless already so.
+ assert_eq!(below_submit(Some(1), 1), Some(0));
+ assert_eq!(below_submit(None, 1), None);
+ assert_eq!(below_submit(None, 0), Some(-1));
+ assert_eq!(below_submit(Some(THREAD_PRIORITY_BELOW_NORMAL), 2), Some(THREAD_PRIORITY_BELOW_NORMAL));
+ assert_eq!(below_submit(Some(2), 2), Some(1));
+ assert_eq!(below_submit(Some(-2), -2), Some(-2));
}
#[test]
@@ -790,6 +919,16 @@ mod tests {
assert_eq!(raised_priority(false, Some(1)), THREAD_PRIORITY_NORMAL);
}
+ #[test]
+ fn physical_cores_are_counted_once_and_only_those_allowed() {
+ // Six cores, two logical processors each (as a Ryzen 5 7600).
+ let sets: Vec<(u32, u8, u8, u8)> = (0..12u8).map(|i| (256 + u32::from(i), 0, i, i / 2)).collect();
+ assert_eq!(cores_in(&sets, None), 6);
+ let without_last: Vec<u32> = sets.iter().filter(|s| s.3 != 5).map(|s| s.0).collect();
+ assert_eq!(cores_in(&sets, Some(&without_last)), 5);
+ assert_eq!(cores_in(&sets, Some(&[])), 1);
+ }
+
/// Stand-ins for the title's threads beside the cost tests after this one: `VICTORY_TEST_LOAD=<n>` (none
/// without), each through 4 MB of its own; prints their passes a second and one more thread's time for 256.
#[test]
diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs
index 86e3569..5bfd10e 100644
--- a/crates/victory-gpu/src/descriptor.rs
+++ b/crates/victory-gpu/src/descriptor.rs
@@ -70,6 +70,11 @@ pub(crate) mod queue_site {
pub(crate) static QUEUE_LOCK: [[std::sync::atomic::AtomicU64; queue_site::COUNT]; 4] =
[const { [const { std::sync::atomic::AtomicU64::new(0) }; queue_site::COUNT] }; 4];
+/// Since the last 5-second line, of the changes to the texture queue noted
+/// without waiting for its lock (`VICTORY_QUEUE_POST`): left to be made,
+/// of them found the lock held (made by its holder), and made.
+pub(crate) static QUEUE_POSTED: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
+
const HEAP_IIDS: [Iid; 4] = [
guid(
0x8efb471d,
diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs
index d628b5d..286fac4 100644
--- a/crates/victory-gpu/src/descriptor/host.rs
+++ b/crates/victory-gpu/src/descriptor/host.rs
@@ -253,6 +253,14 @@ pub(crate) struct HostHeap {
/// on every `TextureQueue` state change so published [`QueueBatch`] flushes
/// drop superseded ops and stay linearizable with lock-free `marks` skips.
slot_state: Box<[std::sync::atomic::AtomicU32]>,
+ /// Changes to `textures` noted while its lock was held, left for the
+ /// next to hold it, which makes them before anything else
+ /// (`VICTORY_QUEUE_POST`, [`HostHeap::post`]); `posted_len`: how many.
+ posted_ops: Mutex<Vec<QueueOp>>,
+ posted_len: std::sync::atomic::AtomicUsize,
+ /// Per title slot, how many of `posted_ops` are its: while any are, its
+ /// marks are not read and a new note of it waits for them to be made.
+ posted: Box<[std::sync::atomic::AtomicU16]>,
/// Capacity hints for [`Due`] (`again`, `fresh`, `checked`), pre-allocated
/// before taking `textures`'s lock so steady-state passes avoid reallocs
/// inside the critical section.
@@ -1561,6 +1569,14 @@ fn queue_marks() -> bool {
*ON.get_or_init(|| std::env::var_os("VICTORY_QUEUE_MARKS").is_none_or(|v| v != "0"))
}
+/// Whether a note of a slot's record that finds the queue's lock held
+/// leaves its change for the holder instead of waiting for it
+/// (`VICTORY_QUEUE_POST=0`: it waits, as before; [`HostHeap::post`]).
+fn queue_post() -> bool {
+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var_os("VICTORY_QUEUE_POST").is_none_or(|v| v != "0"))
+}
+
/// The queue's lock was not taken at place `site` (`super::queue_site`), as
/// nothing would have changed: counted in `super::QUEUE_LOCK`, by the
/// thread in batches (these happen hundreds of thousands of times in five
@@ -2626,6 +2642,13 @@ impl QueueBatch {
}
fn apply(&mut self, textures: &mut TextureQueue, slot_state: &[std::sync::atomic::AtomicU32]) {
+ self.seen_bits = 0;
+ Self::apply_ops(&self.ops, textures, slot_state);
+ self.ops.clear();
+ }
+
+ /// [`QueueBatch::apply`] of `ops`, in order, leaving them in place.
+ fn apply_ops(ops: &[QueueOp], textures: &mut TextureQueue, slot_state: &[std::sync::atomic::AtomicU32]) {
use std::sync::atomic::Ordering::{Acquire, SeqCst};
#[derive(Clone, Copy)]
enum Applied {
@@ -2659,10 +2682,9 @@ impl QueueBatch {
}
*count = 0;
};
- self.seen_bits = 0;
let mut applied = [None; Self::LIMIT];
let mut count = 0usize;
- for op in self.ops.drain(..) {
+ for &op in ops {
let atom = slot_state.get(op.index() as usize);
match op {
QueueOp::Write { index, state, frame, due, seen } => {
@@ -2697,6 +2719,13 @@ impl QueueBatch {
if self.ops.is_empty() {
return;
}
+ // Left for the queue's lock's holder, when it is held
+ // (`VICTORY_QUEUE_POST`, [`HostHeap::post`]).
+ if host.posts(&self.ops) {
+ self.seen_bits = 0;
+ host.post(&mut self.ops);
+ return;
+ }
let mut textures = host.queue(super::queue_site::WRITE);
self.apply(&mut textures, &host.slot_state);
}
@@ -2983,14 +3012,36 @@ fn view_home(
}
/// For device-removed reports: what the slots of the title's view heap that
-/// the words of user data may name hold now ([`crate::host::indirects`]).
+/// the words of user data name hold now ([`crate::host::indirects`]):
+/// `tables` says which words are tables (0: not known). A table's slots past
+/// the title's are dynamic ones, of a table made afresh, and are told as
+/// such: #3222's report left out the table its dispatch read, at slot
+/// 613,663 of a heap with 606,783 title slots.
#[cfg(feature = "diagnostics")]
-pub(crate) fn describe_slots(words: &[u32]) -> Vec<(usize, u32, String)> {
+pub(crate) fn describe_slots(words: &[u32], tables: u16) -> Vec<(usize, u32, String)> {
super::with_view_heap(|host| {
- crate::host::indirects::slots(words, host.count, 6)
+ crate::host::indirects::slots(words, tables, host.count + host.dynamic, 8)
.into_iter()
.take(24)
- .map(|(word, slot)| (word, slot, host.describe_slot(slot).unwrap_or_default()))
+ .map(|(word, slot)| {
+ let what = if slot < host.count {
+ host.describe_slot(slot).unwrap_or_default()
+ } else {
+ let at = slot - host.count;
+ let taken = host.next.lock().unwrap_or_else(|e| e.into_inner()).is_taken(at);
+ let shows = host.kept_in(slot).map(|r| {
+ // SAFETY: a live resource the slot keeps.
+ let d = unsafe { r.GetDesc() };
+ if d.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER {
+ format!("a buffer of {} bytes", d.Width)
+ } else {
+ format!("a texture of {}x{}", d.Width, d.Height)
+ }
+ });
+ format!("dynamic slot {at} (taken {taken:?}, shows {})", shows.as_deref().unwrap_or("no resource"))
+ };
+ (word, slot, what)
+ })
.collect()
})
.unwrap_or_default()
@@ -3457,6 +3508,11 @@ impl HostHeap {
slot_state: (0..if sampler { 0 } else { count as usize })
.map(|_| std::sync::atomic::AtomicU32::new(0))
.collect(),
+ posted_ops: Mutex::new(Vec::new()),
+ posted_len: std::sync::atomic::AtomicUsize::new(0),
+ posted: (0..if sampler { 0 } else { count as usize })
+ .map(|_| std::sync::atomic::AtomicU16::new(0))
+ .collect(),
due_hints: [const { std::sync::atomic::AtomicUsize::new(0) }; 3],
tabled: (0..if sampler { 0 } else { count })
.map(|_| std::sync::atomic::AtomicU32::new(0))
@@ -3565,6 +3621,9 @@ fn null_sampler(at: D3D12_CPU_DESCRIPTOR_HANDLE) {
struct QueueGuard<'a> {
queue: std::sync::MutexGuard<'a, TextureQueue>,
held: Option<(usize, std::time::Instant)>,
+ /// The heap whose changes left for the holder are made when the lock is
+ /// taken and again before it is let go ([`HostHeap::post`]).
+ host: &'a HostHeap,
}
impl std::ops::Deref for QueueGuard<'_> {
@@ -3582,6 +3641,7 @@ impl std::ops::DerefMut for QueueGuard<'_> {
impl Drop for QueueGuard<'_> {
fn drop(&mut self) {
+ self.host.make_posted(&mut self.queue);
if let Some((site, since)) = self.held {
super::QUEUE_LOCK[2][site].fetch_add(since.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed);
}
@@ -3596,7 +3656,7 @@ impl HostHeap {
fn queue(&self, site: usize) -> QueueGuard<'_> {
use super::queue_site::{DUE, MADE_DUE, STALE};
use std::sync::atomic::Ordering::Relaxed;
- let queue = match self.textures.try_lock() {
+ let mut queue = match self.textures.try_lock() {
Ok(queue) => queue,
Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(),
Err(std::sync::TryLockError::WouldBlock) => {
@@ -3607,15 +3667,107 @@ impl HostHeap {
}
};
super::QUEUE_LOCK[0][site].fetch_add(1, Relaxed);
+ // What was left for the holder comes before anything this one
+ // asks or changes.
+ self.make_posted(&mut queue);
let held = matches!(site, DUE | MADE_DUE | STALE).then(|| (site, std::time::Instant::now()));
- QueueGuard { queue, held }
+ QueueGuard { queue, held, host: self }
+ }
+
+ /// Whether `ops` can be left for the queue's lock's holder
+ /// (`VICTORY_QUEUE_POST`, [`HostHeap::post`]): every slot of theirs
+ /// has its count of changes left.
+ fn posts(&self, ops: &[QueueOp]) -> bool {
+ queue_post() && ops.iter().all(|op| (op.index() as usize) < self.posted.len())
+ }
+
+ /// Makes `ops` (as [`QueueBatch`] does, the slot's state checked when
+ /// made) without waiting for the queue's lock: they join the changes
+ /// left for its holder, then the lock is tried; taken, they are made
+ /// now, else by whoever holds it before letting it go or by the next to
+ /// take it before it asks or changes anything. While a slot's change
+ /// waits, its marks are not read ([`HostHeap::queued`]) and a new note
+ /// of the slot takes the lock first ([`HostHeap::queue_texture_inner`]),
+ /// so what is asked of the queue is as if the change had been made at
+ /// once. The caller checked [`HostHeap::posts`].
+ fn post(&self, ops: &mut Vec<QueueOp>) {
+ use std::sync::atomic::Ordering::{Relaxed, Release};
+ if ops.is_empty() {
+ return;
+ }
+ let n = ops.len() as u64;
+ {
+ let mut posted = self.posted_ops.lock().unwrap_or_else(|e| e.into_inner());
+ for op in ops.iter() {
+ self.posted[op.index() as usize].fetch_add(1, Relaxed);
+ }
+ posted.append(ops);
+ self.posted_len.store(posted.len(), Release);
+ }
+ super::QUEUE_POSTED[0].fetch_add(n, Relaxed);
+ let queue = match self.textures.try_lock() {
+ Ok(queue) => queue,
+ Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(),
+ Err(std::sync::TryLockError::WouldBlock) => {
+ super::QUEUE_POSTED[1].fetch_add(n, Relaxed);
+ return;
+ }
+ };
+ super::QUEUE_LOCK[0][super::queue_site::WRITE].fetch_add(1, Relaxed);
+ // Made as the guard is let go.
+ drop(QueueGuard { queue, held: None, host: self });
+ }
+
+ /// Makes the changes left for the queue's lock's holder, in the order
+ /// they were left ([`HostHeap::post`]); `textures` is the locked queue.
+ // (Test hook below: `race_hook`.)
+ fn make_posted(&self, textures: &mut TextureQueue) {
+ use std::sync::atomic::Ordering::{Acquire, Relaxed, Release};
+ if self.posted_len.load(Acquire) == 0 {
+ return;
+ }
+ // The count stays non-zero until the changes are in the queue: a reader
+ // that sees it zero (`texture_news`, `texture_slots_room`) skips the
+ // lock, and between the take and the apply it would read the marks
+ // without these changes and pass over a slot for a frame.
+ let ops = std::mem::take(&mut *self.posted_ops.lock().unwrap_or_else(|e| e.into_inner()));
+ #[cfg(test)]
+ race_hook::window();
+ QueueBatch::apply_ops(&ops, textures, &self.slot_state);
+ {
+ let posted = self.posted_ops.lock().unwrap_or_else(|e| e.into_inner());
+ self.posted_len.store(posted.len(), Release);
+ }
+ // Only once they are made may their slots' marks be read again.
+ for op in &ops {
+ if let Some(n) = self.posted.get(op.index() as usize) {
+ n.fetch_sub(1, Release);
+ }
+ }
+ super::QUEUE_POSTED[2].fetch_add(ops.len() as u64, Relaxed);
+ // The buffer back for the next changes, if none came meanwhile.
+ let mut ops = ops;
+ ops.clear();
+ let mut posted = self.posted_ops.lock().unwrap_or_else(|e| e.into_inner());
+ if posted.is_empty() && posted.capacity() < ops.capacity() {
+ std::mem::swap(&mut *posted, &mut ops);
+ }
+ }
+
+ /// Whether changes of title slot `index` wait for the queue's lock's
+ /// holder ([`HostHeap::post`]).
+ fn slot_posted(&self, index: u32) -> bool {
+ self.posted
+ .get(index as usize)
+ .is_some_and(|n| n.load(std::sync::atomic::Ordering::Acquire) != 0)
}
/// Whether the queue holds title slot `index`, by its marks
/// ([`QueueMarks`]), without its lock; `None`: ask the queue (the marks
- /// are not used, or do not reach the slot).
+ /// are not used, or do not reach the slot, or a change of the slot
+ /// waits for the lock's holder, [`HostHeap::post`]).
fn queued(&self, index: u32) -> Option<bool> {
- if !queue_marks() {
+ if !queue_marks() || self.slot_posted(index) {
return None;
}
self.marks.get(index).map(|write| write != 0)
@@ -3706,7 +3858,8 @@ impl HostHeap {
/// The write of the entry the queue holds for title slot `index`, by its
/// marks (0: none; [`QueueMarks`]); `None`: not known so (ask the queue).
pub(crate) fn texture_slot_write(&self, index: u32) -> Option<u64> {
- if !queue_marks() {
+ // (Nor while a change of it waits for the lock's holder.)
+ if !queue_marks() || self.slot_posted(index) {
return None;
}
self.marks.get(index)
@@ -3829,6 +3982,11 @@ impl HostHeap {
/// A number that changes when a slot is written or made due anew, and
/// whether memory was noted since this heap's pass last took the notes.
pub(crate) fn texture_news(&self) -> (u64, bool) {
+ // Changes left for the lock's holder are made first: the marks then
+ // count them ([`HostHeap::post`]).
+ if self.posted_len.load(std::sync::atomic::Ordering::Acquire) != 0 {
+ drop(self.queue(super::queue_site::OTHER));
+ }
let writes = if queue_marks() {
self.marks.writes()
} else {
@@ -3906,7 +4064,7 @@ impl HostHeap {
/// See [`TextureQueue::room`].
pub(crate) fn texture_slots_room(&self, frame: u64) -> usize {
- if queue_marks() && !self.marks.has_held() {
+ if queue_marks() && !self.marks.has_held() && self.posted_len.load(std::sync::atomic::Ordering::Acquire) == 0 {
return 0;
}
self.queue(super::queue_site::MADE_DUE).room(frame)
@@ -4872,6 +5030,12 @@ impl HostHeap {
let Some(atom) = self.slot_state.get(index as usize) else {
return u32::from(keeps);
};
+ // A change of the slot left for the queue's lock's holder is made
+ // first, as of the state it was noted in ([`HostHeap::post`]).
+ // (Never called with the queue's lock held.)
+ if self.slot_posted(index) {
+ drop(self.queue(super::queue_site::WRITE));
+ }
let mut prev = atom.load(std::sync::atomic::Ordering::Relaxed);
loop {
let next = (prev.wrapping_add(2) & !1) | u32::from(keeps);
@@ -4907,6 +5071,11 @@ impl HostHeap {
{
batch.flush(self);
}
+ // Likewise for a change of it left for the queue's lock's holder
+ // ([`HostHeap::post`]): made before this one is decided.
+ if self.slot_posted(index) {
+ drop(self.queue(super::queue_site::WRITE));
+ }
let stamp = if tabled_out() { self.tabled_stamp(index) } else { 0 };
let now = (frame as u32).wrapping_add(1) & !TABLED_READ;
// A table's slot lately: the draw that reads it uploads its
@@ -4962,6 +5131,31 @@ impl HostHeap {
}
None => {}
}
+ } else if self.posts(&[QueueOp::RemoveIf { index, state, write: 0, frame }]) {
+ // Not waiting for the queue's lock: as a batch of one, left for
+ // its holder when it is held ([`HostHeap::post`]).
+ let op = if keeps {
+ let due = if lately && !seen {
+ TABLED_WRITES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ frame + TABLED_GRACE
+ } else {
+ 0
+ };
+ Some(QueueOp::Write { index, state, frame, due, seen })
+ } else {
+ match self.texture_slot_write(index) {
+ Some(0) => {
+ not_taken(super::queue_site::WRITE);
+ return;
+ }
+ Some(write) => Some(QueueOp::RemoveIf { index, state, write, frame }),
+ None => None,
+ }
+ };
+ if let Some(op) = op {
+ self.post(&mut vec![op]);
+ return;
+ }
}
let mut textures = self.queue(super::queue_site::WRITE);
if keeps {
@@ -10391,9 +10585,12 @@ void main() {
// Full batched vs unbatched parity through `HostHeap::queue_texture_inner`
// across > `QueueBatch::LIMIT` ops including same-slot transitions.
- let (Some(a), Some(b)) = (HostHeap::new(false, 128), HostHeap::new(false, 128)) else {
+ let (Some(a), Some(mut b)) = (HostHeap::new(false, 128), HostHeap::new(false, 128)) else {
return; // no host GPU
};
+ // `b` takes the queue's lock for each note, as before
+ // `VICTORY_QUEUE_POST` (no slot can be posted).
+ b.posted = Box::new([]);
let mut heap_batch = QueueBatch::default();
for i in 0..100u32 {
let slot = i % 80;
@@ -10430,6 +10627,124 @@ void main() {
}
}
+ /// `VICTORY_QUEUE_POST`: notes made while the queue's lock is held are
+ /// left for its holder, the slot then reads as unknown by its marks, and
+ /// once anything takes the lock the queue is what notes that waited for
+ /// the lock each would have made it (same order, writes and census).
+ #[test]
+ fn queue_posts_left_while_held_match_notes_that_wait() {
+ if !queue_post() {
+ return;
+ }
+ let (Some(a), Some(mut b)) = (HostHeap::new(false, 256), HostHeap::new(false, 256)) else {
+ return; // no host GPU
+ };
+ b.posted = Box::new([]);
+ let plan = |i: u32| (i % 97, !i.is_multiple_of(5), i.is_multiple_of(7), 50 + u64::from(i / 40));
+ for round in 0..4u32 {
+ // Each slot once a round while the lock is held elsewhere (a new
+ // note of a posted slot takes the lock first, which would wait
+ // for this very thread here).
+ let held = a.textures.lock().unwrap();
+ for i in round * 97..round * 97 + 97 {
+ let (slot, texture, seen, frame) = plan(i);
+ a.queue_texture_inner(slot, texture, seen, frame, None);
+ b.queue_texture_inner(slot, texture, seen, frame, None);
+ }
+ let posted = (0..97).filter(|&s| a.slot_posted(s)).count();
+ assert!(posted > 0, "nothing was left for the holder in round {round}");
+ for slot in (0..97).filter(|&s| a.slot_posted(s)) {
+ assert_eq!(a.queued(slot), None, "a posted slot's marks are read");
+ }
+ drop(held);
+ // A batch's ops posted while the lock is free are made at once.
+ let mut batch = QueueBatch::default();
+ for i in 0..20u32 {
+ let (slot, texture, seen, frame) = plan(i * 13 + round);
+ let slot = 100 + slot % 100;
+ a.queue_texture_inner(slot, texture, seen, frame, Some(&mut batch));
+ b.queue_texture_inner(slot, texture, seen, frame, None);
+ }
+ batch.flush(&a);
+ for at in [50, 52, 60, u64::MAX] {
+ assert_eq!(a.texture_slots_due_known(at, 300), b.texture_slots_due_known(at, 300), "round {round}, frame {at}");
+ }
+ assert!((0..256).all(|s| !a.slot_posted(s)));
+ assert_eq!(a.texture_news().0, b.texture_news().0);
+ for slot in 0..256u32 {
+ assert_eq!(a.texture_slot_write(slot), b.texture_slot_write(slot), "slot {slot}");
+ }
+ }
+ }
+
+ /// `VICTORY_QUEUE_POST`: notes from many threads, each its own slots,
+ /// while another thread takes the lock over and over, leave the queue
+ /// holding each slot as the same notes made one at a time would.
+ #[test]
+ fn queue_posts_from_threads_match_notes_one_at_a_time() {
+ if !queue_post() {
+ return;
+ }
+ let (Some(a), Some(mut b)) = (HostHeap::new(false, 4096), HostHeap::new(false, 4096)) else {
+ return; // no host GPU
+ };
+ b.posted = Box::new([]);
+ const THREADS: u32 = 6;
+ let plan = |t: u32, i: u32| {
+ let slot = t * 600 + (i * 7) % 600;
+ (slot, !(i + t).is_multiple_of(3), i.is_multiple_of(11), 10 + u64::from(i / 100))
+ };
+ let stop = std::sync::atomic::AtomicBool::new(false);
+ std::thread::scope(|s| {
+ let holder = s.spawn(|| {
+ let mut takes = 0u64;
+ while !stop.load(std::sync::atomic::Ordering::Relaxed) {
+ let q = a.queue(super::super::queue_site::DUE);
+ std::hint::black_box(q.census(12));
+ drop(q);
+ takes += 1;
+ }
+ takes
+ });
+ let notes: Vec<_> = (0..THREADS)
+ .map(|t| {
+ let a = &a;
+ s.spawn(move || {
+ for i in 0..3000u32 {
+ let (slot, texture, seen, frame) = plan(t, i);
+ if i % 4 == 0 {
+ let mut batch = QueueBatch::default();
+ a.queue_texture_inner(slot, texture, seen, frame, Some(&mut batch));
+ batch.flush(a);
+ } else {
+ a.queue_texture_inner(slot, texture, seen, frame, None);
+ }
+ }
+ })
+ })
+ .collect();
+ for n in notes {
+ n.join().unwrap();
+ }
+ stop.store(true, std::sync::atomic::Ordering::Relaxed);
+ assert!(holder.join().unwrap() > 0);
+ });
+ for t in 0..THREADS {
+ for i in 0..3000u32 {
+ let (slot, texture, seen, frame) = plan(t, i);
+ b.queue_texture_inner(slot, texture, seen, frame, None);
+ }
+ }
+ // Anything left is made by the next take.
+ drop(a.queue(super::super::queue_site::OTHER));
+ assert!((0..4096).all(|s| !a.slot_posted(s)));
+ for slot in 0..THREADS * 600 {
+ assert_eq!(a.queued(slot), b.queued(slot), "slot {slot}");
+ let due = |h: &HostHeap| h.queue(super::super::queue_site::OTHER).entry(slot).map(|e| e.due);
+ assert_eq!(due(&a), due(&b), "slot {slot}");
+ }
+ }
+
/// `VICTORY_DUE_INDEX=1` (`DueBuckets`) must match the default flat
/// `TextureQueue` across randomized mixed operations, including `written`,
/// `remove`, `done`, `later`, `hold`, `room`, `partly`, `recheck`
@@ -12088,3 +12403,66 @@ thread_local! {
/// Whether this thread is in [`HostHeap::mirror_for_pass`].
static FOR_PASS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
+
+/// Test-only pause between taking the posted changes and making them
+/// ([`HostHeap::make_posted`]), so a test can read in that window.
+#[cfg(test)]
+pub(super) mod race_hook {
+ use std::sync::atomic::{AtomicU8, Ordering::SeqCst};
+ /// 0 off, 1 armed, 2 paused in the window, 3 go on.
+ pub(super) static STATE: AtomicU8 = AtomicU8::new(0);
+ pub(super) fn window() {
+ if STATE.compare_exchange(1, 2, SeqCst, SeqCst).is_ok() {
+ while STATE.load(SeqCst) != 3 {
+ std::thread::sleep(std::time::Duration::from_millis(1));
+ }
+ STATE.store(0, SeqCst);
+ }
+ }
+}
+
+#[cfg(test)]
+mod posted_race_tests {
+ use super::*;
+ use std::sync::atomic::Ordering::SeqCst;
+
+ /// A reader of `texture_news` while posted changes are being made must
+ /// see them (it waits for the lock), never the marks from before them:
+ /// otherwise the texture pass sees no news and passes over a slot for a frame.
+ #[test]
+ fn news_read_while_posted_changes_are_made_includes_them() {
+ if !queue_post() || !queue_marks() {
+ return;
+ }
+ let Some(a) = HostHeap::new(false, 64) else {
+ return; // no host GPU
+ };
+ // Post a change: the lock is held, so the note is left for the holder.
+ let before = {
+ let held = a.textures.lock().unwrap();
+ let before = a.marks.writes();
+ a.queue_texture_inner(5, true, false, 50, None);
+ assert!(a.slot_posted(5), "the note was not posted");
+ drop(held);
+ before
+ };
+ let a = &a;
+ race_hook::STATE.store(1, SeqCst);
+ std::thread::scope(|s| {
+ // The next taker of the lock makes the posted changes, and pauses in the window.
+ let maker = s.spawn(move || drop(a.queue(super::super::queue_site::OTHER)));
+ while race_hook::STATE.load(SeqCst) != 2 {
+ std::thread::sleep(std::time::Duration::from_millis(1));
+ }
+ let (tx, rx) = std::sync::mpsc::channel();
+ let reader = s.spawn(move || tx.send(a.texture_news().0).unwrap());
+ // With the window closed the reader waits for the lock; let it try for a while.
+ let early = rx.recv_timeout(std::time::Duration::from_millis(200)).ok();
+ race_hook::STATE.store(3, SeqCst);
+ maker.join().unwrap();
+ let news = early.unwrap_or_else(|| rx.recv().unwrap());
+ reader.join().unwrap();
+ assert!(news > before, "texture_news read in the window missed the posted change (writes {news}, before {before})");
+ });
+ }
+}
diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs
index 9ad49c4..e57f092 100644
--- a/crates/victory-gpu/src/draw.rs
+++ b/crates/victory-gpu/src/draw.rs
@@ -668,6 +668,11 @@ pub(crate) struct State {
/// report of a removed device, `crate::host::indirects`).
#[cfg(feature = "diagnostics")]
user: Vec<u32>,
+ /// Which words of `user` are descriptor tables' byte offsets into the
+ /// view heap (bit `i`: word `i`), for that report to name their slots
+ /// and not take a root constant for one.
+ #[cfg(feature = "diagnostics")]
+ user_tables: u16,
/// The tables the last bind made afresh for a program the stand-in for
/// the indirect light follows (`crate::ambient`): root parameter, bytes
/// into the view heap.
@@ -1654,6 +1659,43 @@ pub(crate) fn take_table_slot_drops() -> u64 {
TABLE_SLOT_DROPS.swap(0, Ordering::Relaxed)
}
+/// [`DROPPED`] by why, since the last look ([`take_drops_by`]): no host
+/// pipeline, a stage of the ray-tracing structure builder (off: on purpose),
+/// a pipeline there but its bindings not made (or a mesh dispatch the host
+/// refused). The frame line's "dropped without a host pipeline" counts all
+/// three.
+static DROPS_BY: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
+const DROP_NO_PIPELINE: usize = 0;
+const DROP_BUILDER: usize = 1;
+const DROP_UNBOUND: usize = 2;
+
+/// Draws and dispatches dropped for want of a host pipeline (a shader not
+/// converted), since the start: what the stats panel's note counts. The
+/// ray-tracing structure builder's stages, left out on purpose, were most of
+/// [`DROPPED`] (586,859 of 602,293 in a run in the open world), and the note
+/// read them as shaders that cannot be converted.
+static NO_PIPELINE_ALL: AtomicU64 = AtomicU64::new(0);
+
+/// [`NO_PIPELINE_ALL`].
+pub(crate) fn no_pipeline_all() -> u64 {
+ NO_PIPELINE_ALL.load(Ordering::Relaxed)
+}
+
+/// [`DROPS_BY`], taken.
+pub(crate) fn take_drops_by() -> [u64; 3] {
+ DROPS_BY.each_ref().map(|n| n.swap(0, Ordering::Relaxed))
+}
+
+/// A draw or dispatch of pipeline `pipeline` was dropped by `prepare` or
+/// `bind`: for want of its host pipeline, or with it there.
+fn dropped_why(pipeline: usize) {
+ let why = if crate::pipeline::host_pipeline(pipeline as This).is_none() { DROP_NO_PIPELINE } else { DROP_UNBOUND };
+ DROPS_BY[why].fetch_add(1, Ordering::Relaxed);
+ if why == DROP_NO_PIPELINE {
+ NO_PIPELINE_ALL.fetch_add(1, Ordering::Relaxed);
+ }
+}
+
/// Marks the last traced draw as not run on the host.
#[cfg(feature = "diagnostics")]
fn dropped(pipeline: usize) {
@@ -2064,7 +2106,10 @@ impl State {
self.window = None;
self.batch = None;
#[cfg(feature = "diagnostics")]
- self.user.clear();
+ {
+ self.user.clear();
+ self.user_tables = 0;
+ }
self.ambient_tables.clear();
self.host_pipeline = 0;
self.host_roots = [0; 2];
@@ -2511,6 +2556,13 @@ impl State {
if kind == victory_shader::emit::USER_DISPATCH_THREADS_X {
return 0;
}
+ if kind == victory_shader::emit::USER_TITLE_VIEWS {
+ let host = match self.heaps[0] {
+ 0 => None,
+ h => Some(crate::descriptor::heap(h as This)).filter(|h| !h.samplers()).and_then(|h| h.host()),
+ };
+ return title_views_word(host.map(|h| h.count()), crate::toggled!("VICTORY_TITLE_VIEWS"));
+ }
if kind == USER_ROOT_ADDRESS || kind == USER_ROOT_ADDRESS + 1 {
return match self.roots_ref(compute).get(usize::from(slot)) {
Some(&Root::View(address)) if kind == USER_ROOT_ADDRESS => address as u32,
@@ -3018,6 +3070,9 @@ impl State {
{
self.user.clear();
self.user.extend_from_slice(values);
+ self.user_tables = crate::host::indirects::table_words(
+ t.host.user_data.iter().filter(|u| u.root == RootType::Table).map(|u| u.index),
+ );
}
// SAFETY: an open list; `values` covers the parameter.
unsafe {
@@ -5057,6 +5112,7 @@ impl State {
// The ray-tracing structure builder's stages run all or none.
if crate::pipeline::is_builder(self.pipeline as This) && !crate::pipeline::builder_runs() {
DROPPED.fetch_add(1, Ordering::Relaxed);
+ DROPS_BY[DROP_BUILDER].fetch_add(1, Ordering::Relaxed);
#[cfg(feature = "diagnostics")]
{
crate::pipeline::note_why("a stage of the ray-tracing structure builder, which is off".to_owned());
@@ -5070,6 +5126,8 @@ impl State {
"a dispatch without a host pipeline dropped"
);
DROPPED.fetch_add(1, Ordering::Relaxed);
+ DROPS_BY[DROP_NO_PIPELINE].fetch_add(1, Ordering::Relaxed);
+ NO_PIPELINE_ALL.fetch_add(1, Ordering::Relaxed);
#[cfg(feature = "diagnostics")]
{
crate::pipeline::note_drop(self.pipeline as This);
@@ -5086,6 +5144,7 @@ impl State {
}
if !self.bind(list, p, true) {
DROPPED.fetch_add(1, Ordering::Relaxed);
+ DROPS_BY[DROP_UNBOUND].fetch_add(1, Ordering::Relaxed);
// A stage of the structure builder that cannot be bound is a
// dropped stage: the others stop too.
if crate::pipeline::is_builder(self.pipeline as This) {
@@ -5193,7 +5252,9 @@ impl State {
// On again by default (2026-11-27): those dark patches were water tiles the tile
// list had dropped (`VICTORY_LOOPS_WAVE`), not this; without it glass in a dark room
// mirrors the bright sky (run fix2, spectacles 75 s into the opening). `=0`: off.
- let alpha_too = !std::env::var("VICTORY_AMBIENT_SPECULAR_ALPHA").is_ok_and(|v| v.trim() == "0");
+ static ALPHA_TOO: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+ let alpha_too =
+ *ALPHA_TOO.get_or_init(|| !std::env::var("VICTORY_AMBIENT_SPECULAR_ALPHA").is_ok_and(|v| v.trim() == "0"));
if role == Role::Miss
&& !(layer == crate::ambient::MISS_OPAQUE || (alpha_too && layer == crate::ambient::MISS_ALPHA))
{
@@ -5817,7 +5878,7 @@ impl State {
self.mesh_scissor(list, true);
#[cfg(feature = "diagnostics")]
if let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) {
- list.ran_indirect(p.pso.as_raw() as usize, &p.name, crate::host::indirects::DIRECT, _total, &self.user);
+ list.ran_indirect(p.pso.as_raw() as usize, &p.name, crate::host::indirects::DIRECT, _total, &self.user, self.user_tables);
}
// SAFETY: an open list with the pipeline bound and a grid within host limits.
unsafe { l6.DispatchMesh(x, y, z) };
@@ -5835,6 +5896,7 @@ impl State {
if !ran {
list.taint_queries();
DROPPED.fetch_add(1, Ordering::Relaxed);
+ dropped_why(self.pipeline);
#[cfg(feature = "diagnostics")]
dropped(self.pipeline);
}
@@ -6532,6 +6594,7 @@ impl State {
if !ran {
list.taint_queries();
DROPPED.fetch_add(1, Ordering::Relaxed);
+ dropped_why(self.pipeline);
#[cfg(feature = "diagnostics")]
dropped(self.pipeline);
}
@@ -6712,6 +6775,7 @@ impl State {
if !ran {
list.taint_queries();
DROPPED.fetch_add(1, Ordering::Relaxed);
+ dropped_why(self.pipeline);
#[cfg(feature = "diagnostics")]
dropped(self.pipeline);
}
@@ -7241,7 +7305,7 @@ impl State {
}
}
#[cfg(feature = "diagnostics")]
- list.ran_indirect(p.pso.as_raw() as usize, &p.name, kind, max, &self.user);
+ list.ran_indirect(p.pso.as_raw() as usize, &p.name, kind, max, &self.user, self.user_tables);
if kind == DISPATCH {
if crate::barstat::on() {
let access = self.barstat_access(p, true).map(|mut a| {
@@ -7315,6 +7379,29 @@ fn dispatch_groups(threads: [u32; 3], size: [u32; 3]) -> [u32; 3] {
std::array::from_fn(|i| threads[i].div_ceil(size[i]))
}
+/// The host's word for `victory_shader::emit::USER_TITLE_VIEWS`: the title
+/// slots the bound view heap has host slots for (`title_slots`), past which
+/// a view the shader picks by an index it computes reads the null slot.
+/// Without a title heap of ours bound (the host's fallback heap), or with
+/// `VICTORY_TITLE_VIEWS=0` (`on` false), `u32::MAX`: every index as before,
+/// up to the null slot.
+///
+/// The slots past the title's are the dynamic ones, the tables made afresh
+/// for draws. On a heap capped at 1,000,000 views (NVIDIA) the title has
+/// 606,783 slots of its 1,245,184 there (d7c2d8a7 gave the dynamic ones
+/// 393,216), and before this an index between them and the null slot read
+/// whatever another draw's table had there, a texture's view as a buffer's
+/// among them. From v2026.11.29.02 on the card hung in a program that picks
+/// buffers from the heap by indices it reads from memory (#3222's
+/// device-removed data: an indirect dispatch of 4fb416369fc50b6e, no page
+/// fault).
+fn title_views_word(title_slots: Option<u32>, on: bool) -> u32 {
+ match title_slots {
+ Some(slots) if on => slots,
+ _ => u32::MAX,
+ }
+}
+
/// Where a compute pipeline's user data has a word the host computes: the
/// root parameter and the dword in it.
fn compute_word(p: &HostPipeline, kind: u32) -> Option<(u32, u32)> {
@@ -8295,7 +8382,19 @@ fn staging_budget_per_frame(vram_budget: Option<u64>) -> u64 {
#[cfg(test)]
mod tests {
- use super::{SharedTables, staging_budget_per_frame};
+ use super::{SharedTables, staging_budget_per_frame, title_views_word};
+
+ /// The word that keeps picked view indices to the title's slots: the
+ /// bound heap's title slots on the host, or no bound at all without a
+ /// heap of ours or with the switch off.
+ #[test]
+ fn picked_views_are_kept_to_the_bound_heaps_title_slots() {
+ // The capped NVIDIA heap of the title's 1,245,184 views.
+ assert_eq!(title_views_word(Some(606_783), true), 606_783);
+ assert_eq!(title_views_word(Some(606_783), false), u32::MAX);
+ assert_eq!(title_views_word(None, true), u32::MAX);
+ assert_eq!(title_views_word(Some(0), true), 0);
+ }
#[test]
fn shared_tables_go_back_with_the_last_list() {
diff --git a/crates/victory-gpu/src/fence.rs b/crates/victory-gpu/src/fence.rs
index f8f9d39..8615a48 100644
--- a/crates/victory-gpu/src/fence.rs
+++ b/crates/victory-gpu/src/fence.rs
@@ -198,14 +198,19 @@ fn block_until(this: This, value: u64) -> HRESULT {
});
let fence = fence(this);
let reached = || fence.value.load(Ordering::Acquire) >= value;
- let settle = || {
- if crate::host::late() {
+ // (`crate::host::fence_narrow`: the thread that lands flights sets the
+ // value, so the wait settles nothing but at `FORCE_AFTER`; the time stood
+ // is counted as a blocking fence wait all the same.)
+ let narrow = crate::host::late() && crate::host::fence_narrow();
+ let mut counted = narrow.then(|| Stood(Instant::now()));
+ let settle = |always: bool| {
+ if crate::host::late() && (always || !narrow) {
crate::host::settle_for_fence();
}
};
// What the title gave its queues before goes to the card first.
crate::queue::before_sync();
- settle();
+ settle(false);
crate::queue::release_held(false);
let start = Instant::now();
let mut forced = false;
@@ -230,7 +235,10 @@ fn block_until(this: This, value: u64) -> HRESULT {
"blocking fence wait not met: what queues hold runs now, as at a present"
);
crate::queue::force_held();
- settle();
+ // (The settle counts its own wait: what stood before it is counted here.)
+ drop(counted.take());
+ settle(true);
+ counted = narrow.then(|| Stood(Instant::now()));
continue;
}
if waited >= told + Duration::from_secs(5) {
@@ -248,7 +256,7 @@ fn block_until(this: This, value: u64) -> HRESULT {
);
}
if !reached() {
- settle();
+ settle(false);
crate::queue::release_held(false);
}
}
@@ -261,6 +269,16 @@ fn block_until(_: This, value: u64) -> HRESULT {
tracing::warn!(value, "blocking fence wait without a host");
WAIT_FAILED
}
+
+/// Counts the time from `.0` to its drop as a blocking fence wait.
+#[cfg(windows)]
+struct Stood(std::time::Instant);
+#[cfg(windows)]
+impl Drop for Stood {
+ fn drop(&mut self) {
+ crate::host::fence_waited(self.0.elapsed().as_micros() as u64);
+ }
+}
/// Moves the fence to `value` and sets the events that waited for it.
pub(crate) fn set(this: This, value: u64) {
let fence = fence(this);
@@ -306,6 +324,14 @@ pub(crate) fn written(at: usize, bytes: usize) {
}
!reached
});
+ drop(waiters);
+ // As [`set`] does: a blocking wait (`block_until`) sees the value at once,
+ // not at its next 10 ms slice.
+ #[cfg(windows)]
+ // SAFETY: wakes threads waiting on the fence's value with WaitOnAddress.
+ unsafe {
+ windows_sys::Win32::System::Threading::WakeByAddressAll((&raw const fence.value).cast());
+ }
}
pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT {
let _called = crate::timeline::span("a fence set");
diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs
index 221797a..182ecfe 100644
--- a/crates/victory-gpu/src/host.rs
+++ b/crates/victory-gpu/src/host.rs
@@ -922,13 +922,91 @@ fn sweep() {
{
return;
}
+ // (A flush asked with F7/F8 is done here, on the submitting thread.)
+ if sweep_aside() && !crate::resource::flush_asked() && sweep_handed_off() {
+ return;
+ }
+ sweep_now(false, reclaimed_request);
+}
+
+/// The sweep on a thread of its own (`VICTORY_SWEEP_ASIDE=1`; off by
+/// default): the submitting thread only asks for it, and with flights in
+/// the air no settle is made for it ([`sweep_ahead`]'s reasons hold).
+///
+/// Why: run 20261129-141314 (open world, 8 GB card past its budget) spent
+/// 9-13 ms a frame of the submitting thread on "the heaps' records and what
+/// is swept", steady from line to line, with the sweep once a second (one
+/// "memory now" line a second): about 100 ms in one go at 9 frames a
+/// second. Of it the look for textures to let go alone was 35 ms a sweep
+/// ("looks for textures to let go, ... ms each"), and the slot eviction
+/// after it walks the same 34,000 textures and the heaps' slots.
+///
+/// Why it holds: every part takes its own locks and was already run beside
+/// the recording threads, which take copies out of the same tables; what it
+/// lets go is held by no list (a list being prepared holds what it names)
+/// and is dropped by [`retire`], which waits for the submissions running
+/// and [`bury_lag`] more. With `VICTORY_UPCOPY_CHECK=1` it stays inline.
+/// The slot eviction (`VICTORY_SLOT_EVICT=1`) is not done with it
+/// (`crate::resource::let_go_idle_aside`), and a flush (F7/F8) is done on
+/// the submitting thread.
+fn sweep_aside() -> bool {
+ static ON: OnceLock<bool> = OnceLock::new();
+ *ON.get_or_init(|| {
+ let on = crate::asked_for!("VICTORY_SWEEP_ASIDE") && !upcheck::on();
+ tracing::info!(
+ on,
+ slot_evict_skipped = on && crate::resource::slot_evict_on(),
+ "the once-a-second sweep on a thread of its own, not the submitting thread, without the slot eviction \
+ (VICTORY_SWEEP_ASIDE=1)"
+ );
+ on
+ })
+}
+
+/// [`sweep_aside`]: the sweep thread asked to sweep; false if it could not
+/// be started (the caller sweeps). One still sweeping is not asked again:
+/// the next is due a second later.
+fn sweep_handed_off() -> bool {
+ static ASKED: (std::sync::Mutex<bool>, std::sync::Condvar) = (std::sync::Mutex::new(false), std::sync::Condvar::new());
+ static STARTED: OnceLock<bool> = OnceLock::new();
+ let started = *STARTED.get_or_init(|| {
+ std::thread::Builder::new()
+ .name("victory-sweep".into())
+ .spawn(|| {
+ loop {
+ {
+ let mut asked = ASKED.0.lock().unwrap_or_else(|e| e.into_inner());
+ while !*asked {
+ asked = ASKED.1.wait(asked).unwrap_or_else(|e| e.into_inner());
+ }
+ *asked = false;
+ }
+ let _ = std::panic::catch_unwind(|| sweep_now(true, false));
+ }
+ })
+ .is_ok()
+ });
+ if started {
+ *ASKED.0.lock().unwrap_or_else(|e| e.into_inner()) = true;
+ ASKED.1.notify_one();
+ }
+ started
+}
+
+/// The sweep's work ([`sweep`]), timed: a sweep of 20 ms or more is said.
+/// `aside`: on the sweep's own thread ([`sweep_aside`]). One at a time: a
+/// flush's sweep on the submitting thread waits for one aside.
+fn sweep_now(aside: bool, reclaimed_request: bool) {
+ static ONE: Mutex<()> = Mutex::new(());
+ let _one = ONE.lock().unwrap_or_else(|e| e.into_inner());
+ let began = Instant::now();
#[cfg(feature = "diagnostics")]
crate::book::check();
crate::residency::refresh();
let pressured = crate::residency::pressured();
if pressured {
if idle_reclaim() {
- crate::list::trim_idle(now);
+ crate::list::trim_idle(now_ms());
}
trim_spare_uploads();
trim_spare_chunks();
@@ -945,7 +1023,18 @@ fn sweep() {
crate::shadow::let_go_idle();
crate::texture::let_go_idle();
if !reclaimed_request {
- crate::resource::let_go_idle();
+ if aside {
+ crate::resource::let_go_idle_aside();
+ } else {
+ crate::resource::let_go_idle();
+ }
+ }
+ let ms = began.elapsed().as_secs_f64() * 1e3;
+ if ms >= 20.0 {
+ tracing::info!(
+ "the sweep took {ms:.1} ms of {} (VICTORY_SWEEP_ASIDE=1: a thread of its own)",
+ if aside { "its own thread" } else { "the submitting thread" }
+ );
}
}
@@ -1053,6 +1142,48 @@ fn bury_pool() -> Option<&'static BuryPool> {
})
}
+/// Since the last frame-rate line: objects [`bury`] handed to the thread
+/// that drops them, and that thread's microseconds dropping them.
+static BURIED_ASIDE: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
+
+/// Whether what [`bury`] drops is dropped by a thread of its own, not by
+/// the thread that lands submissions or submits (`VICTORY_BURY_ASIDE=0`:
+/// by them, as before). Some 20,000 objects a frame, each a release.
+fn bury_aside_on() -> bool {
+ static ON: OnceLock<bool> = OnceLock::new();
+ *ON.get_or_init(|| std::env::var_os("VICTORY_BURY_ASIDE").is_none_or(|v| v != "0"))
+}
+
+/// Hands `done` to the thread that drops what was retired
+/// ([`bury_aside_on`]); gives it back when it is the caller's to drop.
+fn bury_aside(done: Vec<(u64, Retired)>) -> Option<Vec<(u64, Retired)>> {
+ type Grave = std::sync::mpsc::Sender<Vec<(u64, Retired)>>;
+ static GRAVE: OnceLock<Option<Grave>> = OnceLock::new();
+ if done.is_empty() || !bury_aside_on() {
+ return Some(done);
+ }
+ let grave = GRAVE.get_or_init(|| {
+ let (send, take) = std::sync::mpsc::channel::<Vec<(u64, Retired)>>();
+ std::thread::Builder::new()
+ .name("victory-burial".into())
+ .spawn(move || {
+ for done in take {
+ let started = Instant::now();
+ let n = done.len() as u64;
+ drop(done);
+ BURIED_ASIDE[0].fetch_add(n, Ordering::Relaxed);
+ BURIED_ASIDE[1].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
+ }
+ })
+ .ok()
+ .map(|_| send)
+ });
+ match grave {
+ Some(send) => send.send(done).err().map(|e| e.0),
+ None => Some(done),
+ }
+}
+
/// Drops what waited for submissions up to `finished` ([`bury_lag`]). The
/// numbers come in order within each thread's shard.
fn bury(finished: u64) {
@@ -1089,7 +1220,9 @@ fn bury(finished: u64) {
}
let count = done.len();
let drained = timing.map(|_| Instant::now());
- drop(done);
+ if let Some(done) = bury_aside(done) {
+ drop(done);
+ }
if let (Some(start), Some(lock_time), Some(drained)) = (timing, lock_time, drained) {
let total = start.elapsed();
if total >= Duration::from_millis(5) {
@@ -3715,6 +3848,18 @@ pub(crate) static SPARE_TRIMMED: std::sync::atomic::AtomicU64 = std::sync::atomi
/// then shared buffers, by size class.
static UPLOAD_SPARE: [Mutex<Spare<Chunk>>; 2] = [const { Mutex::new(Spare::new()) }; 2];
+/// The bytes [`UPLOAD_SPARE`] keeps, upload then shared, for the process
+/// memory line.
+pub(crate) fn upload_spare_bytes() -> [u64; 2] {
+ UPLOAD_SPARE.each_ref().map(|spare| spare.lock().unwrap_or_else(|e| e.into_inner()).bytes)
+}
+
+/// The bytes the submissions' send memories that have run keep
+/// ([`send::give_back`]), for the process memory line.
+pub(crate) fn send_spare_bytes() -> u64 {
+ send::spare_bytes()
+}
+
/// The most bytes [`UPLOAD_SPARE`] keeps of each kind
/// (`VICTORY_UPLOAD_POOL_MB`, 1024, 128 on a small host; 0: no pool, a
/// buffer per copy as before). Every copy a list recorded made a buffer of
@@ -6584,6 +6729,31 @@ pub(crate) fn settle_for_fence() {
settle_now(WHY_FENCE);
}
+/// Whether a thread of the title's blocked on a fence waits for that value
+/// alone (`VICTORY_FENCE_NARROW`, on with the relay; `0`: it settles every
+/// flight, as before). With the relay, the thread that lands flights sets
+/// each fence as the flight that signals it lands (`late_signal`), so the
+/// blocked thread has nothing to do but wait.
+///
+/// Settling took the submission lock and waited for every flight in the
+/// air, so the submitting thread stood behind it with the card idle: in the
+/// open world (RTX 4060, 2026-11-29) 29.8 ms a frame waiting for the
+/// submission lock, and 22.2 ms of the card idle behind us.
+pub(crate) fn fence_narrow() -> bool {
+ static ON: OnceLock<bool> = OnceLock::new();
+ *ON.get_or_init(|| {
+ let on = relay() && std::env::var_os("VICTORY_FENCE_NARROW").is_none_or(|v| v != "0");
+ tracing::info!(on, "blocking fence waits: the value alone, without settling every flight (VICTORY_FENCE_NARROW)");
+ on
+ })
+}
+
+/// Microseconds a blocking fence wait stood without settling
+/// ([`fence_narrow`]): counted as a blocking fence wait in the waits' lines.
+pub(crate) fn fence_waited(us: u64) {
+ LATE_WAITED[WHY_FENCE].fetch_add(us, Ordering::Relaxed);
+}
+
/// Resets the host lists of settled flights and keeps them for reuse, as
/// a queue does for the lists it ran (`crate::list::recycle`).
fn land() {
@@ -7297,6 +7467,14 @@ fn late_line(frames: f64) {
r[3] / 1000.0,
r[4] / 1000.0,
);
+ let [buried, buried_us] = BURIED_ASIDE.each_ref().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames);
+ if buried > 0.0 {
+ tracing::info!(
+ "retired objects dropped per frame by a thread of their own (VICTORY_BURY_ASIDE): {buried:.0} in {:.2} ms, \
+ off the landing and submitting threads (the landing line's \"the rest\")",
+ buried_us / 1000.0
+ );
+ }
let idle = RELAY_IDLE_WAITS.load(Ordering::Relaxed);
if idle > 0 {
tracing::info!("waits for landings given up with nothing left to land: {idle} since the start");
@@ -7311,6 +7489,8 @@ fn late_line(frames: f64) {
c[2],
);
}
+ #[cfg(windows)]
+ crate::resource::maybe_trim_working_set();
if send::own() {
let private_mib = crate::shadow::PRIVATE_CPU_BYTES.load(Ordering::Relaxed) >> 20;
if private_mib != 0 {
@@ -8281,7 +8461,12 @@ impl Host {
list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64);
}
} else {
- let upload = self.snapshot_private_ranges(list, &shadow.buffer, shadow.card_data(), ranges);
+ let data = shadow.card_data();
+ let upload = if data.is_null() {
+ self.snapshot_title_ranges(list, &shadow.buffer, shadow.span().0 as usize, ranges)
+ } else {
+ self.snapshot_private_ranges(list, &shadow.buffer, data, ranges)
+ };
fallback_uploads.push(upload);
}
}
@@ -8696,6 +8881,30 @@ impl Host {
upload
}
+ /// Fallback for lazy read-only card copies when the packed upload cannot
+ /// be allocated: reads dirty ranges directly from title memory via
+ /// [`copy_mapped`] into a temporary upload buffer.
+ ///
+ /// # Safety
+ /// Same as [`Host::snapshot_private_ranges`].
+ unsafe fn snapshot_title_ranges(&self, list: &ID3D12GraphicsCommandList, destination: &ID3D12Resource,
+ title_start: usize, ranges: &[(usize, usize)]) -> ID3D12Resource {
+ let bytes = ranges.iter().map(|&(a, b)| b - a).sum::<usize>();
+ let (upload, mapped) = self.upload_buffer(bytes as u64).unwrap_or_else(|| {
+ fail(format_args!("could not snapshot {bytes} dirty bytes from title memory"))
+ });
+ let mut offset = 0;
+ for &(a, b) in ranges {
+ // SAFETY: `mapped` holds `bytes`; `copy_mapped` handles unmapped title pages.
+ unsafe {
+ copy_mapped(mapped.add(offset), (title_start + a) as *const u8, b - a, false);
+ list.CopyBufferRegion(destination, a as u64, &upload, offset as u64, (b - a) as u64);
+ }
+ offset += b - a;
+ }
+ upload
+ }
+
/// With [`relay`]: whether the compare's result area is half taken by
/// plans in the air. It starts from the beginning only when no plan is
/// out, so the caller lets the flights land first.
@@ -10251,7 +10460,7 @@ impl Host {
SWEPT.store(now_ms(), Ordering::Relaxed);
} else if late_free_present()
&& now_ms() > SWEPT.load(Ordering::Relaxed) + self.sweep_every_ms()
- && sweep_ahead()
+ && (sweep_ahead() || sweep_aside())
&& !upcheck::on()
{
sweep();
@@ -12123,9 +12332,9 @@ impl HostList {
/// Notes an indirect execution, while device-removed data is kept
/// ([`indirects`]).
#[cfg(feature = "diagnostics")]
- pub(crate) fn ran_indirect(&self, pipeline: usize, name: &str, kind: u32, count: u32, user: &[u32]) {
+ pub(crate) fn ran_indirect(&self, pipeline: usize, name: &str, kind: u32, count: u32, user: &[u32], tables: u16) {
if dred_on() || dred_light() {
- self.indirects.lock().unwrap_or_else(|e| e.into_inner()).note(pipeline, name, kind, count, user);
+ self.indirects.lock().unwrap_or_else(|e| e.into_inner()).note(pipeline, name, kind, count, user, tables);
}
}
@@ -13321,6 +13530,13 @@ fn submit_split_line(frames: f64) {
sent[5],
);
}
+ let [flushes, copies] = [0, 1].map(|i| INLINE[i].swap(0, Ordering::Relaxed) as f64 / frames);
+ if refresh_inline() > 0 {
+ tracing::info!(
+ "refreshes done on the submitting thread per frame (VICTORY_REFRESH_INLINE={}): {flushes:.1} flushes, {copies:.0} copies, not spread over the kept threads",
+ refresh_inline()
+ );
+ }
let [first, again] = [0, 1].map(|i| HEAP_SYNC_FIRST[i].swap(0, Ordering::Relaxed) as f64 / frames);
if first + again > 0.0 {
tracing::info!(
@@ -13579,6 +13795,49 @@ fn front_sift() -> bool {
crate::toggled!("VICTORY_FRONT_SIFT")
}
+/// `VICTORY_REFRESH_INLINE=<n>` (0, the default: as before): a flush, or the
+/// refreshes in front of a submission, with at most `n` copies left once
+/// those known to copy nothing are sifted out (no texture due, and all of
+/// memory the kernel write-watches) is done on the submitting thread,
+/// without waking the kept threads for it.
+pub(crate) fn refresh_inline() -> usize {
+ static N: OnceLock<usize> = OnceLock::new();
+ *N.get_or_init(|| {
+ let n = std::env::var("VICTORY_REFRESH_INLINE").ok().and_then(|v| v.trim().parse::<usize>().ok()).unwrap_or(0).min(256);
+ if n > 0 {
+ tracing::info!(n, "refreshes of at most this many copies done on the submitting thread (VICTORY_REFRESH_INLINE)");
+ }
+ n
+ })
+}
+
+/// Since the last frame line, with [`refresh_inline`]: flushes done on the
+/// submitting thread, and their copies.
+static INLINE: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
+
+fn inline_refresh(copies: &[(std::sync::Arc<crate::shadow::Shadow>, usize, usize)]) -> bool {
+ let (n, most) = (copies.len(), refresh_inline());
+ if n == 0 || n > most || !copies.iter().all(|c| c.0.kernel_watched()) {
+ return false;
+ }
+ INLINE[0].fetch_add(1, Ordering::Relaxed);
+ INLINE[1].fetch_add(n as u64, Ordering::Relaxed);
+ true
+}
+
+fn inline_refresh_indexed(
+ dirty: &[(usize, usize, usize)],
+ spans: &[(std::sync::Arc<crate::shadow::Shadow>, usize, usize)],
+) -> bool {
+ let (n, most) = (dirty.len(), refresh_inline());
+ if n == 0 || n > most || !dirty.iter().all(|&(idx, _, _)| spans[idx].0.kernel_watched()) {
+ return false;
+ }
+ INLINE[0].fetch_add(1, Ordering::Relaxed);
+ INLINE[1].fetch_add(n as u64, Ordering::Relaxed);
+ true
+}
+
/// [`front_sift`]: filters `(span_idx, from, to)` entries in parallel using
/// 64-item scoped chunks and a pre-snapshotted `ahead` list (zero `Arc<Shadow>`
/// clones and zero journal locks per span), preserving order in place.
@@ -14186,26 +14445,32 @@ impl Batch {
if due.len() > 1 && !self.front_dirty.is_empty() && crate::asked_for!("VICTORY_LARGE_TEXTURE_FIRST") {
largest_first(due, due_bytes);
}
- FLUSHES[3].fetch_add(self.front_dirty.len() as u64, Ordering::Relaxed);
- // (The textures one to a thread; the copies as `VICTORY_WIDE_CHUNK` says.)
- let chunk = crate::shadow::wide_chunk();
- let dirty = &self.front_dirty;
- let spans = &self.spans;
- let span_chunks = dirty.len().div_ceil(chunk);
- crate::shadow::wide_each_scoped(due.len() + span_chunks, 1, &|lo, hi| {
- for job in lo..hi {
- // The textures first: they are the longer pieces (one per claim).
- let Some(ci) = job.checked_sub(due.len()) else {
- refresh_due(&due[job]);
- continue;
- };
- let start = ci * chunk;
- let end = (start + chunk).min(dirty.len());
- for &(idx, from, to) in &dirty[start..end] {
- Self::update(&spans[idx].0, from, to);
- }
+ if due.is_empty() && inline_refresh_indexed(&self.front_dirty, &self.spans) {
+ for &(idx, from, to) in &self.front_dirty {
+ Self::update(&self.spans[idx].0, from, to);
}
- });
+ } else {
+ FLUSHES[3].fetch_add(self.front_dirty.len() as u64, Ordering::Relaxed);
+ // (The textures one to a thread; the copies as `VICTORY_WIDE_CHUNK` says.)
+ let chunk = crate::shadow::wide_chunk();
+ let dirty = &self.front_dirty;
+ let spans = &self.spans;
+ let span_chunks = dirty.len().div_ceil(chunk);
+ crate::shadow::wide_each_scoped(due.len() + span_chunks, 1, &|lo, hi| {
+ for job in lo..hi {
+ // The textures first: they are the longer pieces (one per claim).
+ let Some(ci) = job.checked_sub(due.len()) else {
+ refresh_due(&due[job]);
+ continue;
+ };
+ let start = ci * chunk;
+ let end = (start + chunk).min(dirty.len());
+ for &(idx, from, to) in &dirty[start..end] {
+ Self::update(&spans[idx].0, from, to);
+ }
+ }
+ });
+ }
FRONT[2].fetch_add(lap.elapsed().as_nanos() as u64, Ordering::Relaxed);
if ahead {
crate::watch::ask_ahead_done();
@@ -14445,7 +14710,9 @@ impl Batch {
lap = std::time::Instant::now();
}
let check_noop = light && self.refreshes.len() > FEW && !sifted && !batch;
- if wide_refresh() && self.refreshes.len() >= 4 {
+ // (Thousands not sifted are sifted on the threads: never here.)
+ let here = light && (4..=FEW).contains(&self.refreshes.len()) && inline_refresh(&self.refreshes);
+ if wide_refresh() && self.refreshes.len() >= 4 && !here {
// Each copy on its own, several at a time: a copy's refresh
// writes that copy and reads title memory, nothing of another's.
// The time counted is the time it took, not the threads' sum.
@@ -16371,6 +16638,32 @@ impl Meter {
first-upload room decisions: {allow} allowed, {explicit} refused by an explicit byte limit, {no_memory} without memory info, \
{allowance_off} with the allowance off, {filled} at the texture-copy ceiling, {whole} at the whole-card budget"
);
+ {
+ let [none, builder, unbound] = crate::draw::take_drops_by();
+ tracing::info!(
+ "draws and dispatches dropped in the last 5 seconds, by why: {none} without a host pipeline, {builder} \
+ stages of the ray-tracing structure builder (off, on purpose), {unbound} with their pipeline but bindings \
+ not made (a table's slots, a root view, an index buffer)"
+ );
+ }
+ // What slot eviction has let go since the start, and its last look.
+ {
+ let e = crate::resource::SLOT_EVICT.each_ref().map(|n| n.load(Ordering::Relaxed));
+ let st = crate::resource::SLOT_STATE.each_ref().map(|n| n.load(Ordering::Relaxed));
+ tracing::info!(
+ "slot eviction since the start: {} let go ({} MB), {} slots back to waiting, {} made again ({} of them soon), {} given up for a draw; at its last look evicting {}, of {} idle-looking {} kept for a table and {} not to be taken (picked by index)",
+ e[0],
+ e[1] >> 20,
+ e[2],
+ e[3],
+ e[4],
+ e[6],
+ st[0],
+ st[3],
+ st[1],
+ st[2]
+ );
+ }
let [looks, mapped, same, staged, all, made, views] =
[0, 1, 2, 3, 4, 5, 6].map(|i| crate::draw::HEAP_TEXTURE_NANOS[i].swap(0, Ordering::Relaxed) / 1_000_000);
let rest = all.saturating_sub(looks + mapped + same + staged + made + views);
@@ -16471,6 +16764,8 @@ impl Meter {
// The queue's lock by place (`crate::descriptor::queue_site`).
let lock = crate::descriptor::QUEUE_LOCK.each_ref().map(|row| row.each_ref().map(|n| n.swap(0, Ordering::Relaxed)));
let [taken, waited, held, skipped] = lock;
+ let [posted, posted_held, posted_made] =
+ crate::descriptor::QUEUE_POSTED.each_ref().map(|n| n.swap(0, Ordering::Relaxed));
if taken.iter().sum::<u64>() + skipped.iter().sum::<u64>() > 0 {
let ms = |ns: u64| ns / 1_000_000;
tracing::info!(
@@ -16480,7 +16775,8 @@ impl Meter {
taking the slots due, {} ms making slots due, {} ms for stale views; not taken {} times, as nothing would \
have changed ({} noting a slot's record, {} by table reads, {} for stale views); since the start, {} slots \
taken out by a table read after the first of their frame (VICTORY_TABLED_REREAD=1), {} records of textures \
- the host writes left out of the queue (VICTORY_QUEUE_HOST_TEXTURES=0)",
+ the host writes left out of the queue (VICTORY_QUEUE_HOST_TEXTURES=0); changes noted without waiting \
+ (VICTORY_QUEUE_POST): {posted}, {posted_held} of them left for the lock's holder, {posted_made} made",
taken.iter().sum::<u64>(),
taken[0],
taken[1],
@@ -18276,11 +18572,11 @@ fn indirects_around(history: &[D3D12_AUTO_BREADCRUMB_OP], done: usize, all: &ind
shown += 1;
let direct = mesh(op);
let nth = if direct { indirects::before(history, at, mesh) } else { indirects::before(history, at, indirect) };
- let Some((what, words)) = all.nth(nth, direct) else {
+ let Some((what, words, tables)) = all.nth(nth, direct) else {
continue;
};
text.push_str(&format!("; command {at} ran {what}"));
- for (word, slot, what) in crate::descriptor::host::describe_slots(words) {
+ for (word, slot, what) in crate::descriptor::host::describe_slots(words, tables) {
text.push_str(&format!(", word {word} slot {slot}: {what}"));
}
}
@@ -20022,6 +20318,133 @@ mod refresh_tests {
clean_sum_ms / measured,
);
}
+
+ /// Bench (ignored): 1,300 copies that copy something in 48 flushes, with
+ /// `BENCH_LOAD` threads spinning beside them and `VICTORY_REFRESH_INLINE`
+ /// as set.
+ #[test]
+ #[ignore]
+ fn bench_written_flushes_under_load() {
+ // 1,300 copies a frame that copy something, in 48 flushes, with every
+ // core kept busy beside them (`VICTORY_REFRESH_INLINE` as set).
+ const N: usize = 1300;
+ const FLUSHES: usize = 48;
+ let busy = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
+ let load: usize = std::env::var("BENCH_LOAD").ok().and_then(|v| v.parse().ok()).unwrap_or(0);
+ let spinners: Vec<_> = (0..load)
+ .map(|_| {
+ let busy = busy.clone();
+ std::thread::spawn(move || {
+ let mut x = 1u64;
+ while busy.load(std::sync::atomic::Ordering::Relaxed) {
+ for _ in 0..1000 { x = x.wrapping_mul(6364136223846793005).wrapping_add(1); }
+ std::hint::black_box(x);
+ }
+ })
+ })
+ .collect();
+ for view in [false, true] {
+ let region = title(N * PAGE, view);
+ unsafe { std::ptr::write_bytes(region as *mut u8, 1, N * PAGE) };
+ let datas: Vec<*mut u8> = (0..N).map(|_| memory(4096)).collect();
+ let copies: Vec<_> = (0..N).map(|i| (Shadow::unbacked((region + i * PAGE) as u64, datas[i], 4096, false), region + i * PAGE, 4096usize)).collect();
+ let _one = one_submission();
+ let asked = vec![(region, region + N * PAGE)];
+ let mut times = Vec::new();
+ for round in 0..30u8 {
+ for (_, at, _) in &copies { unsafe { ((*at + 64) as *mut u8).write_volatile(round) }; }
+ crate::watch::ask_once(&asked);
+ let t = std::time::Instant::now();
+ for part in copies.chunks(N.div_ceil(FLUSHES)) {
+ let mut b = Batch::default();
+ for (s, at, len) in part { b.add(s, *at, *len); }
+ b.flush();
+ }
+ times.push(t.elapsed().as_secs_f64() * 1e3);
+ crate::watch::ask_once_end();
+ for (i, (_, at, _)) in copies.iter().enumerate() { assert_eq!(unsafe { datas[i].add(64).read_volatile() }, round, "{at:#x}"); }
+ }
+ times.sort_by(f64::total_cmp);
+ println!("view {view} load {load} inline {}: {N} written copies in {FLUSHES} flushes: median {:.2} ms, p90 {:.2}, best {:.2}", super::refresh_inline(), times[15], times[27], times[0]);
+ }
+ busy.store(false, std::sync::atomic::Ordering::Relaxed);
+ spinners.into_iter().for_each(|t| t.join().unwrap());
+ }
+
+ /// Bench (ignored): what a refresh known to copy nothing costs, alone
+ /// and in a flush of thousands, as the heap's buffer views have them.
+ #[test]
+ #[ignore]
+ fn bench_noop_refreshes() {
+ const N: usize = 8000;
+ const LEN: usize = 128 * PAGE;
+ for view in [false, true] {
+ let region = title(LEN, view);
+ unsafe { std::ptr::write_bytes(region as *mut u8, 1, LEN) };
+ let mut copies = Vec::new();
+ for i in 0..N {
+ let at = region + (i * 1031) % (LEN - 512);
+ let data = memory(512);
+ copies.push((Shadow::unbacked(at as u64, data, 512, false), at, 512usize));
+ }
+ let _one = one_submission();
+ let asked = vec![(region, region + LEN)];
+ for _ in 0..3 {
+ crate::watch::ask_once(&asked);
+ let mut b = Batch::default();
+ for (s, at, len) in &copies { b.add(s, *at, *len); }
+ b.flush();
+ crate::watch::ask_once_end();
+ }
+ crate::watch::ask_once(&asked);
+ let mut best_single = f64::MAX;
+ let mut known = 0;
+ for _ in 0..20 {
+ let t = std::time::Instant::now();
+ known = copies.iter().filter(|(s, at, len)| s.nothing_new(*at, *len)).count();
+ best_single = best_single.min(t.elapsed().as_secs_f64() * 1e3);
+ }
+ let mut best_flush = f64::MAX;
+ for _ in 0..20 {
+ let mut b = Batch::default();
+ for (s, at, len) in &copies { b.add(s, *at, *len); }
+ let t = std::time::Instant::now();
+ b.flush();
+ best_flush = best_flush.min(t.elapsed().as_secs_f64() * 1e3);
+ }
+ let mut best_fast = f64::MAX;
+ let mut fast = 0;
+ let mut snap = Vec::new();
+ crate::watch::ahead_snapshot_into(&mut snap);
+ for _ in 0..20 {
+ let t = std::time::Instant::now();
+ fast = copies.iter().filter(|(s, at, len)| s.nothing_new_with(&snap, *at, *len)).count();
+ best_fast = best_fast.min(t.elapsed().as_secs_f64() * 1e3);
+ }
+ crate::watch::ask_once_end();
+ // A seventh of them written, as in the world (1,323 of 8,914),
+ // in one flush and in 48 flushes.
+ for flushes in [1usize, 48] {
+ let mut best = f64::MAX;
+ for round in 0..10u8 {
+ for (i, (_, at, _)) in copies.iter().enumerate() {
+ if i % 7 == 0 { unsafe { ((*at + 100) as *mut u8).write_volatile(round) }; }
+ }
+ crate::watch::ask_once(&asked);
+ let t = std::time::Instant::now();
+ for part in copies.chunks(N.div_ceil(flushes)) {
+ let mut b = Batch::default();
+ for (s, at, len) in part { b.add(s, *at, *len); }
+ b.flush();
+ }
+ best = best.min(t.elapsed().as_secs_f64() * 1e3);
+ crate::watch::ask_once_end();
+ }
+ println!("view {view}: {N} refreshes, 1 in 7 written, {flushes} flushes: best {best:.3} ms");
+ }
+ println!("view {view}: {known}/{N} known same; nothing_new loop best {best_single:.3} ms ({:.0} ns each); flush of {N} best {best_flush:.3} ms; nothing_new_with loop {fast}/{N} best {best_fast:.3} ms ({:.0} ns each)", best_single * 1e6 / N as f64, best_fast * 1e6 / N as f64);
+ }
+ }
}
#[cfg(test)]
diff --git a/crates/victory-gpu/src/host/card_steps.rs b/crates/victory-gpu/src/host/card_steps.rs
index 58388af..3e515bc 100644
--- a/crates/victory-gpu/src/host/card_steps.rs
+++ b/crates/victory-gpu/src/host/card_steps.rs
@@ -933,6 +933,27 @@ fn mapped(from: usize, to: usize, known: &mut HashMap<usize, ()>) -> bool {
})
}
+/// Fewest slots a submission's steps write that are written on several
+/// threads, eight parts (`VICTORY_CARD_STEPS_SLOT_PARTS_MIN=<n>`; 64, was
+/// 256). Each slot is still written by one part alone, in the steps' order,
+/// as with 256 and more: only which submissions split changes.
+///
+/// Why: run 20261129-141314 wrote 5,000 slots a frame in 21 submissions
+/// (some 240 each, under the old 256), two descriptors each, one after the
+/// other on the submitting thread; "planning steps done on the card" was
+/// 5-12 ms a frame of it.
+fn slot_parts_min() -> usize {
+ static MIN: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
+ *MIN.get_or_init(|| {
+ std::env::var("VICTORY_CARD_STEPS_SLOT_PARTS_MIN").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(64usize).max(1)
+ })
+}
+
+/// The submitting thread's time in the steps done on the card, in
+/// nanoseconds: the look at what is in the way, the plan, what holds the
+/// places read, our list recorded, the slots written.
+static SPENT: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5];
+
/// A table by addresses and numbers of ours.
type HashMap<K, V> = std::collections::HashMap<K, V, std::hash::BuildHasherDefault<AddressHash>>;
@@ -1340,6 +1361,17 @@ mod late {
}
}
+ /// Tests: forgets what was learned of the pages of `[from, to)` (another
+ /// test's memory, freed, may be handed out again at the same place).
+ #[cfg(test)]
+ pub(super) fn forget(from: usize, to: usize) {
+ if let Some(pages) = PAGES.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
+ for page in from / PAGE..to.div_ceil(PAGE) {
+ pages.remove(&page);
+ }
+ }
+ }
+
fn learn(from: usize, to: usize, by: &str) {
let mut pages = PAGES.lock().unwrap_or_else(|e| e.into_inner());
let pages = pages.get_or_insert_with(Default::default);
@@ -1604,6 +1636,7 @@ impl Host {
if stage() == 0 || !relay_exact() {
return None;
}
+ let began = std::time::Instant::now();
let (written, copies) = {
let line = line();
if line.blocking().is_empty() {
@@ -1620,6 +1653,7 @@ impl Host {
if !blocked && seen.is_none() && forwards.is_empty() {
return None;
}
+ SPENT[0].fetch_add(began.elapsed().as_nanos() as u64, Ordering::Relaxed);
let taken = match seen {
Some(seen) => Err(seen.why()),
None => self.take_steps(&written, runs, forwards, later),
@@ -1639,6 +1673,11 @@ impl Host {
fn take_steps(&self, written: &[(usize, usize)], runs: &[&HostList], forwards: Vec<Forward>, later: bool) -> Result<Option<Taken>, &'static str> {
let mut spent = crate::timeline::span("steps on the card: chosen");
+ let split = std::cell::Cell::new(std::time::Instant::now());
+ let part = |i: usize| {
+ let now = std::time::Instant::now();
+ SPENT[i].fetch_add((now - split.replace(now)).as_nanos() as u64, Ordering::Relaxed);
+ };
let (mut does, steps) = does_of(written, runs);
let serve = placed_fills();
let by_source = !serve && placed_reads() && read_behind_placed(&mut does, written) > 0;
@@ -1682,6 +1721,7 @@ impl Host {
// that copy's host copy on the card they are. Checked before anything
// is recorded or written.
let shown = show_placed(written, runs, &does, &steps, &served)?;
+ part(1);
spent.next("steps on the card: what holds their bytes");
let mut writers = {
let line = line();
@@ -1794,6 +1834,7 @@ impl Host {
forwarded.push(end);
end = (end + len).next_multiple_of(256);
}
+ part(2);
spent.next("steps on the card: the list");
let Some(own) = self.own_list() else {
return Err("no host list or buffer for it");
@@ -1900,8 +1941,9 @@ impl Host {
own.list.close();
// SAFETY: a live buffer.
let gpu = unsafe { own.between.GetGPUVirtualAddress() };
+ part(3);
spent.next("steps on the card: the slots");
- let parts = if ops.len() < 256 { 1 } else { 8 };
+ let parts = if ops.len() < slot_parts_min() { 1 } else { 8 };
// With `later` (`VICTORY_OFF_LINE`): kept for the thread that sends
// the submission ([`Slots::write`]); else written here, as always.
let slots = if later {
@@ -1939,6 +1981,7 @@ impl Host {
for s in &shown {
crate::descriptor::constant_slot(s.heap, s.index, &s.shadow.buffer, s.gpu, s.len);
}
+ part(4);
let copies = ops.iter().filter(|op| matches!(op.to, To::Copy(..))).count();
DONE[0].fetch_add((ops.len() - copies) as u64, Ordering::Relaxed);
DONE[1].fetch_add(copies as u64, Ordering::Relaxed);
@@ -2045,6 +2088,18 @@ pub(super) fn log(frames: f64) {
let all: Vec<String> = refusals.iter().map(|(why, n)| format!("{:.2} {why}", f64::from(*n) / frames)).collect();
tracing::info!("submissions refused for the card's steps, per frame: {}", all.join("; "));
}
+ let ms: Vec<f64> = SPENT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
+ tracing::info!(
+ "the planning of steps done on the card, ms per frame of the submitting thread: {:.2} the look at what is in the way, \
+ {:.2} the plan, {:.2} what holds the places read, {:.2} our list recorded, {:.2} the slots written (on eight threads \
+ from {} a submission, VICTORY_CARD_STEPS_SLOT_PARTS_MIN)",
+ ms[0],
+ ms[1],
+ ms[2],
+ ms[3],
+ ms[4],
+ slot_parts_min()
+ );
let d: Vec<f64> = DONE.iter().map(|d| d.swap(0, Ordering::Relaxed) as f64 / frames).collect();
tracing::info!(
"steps done on the card instead of waiting for flights, per frame (VICTORY_CARD_STEPS={}): {:.2} fills, {:.2} buffer \
@@ -2280,6 +2335,7 @@ mod tests {
// buffer between.
let sent = [(kept, 32, 0), (changed, 240, 256)];
let card = vec![0u8; 512];
+ late::forget(page, page + 3 * 4096);
// SAFETY: inside `memory`.
unsafe { *(changed as *mut u8).add(88) = 1 };
assert!(!late::written(kept, kept + 32) && !late::written(changed, changed + 240));
@@ -2304,6 +2360,7 @@ mod tests {
let upload = vec![0u8; 1024];
let up = upload.as_ptr() as usize;
let cpu = [(up, kept, 32), (up + 512, changed, 0x220)];
+ late::forget(page, page + 3 * 4096);
// SAFETY: inside `memory`.
unsafe { *(changed as *mut u8).add(0x100) = 7 };
late::landed_cpu(&cpu);
diff --git a/crates/victory-gpu/src/host/font.rs b/crates/victory-gpu/src/host/font.rs
index 6cd704f..423019b 100644
--- a/crates/victory-gpu/src/host/font.rs
+++ b/crates/victory-gpu/src/host/font.rs
@@ -53,6 +53,7 @@ pub(super) const fn glyph(c: u8) -> [u8; 7] {
b'<' => [0b00010, 0b00100, 0b01000, 0b10000, 0b01000, 0b00100, 0b00010],
b'*' => [0, 0b00100, 0b10101, 0b01110, 0b10101, 0b00100, 0],
b':' => [0, 0b01100, 0b01100, 0, 0b01100, 0b01100, 0],
+ b'|' => [0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100],
b'_' => [0, 0, 0, 0, 0, 0, 0b11111],
b'=' => [0, 0, 0b11111, 0, 0b11111, 0, 0],
b'(' => [0b00010, 0b00100, 0b01000, 0b01000, 0b01000, 0b00100, 0b00010],
@@ -79,3 +80,75 @@ pub(super) fn colours(format: DXGI_FORMAT) -> Option<[&'static [u8]; 2]> {
_ => return None,
})
}
+
+/// Converts a finite non-negative float in `[0.0, 1.0]` to IEEE-754 binary16.
+fn f32_to_f16(v: f32) -> u16 {
+ let bits = v.clamp(0.0, 1.0).to_bits();
+ let exp = ((bits >> 23) & 0xFF) as i32 - 127 + 15;
+ let mant = bits & 0x007F_FFFF;
+ if exp <= 0 {
+ if exp < -10 {
+ return 0;
+ }
+ let m = (mant | 0x0080_0000) >> (14 - exp);
+ return m as u16;
+ }
+ if exp >= 31 {
+ return 0x7C00;
+ }
+ ((exp as u16) << 10) | ((mant >> 13) as u16)
+}
+
+/// Encodes an opaque sRGB `[r, g, b]` colour into a swap chain pixel.
+pub(super) fn encode_rgb(format: DXGI_FORMAT, [r, g, b]: [u8; 3]) -> Option<([u8; 8], usize)> {
+ let mut out = [0u8; 8];
+ match format {
+ DXGI_FORMAT_R8G8B8A8_UNORM => {
+ out[..4].copy_from_slice(&[r, g, b, 0xFF]);
+ Some((out, 4))
+ }
+ DXGI_FORMAT_B8G8R8A8_UNORM => {
+ out[..4].copy_from_slice(&[b, g, r, 0xFF]);
+ Some((out, 4))
+ }
+ DXGI_FORMAT_R10G10B10A2_UNORM => {
+ let to10 = |c: u8| ((u32::from(c) * 1023 + 127) / 255) & 0x3FF;
+ let packed = to10(r) | (to10(g) << 10) | (to10(b) << 20) | (0b11u32 << 30);
+ out[..4].copy_from_slice(&packed.to_le_bytes());
+ Some((out, 4))
+ }
+ DXGI_FORMAT_R16G16B16A16_FLOAT => {
+ // Simple sRGB-approx gamma (v^2.2) so colours stay rich in scRGB HDR swap chains.
+ let lin = |c: u8| f32_to_f16((f32::from(c) / 255.0).powf(2.2));
+ out[0..2].copy_from_slice(&lin(r).to_le_bytes());
+ out[2..4].copy_from_slice(&lin(g).to_le_bytes());
+ out[4..6].copy_from_slice(&lin(b).to_le_bytes());
+ out[6..8].copy_from_slice(&0x3C00u16.to_le_bytes());
+ Some((out, 8))
+ }
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn encode_rgb_handles_all_swapchain_formats() {
+ let (rgba, n) = encode_rgb(DXGI_FORMAT_R8G8B8A8_UNORM, [10, 20, 30]).unwrap();
+ assert_eq!((n, &rgba[..4]), (4, &[10, 20, 30, 0xFF][..]));
+ let (bgra, n) = encode_rgb(DXGI_FORMAT_B8G8R8A8_UNORM, [10, 20, 30]).unwrap();
+ assert_eq!((n, &bgra[..4]), (4, &[30, 20, 10, 0xFF][..]));
+ let (rgb10_black, n) = encode_rgb(DXGI_FORMAT_R10G10B10A2_UNORM, [0, 0, 0]).unwrap();
+ assert_eq!((n, &rgb10_black[..4]), (4, &[0, 0, 0, 0xC0][..]));
+ let (rgb10_white, _) = encode_rgb(DXGI_FORMAT_R10G10B10A2_UNORM, [255, 255, 255]).unwrap();
+ assert_eq!(&rgb10_white[..4], &[0xFF; 4]);
+ let (f16_black, n) = encode_rgb(DXGI_FORMAT_R16G16B16A16_FLOAT, [0, 0, 0]).unwrap();
+ assert_eq!((n, &f16_black[..8]), (8, &[0, 0, 0, 0, 0, 0, 0, 0x3C][..]));
+ let (f16_white, _) = encode_rgb(DXGI_FORMAT_R16G16B16A16_FLOAT, [255, 255, 255]).unwrap();
+ assert_eq!(&f16_white[..8], &[0, 0x3C, 0, 0x3C, 0, 0x3C, 0, 0x3C]);
+ assert!(encode_rgb(DXGI_FORMAT_UNKNOWN, [1, 2, 3]).is_none());
+ assert_ne!(glyph(b'|'), glyph(b'#'));
+ }
+}
diff --git a/crates/victory-gpu/src/host/indirects.rs b/crates/victory-gpu/src/host/indirects.rs
index 7ce7751..8f8e714 100644
--- a/crates/victory-gpu/src/host/indirects.rs
+++ b/crates/victory-gpu/src/host/indirects.rs
@@ -8,7 +8,11 @@
//! Per list, in the order recorded: the pipeline (by its host object, whose
//! name is kept once) and the first root constants (user data) it had. The
//! report finds an indirect execution by how many the breadcrumbs' history
-//! has before it. Nothing is kept without device-removed data.
+//! has before it, and which of those words are descriptor tables' byte
+//! offsets: #3222's report named "word 6 slot 16: null" for a root constant
+//! of 16 and said nothing of the table at word 4, whose slots lay past the
+//! title's in the host's dynamic ones. Nothing is kept without
+//! device-removed data.
//! `VICTORY_D3D12_DRED=faults` and no data at all: nothing is noted.
use std::collections::HashMap;
@@ -31,6 +35,8 @@ pub(crate) struct Ran {
count: u32,
words: [u32; WORDS],
used: u8,
+ /// Bit `i`: word `i` is a table's byte offset ([`table_words`]).
+ tables: u16,
}
#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))]
@@ -51,12 +57,14 @@ impl Indirects {
/// An indirect execution of `kind` (the argument's type) of at most
/// `count` records with `pipeline` (a host object) and user data.
/// A direct mesh dispatch of `count` groups is of kind [`DIRECT`].
- pub(crate) fn note(&mut self, pipeline: usize, name: &str, kind: u32, count: u32, user: &[u32]) {
+ /// `tables`: which words are tables' byte offsets ([`table_words`]; 0:
+ /// not known).
+ pub(crate) fn note(&mut self, pipeline: usize, name: &str, kind: u32, count: u32, user: &[u32], tables: u16) {
self.names.entry(pipeline).or_insert_with(|| name.to_owned());
let used = user.len().min(WORDS);
let mut words = [0; WORDS];
words[..used].copy_from_slice(&user[..used]);
- let ran = Ran { pipeline, kind, count, words, used: used as u8 };
+ let ran = Ran { pipeline, kind, count, words, used: used as u8, tables };
if kind == DIRECT {
self.meshes.push(ran);
} else {
@@ -72,9 +80,9 @@ impl Indirects {
}
}
- /// The `nth` execution (from 0), or direct mesh dispatch: its text and
- /// its user data.
- pub(crate) fn nth(&self, nth: usize, direct: bool) -> Option<(String, &[u32])> {
+ /// The `nth` execution (from 0), or direct mesh dispatch: its text, its
+ /// user data and which words of it are tables.
+ pub(crate) fn nth(&self, nth: usize, direct: bool) -> Option<(String, &[u32], u16)> {
let ran = if direct { &self.meshes } else { &self.ran }.get(nth)?;
let name = self.names.get(&ran.pipeline).map_or("a pipeline", String::as_str);
let words = &ran.words[..usize::from(ran.used)];
@@ -85,6 +93,7 @@ impl Indirects {
format!("{name} (indirect kind {} max {}, the list's indirect execution {nth}, user data {words:x?})", ran.kind, ran.count)
},
words,
+ ran.tables,
))
}
}
@@ -96,18 +105,37 @@ pub(crate) fn before<T>(history: &[T], at: usize, is: impl Fn(&T) -> bool) -> us
history[..at.min(history.len())].iter().filter(|op| is(op)).count()
}
-/// The heap slots the user data may name, for the report to describe: the
-/// words that are slots as they are, and the slots from where a word is a
-/// table's byte offset (32 bytes a descriptor), `table` of them.
+/// Which of a bind's user-data words are tables' byte offsets: bit `i` for
+/// word `i` (words from 16 on are not kept, [`WORDS`]).
#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))]
-pub(crate) fn slots(words: &[u32], count: u32, table: u32) -> Vec<(usize, u32)> {
+pub(crate) fn table_words(indices: impl IntoIterator<Item = u32>) -> u16 {
+ indices.into_iter().filter(|&i| (i as usize) < WORDS).fold(0, |bits, i| bits | 1 << i)
+}
+
+/// The heap slots the user data names, for the report to describe: from
+/// each word that is a table's byte offset (32 bytes a descriptor), `table`
+/// slots, below `count` (the view heap's slots, the title's and the dynamic
+/// ones past them, where tables made afresh lie). With no word known to be a
+/// table (`tables` 0), the words that may be: a multiple of 32 as a table,
+/// and a small word that is not as a slot of its own.
+#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))]
+pub(crate) fn slots(words: &[u32], tables: u16, count: u32, table: u32) -> Vec<(usize, u32)> {
let mut out = Vec::new();
+ let from = |out: &mut Vec<(usize, u32)>, i: usize, word: u32| {
+ out.extend((0..table).map(|k| (i, word / 32 + k)).filter(|s| s.1 < count));
+ };
for (i, &word) in words.iter().enumerate() {
+ if tables != 0 {
+ if i < WORDS && tables & 1 << i != 0 && word % 32 == 0 {
+ from(&mut out, i, word);
+ }
+ continue;
+ }
if word > 0 && word < count && word % 32 != 0 {
out.push((i, word));
}
if word % 32 == 0 && word / 32 > 16 && word / 32 < count {
- out.extend((0..table).map(|k| (i, word / 32 + k)).filter(|s| s.1 < count));
+ from(&mut out, i, word);
}
}
out
@@ -122,21 +150,22 @@ mod tests {
#[test]
fn an_indirect_execution_is_found_by_its_place_in_the_history() {
let mut all = Indirects::default();
- all.note(1, "[compute a]", 2, 1, &[0x2549f40, 0x20, 0x11]);
- all.note(2, "[compute b]", 2, 1, &[7; 20]);
- all.note(1, "another name of the same is not taken", 10, 4, &[]);
+ all.note(1, "[compute a]", 2, 1, &[0x2549f40, 0x20, 0x11], 0b1);
+ all.note(2, "[compute b]", 2, 1, &[7; 20], 0);
+ all.note(1, "another name of the same is not taken", 10, 4, &[], 0);
// dispatch, indirect, barrier, indirect, indirect
let history = [6, 5, 15, 5, 5];
let nth = before(&history, 3, |op| *op == 5);
assert_eq!(nth, 1);
- let (text, words) = all.nth(nth, false).unwrap();
+ let (text, words, tables) = all.nth(nth, false).unwrap();
assert!(text.starts_with("[compute b] (indirect kind 2 max 1"), "{text}");
- assert_eq!(words, [7; WORDS]);
- all.note(2, "[mesh b]", DIRECT, 9, &[1]);
- let (text, _) = all.nth(0, true).unwrap();
+ assert_eq!((words, tables), (&[7; WORDS][..], 0));
+ assert_eq!(all.nth(0, false).unwrap().2, 0b1);
+ all.note(2, "[mesh b]", DIRECT, 9, &[1], 0);
+ let (text, _, _) = all.nth(0, true).unwrap();
assert!(text.starts_with("[compute b] (a mesh dispatch of 9 groups"), "{text}");
assert!(all.nth(1, true).is_none());
- let (text, words) = all.nth(2, false).unwrap();
+ let (text, words, _) = all.nth(2, false).unwrap();
assert!(text.starts_with("[compute a] (indirect kind 10 max 4"), "{text}");
assert!(words.is_empty());
assert!(all.nth(3, false).is_none());
@@ -150,7 +179,28 @@ mod tests {
#[test]
fn user_data_names_slots() {
let words = [0, 0x2549f40, 0x20, 0x11, 0x26f1, 0xffff_ffff];
- let slots = slots(&words, 1_245_184, 2);
+ let slots = slots(&words, 0, 1_245_184, 2);
assert_eq!(slots, [(1, 0x2549f40 / 32), (1, 0x2549f40 / 32 + 1), (3, 0x11), (4, 0x26f1)]);
}
+
+ /// #3222's dispatch: a table at word 4 whose slots lie past the title's
+ /// (606,783 on a capped heap), root constants at words 5 to 7. With the
+ /// words that are tables known, the table's slots are named, in the
+ /// dynamic ones, and the constant 16 at word 6 is no slot.
+ #[test]
+ fn the_tables_words_name_their_slots_and_constants_none() {
+ let words = [0, 0, 0, 0, 0x12b_a3e0, 0, 0x10, 0];
+ let tables = table_words([4]);
+ assert_eq!(tables, 0b1_0000);
+ let named = slots(&words, tables, 606_783 + 393_216, 7);
+ let first = 0x12b_a3e0 / 32;
+ assert_eq!(first, 613_663);
+ assert_eq!(named, (0..7).map(|k| (4, first + k)).collect::<Vec<_>>());
+ // Not knowing which words are tables, the constant was taken for a slot.
+ assert!(slots(&words, 0, 606_783 + 393_216, 7).contains(&(6, 16)));
+ // A table word that is no descriptor's offset names nothing; words
+ // past those kept are not tables.
+ assert!(slots(&[0x10], 0b1, 1000, 2).is_empty());
+ assert_eq!(table_words([3, 15, 16, 40]), 1 << 3 | 1 << 15);
+ }
}
diff --git a/crates/victory-gpu/src/host/panel.rs b/crates/victory-gpu/src/host/panel.rs
index 7ffc2d9..9ebc966 100644
--- a/crates/victory-gpu/src/host/panel.rs
+++ b/crates/victory-gpu/src/host/panel.rs
@@ -1,15 +1,13 @@
//! The run's numbers on the picture, in every build (`VICTORY_PANEL=1`; off
//! by default; F3 or the settings menu shows and hides it while our window
-//! has the focus; the time spent recording is counted in diagnostics builds
-//! only): white
-//! text on a black box in the upper left corner of what is shown, so that a
-//! screenshot carries them, with what it costs itself on the submitting
-//! thread. Made again twice a second from the counters of
-//! the frame-rate line, memory and textures; a frame itself only copies the
-//! box out of a buffer in the card's memory. Copied onto the swap chain's
-//! buffer, behind the title's picture: saved frames and the frame recorder
-//! see the title's own.
-
+//! has the focus): a multi-colour telemetry HUD in the upper-right corner
+//! showing native FPS, frametime graph, GPU usage, VRAM (local/budget/cap/shared),
+//! per-core CPU bars, process memory, and system RAM, plus an automatic
+//! top-centre shader-compilation progress banner whenever shaders are queued.
+//! Made again twice a second from the counters; each frame only copies the
+//! pre-painted box out of a card-local buffer onto the swap chain back buffer.
+
+use std::collections::VecDeque;
use std::sync::{Once, OnceLock};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
@@ -19,7 +17,7 @@ use windows::Win32::Graphics::Dxgi::Common::*;
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{GetAsyncKeyState, VK_F3, VK_F7, VK_F8};
use windows_sys::Win32::UI::WindowsAndMessaging::{GetForegroundWindow, GetWindowThreadProcessId};
-use super::font::{colours, glyph};
+use super::font::{colours, encode_rgb, glyph};
use super::{Host, HostList, transition};
/// How often the numbers change.
@@ -28,28 +26,61 @@ const EVERY: Duration = Duration::from_millis(500);
/// A character's dots, and with the space beside and below it.
const GLYPH: (u32, u32) = (5, 7);
const CELL: (u32, u32) = (6, 9);
-/// Characters in a line, lines, and the box's rim in dots.
+/// Characters in a line, lines, and the box's rim in dots (legacy monochrome boxes).
+#[cfg_attr(not(test), allow(dead_code))]
const COLUMNS: u32 = 40;
+#[cfg_attr(not(test), allow(dead_code))]
const LINES: u32 = 13;
const RIM: u32 = 3;
-/// Graphs under the text (FPS, the game's CPU, its memory, the card's
-/// memory): each [`GRAPH`] dots high with [`GRAPH_GAP`] below, one sample a
-/// dot across the box, the newest on the right (two minutes at [`EVERY`]).
+/// Graphs under the text (legacy monochrome box layout; kept for `Notice`/`Advisor`/`tests`).
+#[cfg_attr(not(test), allow(dead_code))]
const GRAPHS: u32 = 4;
const GRAPH: u32 = 16;
const GRAPH_GAP: u32 = 3;
-const HISTORY: usize = (COLUMNS * CELL.0) as usize;
/// The texts are put into one of these in turn: the card reads the others,
/// at most half a second old.
const UPLOADS: usize = 4;
+/// Telemetry HUD logical dimensions in dots (`520 x 352` px at `scale = 2` on 1080p).
+const HUD_W: u32 = 260;
+const HUD_H: u32 = 176;
+const HUD_PAD: u32 = 5;
+const FRAMETIME_HISTORY: usize = 124;
+
+/// Top-centre shader compilation banner logical dimensions in dots.
+const BANNER_W: u32 = 256;
+const BANNER_H: u32 = 34;
+
+/// High-contrast dark telemetry colour palette (sRGB).
+mod palette {
+ pub(super) const BG: [u8; 3] = [14, 17, 24];
+ pub(super) const GRAPH_BG: [u8; 3] = [9, 11, 16];
+ pub(super) const BORDER: [u8; 3] = [58, 66, 82];
+ pub(super) const GUIDE: [u8; 3] = [44, 52, 68];
+ pub(super) const GOLD: [u8; 3] = [255, 200, 68];
+ pub(super) const WHITE: [u8; 3] = [238, 242, 248];
+ pub(super) const DIM: [u8; 3] = [145, 156, 175];
+ pub(super) const LABEL: [u8; 3] = [100, 185, 255];
+ pub(super) const CYAN: [u8; 3] = [120, 218, 255];
+ pub(super) const GREEN: [u8; 3] = [80, 212, 120];
+ pub(super) const AMBER: [u8; 3] = [235, 152, 55];
+ pub(super) const RED: [u8; 3] = [238, 68, 68];
+ pub(super) const CORE_BG: [u8; 3] = [28, 34, 46];
+ pub(super) const CORE_FILL: [u8; 3] = [95, 185, 255];
+}
+
fn asked() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| crate::switch::on("VICTORY_PANEL"))
}
+fn shader_banner_enabled() -> bool {
+ static ON: OnceLock<bool> = OnceLock::new();
+ *ON.get_or_init(|| std::env::var_os("VICTORY_SHADER_BANNER").is_none_or(|v| v != "0"))
+}
+
/// Whether it is shown now.
pub(super) fn shown() -> &'static AtomicBool {
static SHOWN: OnceLock<AtomicBool> = OnceLock::new();
@@ -118,7 +149,8 @@ pub(super) struct Shape {
graphs: u32,
}
-/// The numbers panel's box.
+/// The legacy monochrome panel box (kept for unit tests).
+#[cfg(test)]
const PANEL: Shape = Shape { columns: COLUMNS, lines: LINES, graphs: GRAPHS };
/// The box's size in pixels, a dot being `scale` of them each way.
@@ -135,6 +167,12 @@ fn scale(height: u32) -> u32 {
(height / 540).max(1)
}
+/// Pixels to a dot for the telemetry HUD and shader banner: windowed 1080p
+/// (`~1040` px client height) cleanly gets `2x`, matching fullscreen 1080p.
+fn hud_scale(height: u32) -> u32 {
+ (height / 500).max(1)
+}
+
/// Whether a dot of the picture of `lines` and `graphs` is white.
fn lit(lines: &[String], graphs: &[Vec<f32>], shape: Shape, x: u32, y: u32) -> bool {
let (Some(x), Some(y)) = (x.checked_sub(RIM), y.checked_sub(RIM)) else {
@@ -197,16 +235,125 @@ fn painted(lines: &[String], graphs: &[Vec<f32>], shape: Shape, scale: u32, colo
out
}
+/// A small logical-dot RGB canvas encoded into the swap chain's pixel format.
+struct Canvas {
+ w: u32,
+ h: u32,
+ dots: Vec<[u8; 3]>,
+}
+
+impl Canvas {
+ fn new(w: u32, h: u32, bg: [u8; 3]) -> Canvas {
+ Canvas { w, h, dots: vec![bg; (w * h) as usize] }
+ }
+
+ #[inline]
+ fn set(&mut self, x: u32, y: u32, rgb: [u8; 3]) {
+ if x < self.w && y < self.h {
+ self.dots[(y * self.w + x) as usize] = rgb;
+ }
+ }
+
+ fn fill_rect(&mut self, x: u32, y: u32, w: u32, h: u32, rgb: [u8; 3]) {
+ let x1 = x.saturating_add(w).min(self.w);
+ let y1 = y.saturating_add(h).min(self.h);
+ for py in y..y1 {
+ let row = (py * self.w) as usize;
+ self.dots[row + x as usize..row + x1 as usize].fill(rgb);
+ }
+ }
+
+ fn stroke_rect(&mut self, x: u32, y: u32, w: u32, h: u32, rgb: [u8; 3]) {
+ if w == 0 || h == 0 {
+ return;
+ }
+ self.fill_rect(x, y, w, 1, rgb);
+ self.fill_rect(x, y + h - 1, w, 1, rgb);
+ self.fill_rect(x, y, 1, h, rgb);
+ self.fill_rect(x + w - 1, y, 1, h, rgb);
+ }
+
+ fn text(&mut self, x: u32, y: u32, text: &str, rgb: [u8; 3], char_scale: u32) {
+ let step = CELL.0 * char_scale;
+ for (idx, b) in text.bytes().enumerate() {
+ let gx = x.saturating_add(idx as u32 * step);
+ if gx >= self.w {
+ break;
+ }
+ let bits = glyph(b.to_ascii_uppercase());
+ for (row, &mask) in bits.iter().enumerate() {
+ if mask == 0 {
+ continue;
+ }
+ for col in 0..GLYPH.0 {
+ if (mask >> (GLYPH.0 - 1 - col)) & 1 != 0 {
+ self.fill_rect(
+ gx + col * char_scale,
+ y + row as u32 * char_scale,
+ char_scale,
+ char_scale,
+ rgb,
+ );
+ }
+ }
+ }
+ }
+ }
+
+ fn text_rich(&mut self, x: u32, y: u32, text: &str, main_rgb: [u8; 3], sep_rgb: [u8; 3]) {
+ for (idx, b) in text.bytes().enumerate() {
+ let gx = x.saturating_add(idx as u32 * CELL.0);
+ if gx >= self.w {
+ break;
+ }
+ let rgb = if b == b'|' { sep_rgb } else { main_rgb };
+ let bits = glyph(b.to_ascii_uppercase());
+ for (row, &mask) in bits.iter().enumerate() {
+ if mask == 0 {
+ continue;
+ }
+ for col in 0..GLYPH.0 {
+ if (mask >> (GLYPH.0 - 1 - col)) & 1 != 0 {
+ self.set(gx + col, y + row as u32, rgb);
+ }
+ }
+ }
+ }
+ }
+
+ fn encode(&self, format: DXGI_FORMAT, scale: u32, pitch: usize) -> Option<Vec<u8>> {
+ let (_, bytes) = encode_rgb(format, [0, 0, 0])?;
+ let height = (self.h * scale) as usize;
+ let mut out = vec![0u8; pitch * height];
+ for y in 0..self.h {
+ let top = pitch * (y * scale) as usize;
+ let row = (y * self.w) as usize;
+ for x in 0..self.w {
+ let (encoded, _) = encode_rgb(format, self.dots[row + x as usize])?;
+ let px = &encoded[..bytes];
+ for i in 0..scale {
+ let at = top + (x * scale + i) as usize * bytes;
+ out[at..at + bytes].copy_from_slice(px);
+ }
+ }
+ for i in 1..scale as usize {
+ out.copy_within(top..top + pitch, top + i * pitch);
+ }
+ }
+ Some(out)
+ }
+}
+
/// The counters read for it. They grow, and go back to 0 with the frame-rate
/// line (right behind a look of ours).
#[derive(Clone, Copy, Default)]
struct Counters([u64; COUNTERS]);
-const COUNTERS: usize = 11;
+const COUNTERS: usize = 12;
impl Counters {
fn now() -> Counters {
- use super::{CARD_CLOCK_US, COPY_BACK, PREPARING};
+ use super::{CARD_CLOCK_US, COPY_BACK, PREPARING, SUBMISSION_US};
#[cfg(feature = "diagnostics")]
let recording = crate::copystat::peek(crate::copystat::C::RecordNs);
#[cfg(not(feature = "diagnostics"))]
@@ -221,9 +368,10 @@ impl Counters {
get(&COPY_BACK[0]),
get(&COPY_BACK[1]),
get(&crate::shadow::CARD_STATS[0]),
- crate::draw::dropped_now(),
+ crate::draw::no_pipeline_all(),
recording,
crate::draw::drawn(),
+ get(&SUBMISSION_US[0]),
])
}
@@ -290,7 +438,214 @@ fn cpu_percent(before: (u64, u64, u64), now: (u64, u64, u64), seconds: f64, core
(game.clamp(0.0, 100.0), pc.clamp(0.0, 100.0))
}
-/// What the panel says of the PC beside the run's counters.
+/// Windows `SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION` (48 bytes on x64).
+#[repr(C)]
+#[derive(Clone, Copy, Default)]
+struct SystemProcessorPerformanceInfo {
+ idle_time: i64,
+ kernel_time: i64,
+ user_time: i64,
+ dpc_time: i64,
+ interrupt_time: i64,
+ interrupt_count: u32,
+ _pad: u32,
+}
+
+type NtQuerySystemInformationFn =
+ unsafe extern "system" fn(u32, *mut std::ffi::c_void, u32, *mut u32) -> i32;
+
+/// Queries per-logical-processor `(idle, total)` ticks via `ntdll!NtQuerySystemInformation`.
+fn per_core_times() -> Option<Vec<(i64, i64)>> {
+ use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress};
+ static QUERY: OnceLock<Option<NtQuerySystemInformationFn>> = OnceLock::new();
+ let func = *QUERY.get_or_init(|| {
+ // SAFETY: `ntdll.dll` is permanently loaded in every Windows process.
+ unsafe {
+ let module = GetModuleHandleA(c"ntdll.dll".as_ptr().cast());
+ if module.is_null() {
+ return None;
+ }
+ let proc = GetProcAddress(module, c"NtQuerySystemInformation".as_ptr().cast())?;
+ Some(std::mem::transmute::<unsafe extern "system" fn() -> isize, NtQuerySystemInformationFn>(proc))
+ }
+ });
+ let func = func?;
+ let cores = std::thread::available_parallelism().map_or(1, |n| n.get()).clamp(1, 128);
+ let mut buf = vec![SystemProcessorPerformanceInfo::default(); cores];
+ let mut returned = 0u32;
+ const SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION: u32 = 8;
+ // SAFETY: `buf` is sized for `cores` entries of `SystemProcessorPerformanceInfo`.
+ let status = unsafe {
+ func(
+ SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION,
+ buf.as_mut_ptr().cast(),
+ (buf.len() * size_of::<SystemProcessorPerformanceInfo>()) as u32,
+ &mut returned,
+ )
+ };
+ if status < 0 {
+ return None;
+ }
+ let count = (returned as usize / size_of::<SystemProcessorPerformanceInfo>()).min(buf.len());
+ if count == 0 {
+ return None;
+ }
+ Some(
+ buf[..count]
+ .iter()
+ .map(|entry| (entry.idle_time, entry.kernel_time.saturating_add(entry.user_time)))
+ .collect(),
+ )
+}
+
+/// Per-core busy fraction in `0.0..=1.0` between two [`per_core_times`] snapshots.
+fn core_busy_fractions(before: &[(i64, i64)], now: &[(i64, i64)]) -> Vec<f32> {
+ before
+ .iter()
+ .zip(now)
+ .map(|(&(b_idle, b_total), &(n_idle, n_total))| {
+ let d_idle = n_idle.saturating_sub(b_idle).max(0) as f64;
+ let d_total = n_total.saturating_sub(b_total).max(0) as f64;
+ if d_total > 0.0 {
+ ((d_total - d_idle) / d_total).clamp(0.0, 1.0) as f32
+ } else {
+ 0.0
+ }
+ })
+ .collect()
+}
+
+/// Cleans a CPU/GPU brand string to uppercase ASCII supported by `font::glyph`.
+fn clean_hardware_name(raw: &str, max_len: usize) -> String {
+ let mut s = raw.to_ascii_uppercase();
+ for noise in [
+ "(R)",
+ "(TM)",
+ "(C)",
+ "WITH RADEON GRAPHICS",
+ "6-CORE PROCESSOR",
+ "8-CORE PROCESSOR",
+ "12-CORE PROCESSOR",
+ "16-CORE PROCESSOR",
+ "PROCESSOR",
+ "CPU",
+ ] {
+ s = s.replace(noise, " ");
+ }
+ if let Some(at) = s.find('@') {
+ s.truncate(at);
+ }
+ let mut cleaned = String::with_capacity(s.len().min(max_len));
+ let mut prev_space = true;
+ for ch in s.bytes() {
+ let valid = ch.is_ascii_alphanumeric() || matches!(ch, b'-' | b'.' | b'/' | b'+');
+ if valid {
+ cleaned.push(ch as char);
+ prev_space = false;
+ } else if !prev_space {
+ cleaned.push(' ');
+ prev_space = true;
+ }
+ }
+ let trimmed = cleaned.trim();
+ if trimmed.len() <= max_len {
+ trimmed.to_owned()
+ } else {
+ trimmed[..max_len].trim_end().to_owned()
+ }
+}
+
+/// Reads the CPU brand string once via x86_64 CPUID leaves `0x80000002..=0x80000004`.
+fn cpu_brand() -> &'static str {
+ static BRAND: OnceLock<String> = OnceLock::new();
+ BRAND.get_or_init(|| {
+ #[cfg(target_arch = "x86_64")]
+ {
+ use std::arch::x86_64::__cpuid;
+ let max_ext = __cpuid(0x8000_0000).eax;
+ if max_ext >= 0x8000_0004 {
+ let mut bytes = [0u8; 48];
+ for (i, leaf) in [0x8000_0002u32, 0x8000_0003, 0x8000_0004].into_iter().enumerate() {
+ let r = __cpuid(leaf);
+ let base = i * 16;
+ bytes[base..base + 4].copy_from_slice(&r.eax.to_le_bytes());
+ bytes[base + 4..base + 8].copy_from_slice(&r.ebx.to_le_bytes());
+ bytes[base + 8..base + 12].copy_from_slice(&r.ecx.to_le_bytes());
+ bytes[base + 12..base + 16].copy_from_slice(&r.edx.to_le_bytes());
+ }
+ let end = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len());
+ let name = clean_hardware_name(&String::from_utf8_lossy(&bytes[..end]), 30);
+ if !name.is_empty() {
+ return name;
+ }
+ }
+ }
+ "CPU".to_owned()
+ })
+}
+
+/// Queries the GPU adapter name and dedicated VRAM capacity once via DXGI `GetDesc1`.
+fn adapter_info(host: &Host) -> (&'static str, u64) {
+ static INFO: OnceLock<(String, u64)> = OnceLock::new();
+ let (name, cap) = INFO.get_or_init(|| {
+ if let Some(adapter) = host.adapter.as_ref() {
+ // SAFETY: `GetDesc1` reads immutable adapter metadata.
+ if let Ok(desc) = unsafe { adapter.GetDesc1() } {
+ let len = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len());
+ let raw = String::from_utf16_lossy(&desc.Description[..len]);
+ let clean = clean_hardware_name(&raw, 30);
+ let name = if clean.is_empty() { "GPU".to_owned() } else { clean };
+ return (name, desc.DedicatedVideoMemory as u64);
+ }
+ }
+ ("GPU".to_owned(), 0)
+ });
+ (name.as_str(), *cap)
+}
+
+/// Computes `(one_percent_low_fps, max_fps)` from recent per-frame durations in ms.
+fn frametime_stats(samples: &VecDeque<f32>, fallback_fps: f64) -> (f64, f64) {
+ if samples.len() < 4 {
+ return (fallback_fps, fallback_fps);
+ }
+ let mut sorted: Vec<f32> = samples.iter().copied().filter(|&ms| ms.is_finite() && ms > 0.5).collect();
+ if sorted.len() < 4 {
+ return (fallback_fps, fallback_fps);
+ }
+ sorted.sort_by(|a, b| a.total_cmp(b));
+ let n = sorted.len();
+ // 1% low = slowest ~2% frames averaged (smooth on a 124-frame window).
+ let slow_count = (n / 50).max(1);
+ let slow_avg_ms = sorted[n - slow_count..].iter().map(|&v| f64::from(v)).sum::<f64>() / slow_count as f64;
+ // Max FPS = 5th percentile fastest frame so single micro-presents do not skew the readout.
+ let fast_idx = (n / 20).min(n - 1);
+ let fast_ms = f64::from(sorted[fast_idx]).max(1.0);
+ ((1e3 / slow_avg_ms.max(1.0)).min(fallback_fps.max(1.0)), (1e3 / fast_ms).max(fallback_fps))
+}
+
+/// Compact upscaler label for the upper-right HUD header.
+fn short_upscaler(dlss: Option<(&str, Option<char>)>) -> String {
+ match dlss {
+ Some((mode, preset)) => {
+ let tag = match mode.to_ascii_lowercase().as_str() {
+ "ultraperformance" | "ultra performance" => "ULTRA",
+ "performance" => "PERF",
+ "balanced" => "BAL",
+ "quality" => "QUAL",
+ "dlaa" => "DLAA",
+ _ => "ON",
+ };
+ match preset {
+ Some(p) => format!("DLSS {tag} {}", p.to_ascii_uppercase()),
+ None => format!("DLSS {tag}"),
+ }
+ }
+ None => "DLSS OFF".to_owned(),
+ }
+}
+
+/// What the panel says of the PC beside the run's counters (kept for legacy tests).
+#[cfg_attr(not(test), allow(dead_code))]
#[derive(Clone, Copy, Default)]
struct Pc {
cpu_game: f64,
@@ -301,6 +656,7 @@ struct Pc {
}
/// The lines of [`Pc`].
+#[cfg_attr(not(test), allow(dead_code))]
fn pc_lines(pc: Pc) -> [String; 2] {
let gb = |bytes: u64| bytes as f64 / (1u64 << 30) as f64;
[
@@ -310,9 +666,11 @@ fn pc_lines(pc: Pc) -> [String; 2] {
}
/// The line that names the graphs, top to bottom.
+#[cfg_attr(not(test), allow(dead_code))]
const LEGEND: &str = "GRAPHS 2 MIN: FPS/60 CPU RAM/PC VRAM";
/// Show the applied mode and, when the backend reports it, the last present count.
+#[cfg_attr(not(test), allow(dead_code))]
fn generated(fps: f64, reading: crate::streamline::FramegenReading) -> String {
use crate::streamline::FramegenReading;
match reading {
@@ -327,6 +685,7 @@ fn generated(fps: f64, reading: crate::streamline::FramegenReading) -> String {
/// The upscaling line: DLSS's mode and preset, or that the title's own
/// upscaling runs.
+#[cfg_attr(not(test), allow(dead_code))]
fn upscaler(dlss: Option<(&str, Option<char>)>) -> String {
match dlss {
Some((mode, Some(preset))) => format!("DLSS {mode} PRESET {preset}").to_uppercase(),
@@ -335,54 +694,217 @@ fn upscaler(dlss: Option<(&str, Option<char>)>) -> String {
}
}
-/// The text. `c`: [`Counters`] per frame, `ms` a frame's time, `worst` the
-/// longest frame's, `cost` what this takes of a frame, in microseconds,
-/// `output` the picture's size.
-fn text(c: &[f64; COUNTERS], ms: f64, worst: f64, cost: f64, pc: Pc, output: (u32, u32), host: &Host) -> Vec<String> {
- let gb = |bytes: u64| bytes as f64 / (1u64 << 30) as f64;
- let (_, private) = process_memory();
- let [budget, used, _, shared] = host.video_memory().unwrap_or_default();
- let idle = (c[1] / 1e3).min(ms);
- let fps = 1e3 / ms.max(0.001);
- let console = match crate::console::current() {
- crate::console::Console::SeriesS => "SERIES S",
- crate::console::Console::SeriesX => "SERIES X",
- };
- let dlss = crate::streamline::upscaled_lately();
- let size = |[w, h]: [u32; 2]| format!("{w}X{h}");
- let picture = match dlss {
- Some((_, scene, out, _)) => format!("SCENE {} OUTPUT {}", size(scene), size(out)),
- None => format!("OUTPUT {}", size([output.0, output.1])),
- };
- // Which ray tracing runs: the card's own (DXR, `VICTORY_HW_RT=1`), ours
- // in shaders (`VICTORY_BVH_BUILDER=1`), or none.
- let rays = if crate::hwrt::active() {
- "RAY TRACING HARDWARE (DXR)"
- } else if std::env::var_os("VICTORY_BVH_BUILDER").is_some_and(|v| v == "1") {
- "RAY TRACING SOFTWARE"
+/// Live data rendered into the upper-right telemetry HUD.
+struct HudSnapshot {
+ fps: f64,
+ fg_mult: u32,
+ upscaler_tag: String,
+ console_tag: &'static str,
+ output: (u32, u32),
+ draws: f64,
+ dropped: f64,
+ frame_ms: f64,
+ sub_ms: f64,
+ gpu_ms: f64,
+ fps_low1: f64,
+ fps_max: f64,
+ gpu_name: String,
+ gpu_pct: f64,
+ vram_used: u64,
+ vram_budget: u64,
+ vram_ded_cap: u64,
+ vram_shared: u64,
+ cpu_name: String,
+ cpu_pc_pct: f64,
+ core_loads: Vec<f32>,
+ proc_ws: u64,
+ proc_commit: u64,
+ ram_free: u64,
+ ram_total: u64,
+ frametimes: Vec<f32>,
+}
+
+/// Renders the telemetry HUD into a `HUD_W x HUD_H` RGB dot canvas.
+fn render_hud_canvas(s: &HudSnapshot) -> Canvas {
+ let mut c = Canvas::new(HUD_W, HUD_H, palette::BG);
+ c.stroke_rect(0, 0, HUD_W, HUD_H, palette::BORDER);
+
+ let inner_w = HUD_W - 2 * HUD_PAD;
+ let gib = |bytes: u64| bytes as f64 / (1u64 << 30) as f64;
+
+ // Header: prominent 2x native FPS (+ optional FG) on left, upscaler & console on right.
+ if s.fg_mult > 1 {
+ let left = format!("{:.0} NAT", s.fps);
+ c.text(HUD_PAD, 5, &left, palette::GOLD, 2);
+ let slash_x = HUD_PAD + left.len() as u32 * CELL.0 * 2;
+ c.text(slash_x, 5, "/", palette::DIM, 2);
+ let right = format!("{:.0} FG", s.fps * f64::from(s.fg_mult));
+ c.text(slash_x + CELL.0 * 2, 5, &right, palette::WHITE, 2);
+ } else {
+ let headline = format!("{:.1} NATIVE", s.fps);
+ c.text(HUD_PAD, 5, &headline, palette::GOLD, 2);
+ }
+ let up_w = s.upscaler_tag.len() as u32 * CELL.0;
+ c.text(HUD_W - HUD_PAD - up_w, 5, &s.upscaler_tag, palette::CYAN, 1);
+ let con_w = s.console_tag.len() as u32 * CELL.0;
+ c.text(HUD_W - HUD_PAD - con_w, 14, s.console_tag, palette::DIM, 1);
+
+ // Sub-header lines.
+ let row2 = format!("{}X{} | {:.0} DRAWS | GPU {:.1}MS", s.output.0, s.output.1, s.draws, s.gpu_ms);
+ c.text_rich(HUD_PAD, 24, &row2, palette::WHITE, palette::DIM);
+ let row3 = format!(
+ "FRAME {:.1} | SUB {:.1} | 1% {:.0} | MAX {:.0}",
+ s.frame_ms, s.sub_ms, s.fps_low1, s.fps_max
+ );
+ c.text_rich(HUD_PAD, 34, &row3, palette::WHITE, palette::DIM);
+
+ // Live frametime bar graph.
+ let gx = HUD_PAD;
+ let gy = 45;
+ let gw = inner_w;
+ let gh = 32;
+ c.fill_rect(gx, gy, gw, gh, palette::GRAPH_BG);
+ c.fill_rect(gx, gy, gw, 1, palette::BORDER);
+ c.fill_rect(gx, gy + gh - 1, gw, 1, palette::BORDER);
+
+ let ceil_ms = s
+ .frametimes
+ .iter()
+ .copied()
+ .fold(100.0f32, |acc, v| acc.max(v.min(250.0)));
+ // 50 ms (20 FPS) dotted target guide line.
+ let usable_h = gh - 3;
+ let guide_offset = ((50.0 / ceil_ms).clamp(0.05, 0.95) * usable_h as f32).round() as u32;
+ let guide_y = gy + gh - 2 - guide_offset;
+ for x in (gx + 1..gx + gw - 1).step_by(3) {
+ c.set(x, guide_y, palette::GUIDE);
+ }
+
+ let max_bars = (gw / 2) as usize;
+ let count = s.frametimes.len().min(max_bars);
+ for (i, &dt) in s.frametimes[s.frametimes.len() - count..].iter().enumerate() {
+ let bx = gx + gw - 2 - ((count - 1 - i) as u32) * 2;
+ let frac = (dt / ceil_ms).clamp(0.0, 1.0);
+ let bh = ((frac * usable_h as f32).round() as u32).clamp(1, usable_h);
+ let colour = if dt <= 50.0 {
+ palette::GREEN
+ } else if dt <= 90.0 {
+ palette::AMBER
+ } else {
+ palette::RED
+ };
+ c.fill_rect(bx, gy + gh - 1 - bh, 1, bh, colour);
+ }
+
+ // GPU & VRAM block.
+ c.fill_rect(HUD_PAD, 81, inner_w, 1, palette::BORDER);
+ let val_x = HUD_PAD + 31;
+ let max_val_chars = ((HUD_W - HUD_PAD - val_x) / CELL.0) as usize;
+
+ c.text(HUD_PAD, 85, "GPU", palette::LABEL, 1);
+ let gpu_pct_str = format!(" {:.0}%", s.gpu_pct.clamp(0.0, 100.0));
+ let gpu_name_limit = max_val_chars.saturating_sub(gpu_pct_str.len());
+ let gpu_line = format!(
+ "{}{gpu_pct_str}",
+ &s.gpu_name[..s.gpu_name.len().min(gpu_name_limit)]
+ );
+ c.text(val_x, 85, &gpu_line, palette::WHITE, 1);
+
+ c.text(HUD_PAD, 95, "VRAM", palette::LABEL, 1);
+ let vram1 = format!("LOCAL {:.1} | BUDGET {:.1} GIB", gib(s.vram_used), gib(s.vram_budget));
+ c.text_rich(val_x, 95, &vram1, palette::WHITE, palette::DIM);
+
+ let cap = if s.vram_ded_cap > 0 { s.vram_ded_cap } else { s.vram_budget };
+ let vram2 = format!("DED CAP {:.1} | SHARED {:.1} GIB", gib(cap), gib(s.vram_shared));
+ c.text_rich(val_x, 105, &vram2, palette::WHITE, palette::DIM);
+
+ // CPU & per-core bar strip.
+ c.fill_rect(HUD_PAD, 115, inner_w, 1, palette::BORDER);
+ c.text(HUD_PAD, 119, "CPU", palette::LABEL, 1);
+ let cpu_pct_str = format!(" {:.0}%", s.cpu_pc_pct.clamp(0.0, 100.0));
+ let cpu_name_limit = max_val_chars.saturating_sub(cpu_pct_str.len());
+ let cpu_line = format!(
+ "{}{cpu_pct_str}",
+ &s.cpu_name[..s.cpu_name.len().min(cpu_name_limit)]
+ );
+ c.text(val_x, 119, &cpu_line, palette::WHITE, 1);
+
+ let bar_y = 130;
+ let bar_h = 13;
+ if !s.core_loads.is_empty() {
+ let n = s.core_loads.len().min(32) as u32;
+ let gap = if n <= 16 { 2 } else { 1 };
+ let bar_w = ((inner_w.saturating_sub((n - 1) * gap)) / n).max(3);
+ let used_w = n * bar_w + (n - 1) * gap;
+ let start_x = HUD_PAD + (inner_w.saturating_sub(used_w)) / 2;
+ for (i, &load) in s.core_loads.iter().take(n as usize).enumerate() {
+ let bx = start_x + i as u32 * (bar_w + gap);
+ c.fill_rect(bx, bar_y, bar_w, bar_h, palette::CORE_BG);
+ let frac = load.clamp(0.0, 1.0);
+ let fill = if frac > 0.02 {
+ ((frac * bar_h as f32).round() as u32).clamp(1, bar_h)
+ } else {
+ 0
+ };
+ if fill > 0 {
+ let col = if frac > 0.95 {
+ palette::RED
+ } else if frac > 0.85 {
+ palette::AMBER
+ } else {
+ palette::CORE_FILL
+ };
+ c.fill_rect(bx, bar_y + bar_h - fill, bar_w, fill, col);
+ }
+ }
+ } else {
+ c.fill_rect(HUD_PAD, bar_y, inner_w, bar_h, palette::CORE_BG);
+ let fill = ((s.cpu_pc_pct.clamp(0.0, 100.0) / 100.0) * inner_w as f64).round() as u32;
+ c.fill_rect(HUD_PAD, bar_y, fill.min(inner_w), bar_h, palette::CORE_FILL);
+ }
+
+ // Process & system RAM block.
+ c.fill_rect(HUD_PAD, 147, inner_w, 1, palette::BORDER);
+ c.text(HUD_PAD, 151, "PROC", palette::LABEL, 1);
+ let proc_line = format!("WS {:.1} | CMT {:.1} GIB | DROP {:.0}", gib(s.proc_ws), gib(s.proc_commit), s.dropped);
+ c.text_rich(val_x, 151, &proc_line, palette::WHITE, palette::DIM);
+
+ c.text(HUD_PAD, 161, "RAM", palette::LABEL, 1);
+ let ram_used = s.ram_total.saturating_sub(s.ram_free);
+ let ram_line = format!(
+ "{:.1}/{:.1} GIB | FREE {:.1} GIB",
+ gib(ram_used),
+ gib(s.ram_total),
+ gib(s.ram_free)
+ );
+ c.text_rich(val_x, 161, &ram_line, palette::WHITE, palette::DIM);
+
+ c
+}
+
+/// Renders the top-centre shader compilation banner into a `BANNER_W x BANNER_H` RGB canvas.
+fn render_shader_banner_canvas(left: u64, peak: u64) -> Canvas {
+ let mut c = Canvas::new(BANNER_W, BANNER_H, palette::BG);
+ c.stroke_rect(0, 0, BANNER_W, BANNER_H, palette::AMBER);
+ let title = format!("COMPILING SHADERS: {left} LEFT");
+ c.text(6, 5, &title, palette::GOLD, 1);
+ c.text(6, 15, "PLEASE WAIT - FPS AND LIGHTING SETTLE", palette::DIM, 1);
+ let bar_x = 6;
+ let bar_y = 25;
+ let bar_w = BANNER_W - 12;
+ let bar_h = 4;
+ c.fill_rect(bar_x, bar_y, bar_w, bar_h, palette::CORE_BG);
+ let progress = if peak > 0 {
+ (peak.saturating_sub(left) as f64 / peak as f64).clamp(0.02, 1.0)
} else {
- "RAY TRACING OFF"
+ 0.02
};
- let [cpu, free] = pc_lines(pc);
- vec![
- format!("FPS {fps:.1} FRAME {ms:.1} MS LONGEST {worst:.0}"),
- format!("{console} BUILD {}", env!("VICTORY_BUILD")).to_uppercase(),
- picture,
- upscaler(dlss.map(|(mode, _, _, preset)| (mode, preset))),
- generated(fps, crate::streamline::framegen_reading()),
- rays.to_owned(),
- format!("GPU BUSY {:.1} MS WAITS FOR GPU {:.1}", ms - idle, c[3] / 1e3),
- format!("DRAWS {:.0} DROPPED {:.0}", c[10], c[8]),
- format!("RAM {:.1} GB", gb(private)),
- format!("VRAM {:.1}/{:.1} GB SHARED {:.1}", gb(used), gb(budget), gb(shared)),
- cpu,
- free,
- format!("THIS PANEL {:.0} US A FRAME", cost),
- LEGEND.to_owned(),
- ]
+ let fill = ((progress * bar_w as f64).round() as u32).clamp(2, bar_w);
+ c.fill_rect(bar_x, bar_y, fill, bar_h, palette::AMBER);
+ c
}
-/// The buffers of a box that size and format.
+/// The buffers of a monochrome box that size and format (used by `Notice` and `Advisor`).
struct Buffers {
shape: Shape,
format: DXGI_FORMAT,
@@ -478,27 +1000,204 @@ impl Buffers {
}
}
-/// The panel of a presenter.
+/// GPU upload/default buffer pair for an arbitrary multi-colour [`Canvas`].
+struct ColorBuffers {
+ logical: (u32, u32),
+ format: DXGI_FORMAT,
+ scale: u32,
+ pitch: u32,
+ uploads: Vec<(ID3D12Resource, *mut u8)>,
+ card: ID3D12Resource,
+ turn: usize,
+ fresh: bool,
+}
+
+// SAFETY: free-threaded resources, written only under the presenter's lock.
+unsafe impl Send for ColorBuffers {}
+
+impl ColorBuffers {
+ fn new(host: &Host, logical: (u32, u32), format: DXGI_FORMAT, scale: u32) -> Option<ColorBuffers> {
+ let (_, bpp) = encode_rgb(format, [0, 0, 0])?;
+ let (width, height) = (logical.0 * scale, logical.1 * scale);
+ let pitch = (width * bpp as u32).next_multiple_of(256);
+ let bytes = u64::from(pitch) * u64::from(height);
+ let uploads = (0..UPLOADS).map(|_| host.upload_buffer(bytes)).collect::<Option<Vec<_>>>()?;
+ let heap = D3D12_HEAP_PROPERTIES {
+ Type: D3D12_HEAP_TYPE_DEFAULT,
+ ..Default::default()
+ };
+ let desc = D3D12_RESOURCE_DESC {
+ Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
+ Width: bytes,
+ Height: 1,
+ DepthOrArraySize: 1,
+ MipLevels: 1,
+ SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+ Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
+ ..Default::default()
+ };
+ let mut card: Option<ID3D12Resource> = None;
+ // SAFETY: plain creation of a buffer.
+ unsafe {
+ host.device
+ .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut card)
+ .ok()?;
+ }
+ Some(ColorBuffers { logical, format, scale, pitch, uploads, card: card?, turn: 0, fresh: false })
+ }
+
+ fn pixel_size(&self) -> (u32, u32) {
+ (self.logical.0 * self.scale, self.logical.1 * self.scale)
+ }
+
+ fn write(&mut self, canvas: &Canvas) {
+ let Some(picture) = canvas.encode(self.format, self.scale, self.pitch as usize) else {
+ return;
+ };
+ self.turn = (self.turn + 1) % UPLOADS;
+ // SAFETY: mapped upload buffer sized for `pitch * height`, rotated across `UPLOADS` frames.
+ unsafe { std::ptr::copy_nonoverlapping(picture.as_ptr(), self.uploads[self.turn].1, picture.len()) };
+ self.fresh = true;
+ }
+
+ fn copy(&mut self, list: &ID3D12GraphicsCommandList, back: &ID3D12Resource, at: (u32, u32), (width, height): (u32, u32)) {
+ let (w, h) = self.pixel_size();
+ if at.0 >= width || at.1 >= height {
+ return;
+ }
+ // SAFETY: open command list and live resources; `part` is clamped to the back buffer.
+ unsafe {
+ if std::mem::take(&mut self.fresh) {
+ list.CopyResource(&self.card, &self.uploads[self.turn].0);
+ crate::barstat::rb(list, &[transition(&self.card, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
+ }
+ let from = D3D12_TEXTURE_COPY_LOCATION {
+ pResource: std::mem::transmute_copy(&self.card),
+ Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
+ Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
+ PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
+ Offset: 0,
+ Footprint: D3D12_SUBRESOURCE_FOOTPRINT {
+ Format: self.format,
+ Width: w,
+ Height: h,
+ Depth: 1,
+ RowPitch: self.pitch,
+ },
+ },
+ },
+ };
+ let to = D3D12_TEXTURE_COPY_LOCATION {
+ pResource: std::mem::transmute_copy(back),
+ Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
+ Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 },
+ };
+ let part = D3D12_BOX { left: 0, top: 0, front: 0, right: w.min(width - at.0), bottom: h.min(height - at.1), back: 1 };
+ list.CopyTextureRegion(&to, at.0, at.1, 0, &from, Some(&part));
+ }
+ }
+}
+
+/// Top-centre progress banner shown automatically while pipelines are compiling.
+struct ShaderBanner {
+ last_check: Instant,
+ left: u64,
+ peak: u64,
+ zero_since: Option<Instant>,
+ canvas: Option<Canvas>,
+ changed: bool,
+ buffers: Option<ColorBuffers>,
+ failed: bool,
+}
+
+impl ShaderBanner {
+ fn new() -> ShaderBanner {
+ ShaderBanner {
+ last_check: Instant::now() - EVERY,
+ left: 0,
+ peak: 0,
+ zero_since: None,
+ canvas: None,
+ changed: false,
+ buffers: None,
+ failed: false,
+ }
+ }
+
+ fn poll(&mut self) {
+ if !shader_banner_enabled() || self.failed {
+ return;
+ }
+ let now = Instant::now();
+ if now.duration_since(self.last_check) < Duration::from_millis(250) {
+ return;
+ }
+ self.last_check = now;
+ let left = crate::pipeline::making();
+ if left > 0 {
+ self.zero_since = None;
+ self.peak = self.peak.max(left);
+ if left != self.left || self.canvas.is_none() {
+ self.left = left;
+ self.canvas = Some(render_shader_banner_canvas(left, self.peak));
+ self.changed = true;
+ }
+ } else {
+ self.left = 0;
+ self.canvas = None;
+ let zero_since = *self.zero_since.get_or_insert(now);
+ if now.duration_since(zero_since) >= Duration::from_secs(2) {
+ self.peak = 0;
+ }
+ }
+ }
+
+ fn draw(&mut self, host: &Host, list: &HostList, back: &ID3D12Resource, (width, height): (u32, u32), format: DXGI_FORMAT) {
+ if self.left == 0 || self.failed {
+ return;
+ }
+ let Some(canvas) = &self.canvas else { return };
+ #[cfg(feature = "diagnostics")]
+ let _ours = crate::replay::record::unrecorded();
+ let scale = hud_scale(height);
+ if self.buffers.as_ref().is_none_or(|b| (b.format, b.scale) != (format, scale)) {
+ std::mem::forget(self.buffers.take());
+ self.buffers = ColorBuffers::new(host, (BANNER_W, BANNER_H), format, scale);
+ self.failed = self.buffers.is_none();
+ self.changed = true;
+ }
+ let Some(buffers) = &mut self.buffers else { return };
+ if std::mem::take(&mut self.changed) {
+ buffers.write(canvas);
+ }
+ let (w, _) = buffers.pixel_size();
+ let at = (width.saturating_sub(w) / 2, 8 * scale);
+ buffers.copy(&list.list, back, at, (width, height));
+ }
+}
+
+/// The telemetry panel of a presenter.
pub(super) struct Panel {
since: Instant,
frames: u32,
last: Instant,
- worst: f64,
- /// What this took since the last text.
- cost: Duration,
before: Counters,
- lines: Vec<String>,
+ canvas: Option<Canvas>,
changed: bool,
- buffers: Option<Buffers>,
+ buffers: Option<ColorBuffers>,
failed: bool,
/// The picture the failed buffers were for: a change of it tries again.
failed_at: Option<(DXGI_FORMAT, u32)>,
/// The picture's size, as the last draw had it.
output: (u32, u32),
- /// The graphs' samples, 0 to 1 of their scales ([`GRAPHS`]).
- history: Vec<Vec<f32>>,
- /// [`cpu_times`] at the last text, and when.
+ /// Per-frame durations (ms) for the live frametime bar graph and 1% low / max FPS.
+ frametimes: VecDeque<f32>,
+ /// [`cpu_times`] at the last sample, and when.
cpu: Option<((u64, u64, u64), Instant)>,
+ /// Last per-core `(idle, total)` ticks from `NtQuerySystemInformation`.
+ core_prev: Option<Vec<(i64, i64)>>,
+ /// Automatic shader compilation banner at top-centre.
+ shader_banner: ShaderBanner,
}
impl Panel {
@@ -509,62 +1208,46 @@ impl Panel {
since: now,
frames: 0,
last: now,
- worst: 0.0,
- cost: Duration::ZERO,
before: Counters::default(),
- lines: Vec::new(),
+ canvas: None,
changed: false,
buffers: None,
failed: false,
failed_at: None,
output: (0, 0),
- history: vec![Vec::new(); GRAPHS as usize],
+ frametimes: VecDeque::with_capacity(FRAMETIME_HISTORY),
cpu: None,
+ core_prev: None,
+ shader_banner: ShaderBanner::new(),
}
}
- /// The PC's numbers now, and a sample for each graph.
- fn sample(&mut self, fps: f64, host: &Host) -> Pc {
- let now = (cpu_times(), Instant::now());
- let cores = std::thread::available_parallelism().map_or(1, |n| n.get()) as f64;
- let (cpu_game, cpu_pc) = match self.cpu.replace(now) {
- Some((before, at)) => cpu_percent(before, now.0, (now.1 - at).as_secs_f64(), cores),
- None => (0.0, 0.0),
- };
- let (free, total, commit_left) = pc_memory();
- let (_, private) = process_memory();
- let [budget, used, ..] = host.video_memory().unwrap_or_default();
- let ratio = |a: u64, b: u64| if b == 0 { 0.0 } else { a as f32 / b as f32 };
- let samples = [(fps / 60.0) as f32, (cpu_game / 100.0) as f32, ratio(private, total), ratio(used, budget)];
- for (graph, sample) in self.history.iter_mut().zip(samples) {
- if graph.len() == HISTORY {
- graph.remove(0);
- }
- graph.push(sample);
- }
- Pc { cpu_game, cpu_pc, free, total, commit_left }
- }
-
/// A frame was presented; `line`: the counters go back to 0 right behind
- /// this call. (Not shown it asks for the key's state and no more.)
+ /// this call. (Not shown it asks for the key's state and shader queue only.)
pub(super) fn frame(&mut self, line: bool) {
if let Some(kind) = flush_pressed() {
crate::resource::ask_flush(kind);
}
+ if pressed() {
+ shown().fetch_xor(true, Ordering::Relaxed);
+ }
+ self.shader_banner.poll();
if !shown().load(Ordering::Relaxed) {
self.frames = 0;
return;
}
let now = Instant::now();
if self.frames == 0 {
- // Shown from here on, whatever the hidden gap was: a window
- // that keeps it in `since` and `last` prints the gap as a
- // frame time (the panel re-shown within a second printed
- // about a second a frame) and spreads the counters over it.
- (self.since, self.last, self.worst, self.before) = (now, now, 0.0, Counters::now());
+ (self.since, self.last, self.before) = (now, now, Counters::now());
+ }
+ let dt_ms = (now - self.last).as_secs_f64() * 1e3;
+ if dt_ms > 0.2 && dt_ms < 5_000.0 {
+ if self.frametimes.len() == FRAMETIME_HISTORY {
+ self.frametimes.pop_front();
+ }
+ self.frametimes.push_back(dt_ms as f32);
}
self.frames += 1;
- self.worst = self.worst.max((now - self.last).as_secs_f64() * 1e3);
self.last = now;
let elapsed = now - self.since;
if elapsed < EVERY && !(line && elapsed * 2 >= EVERY) {
@@ -575,17 +1258,76 @@ impl Panel {
let counters = Counters::now();
let c = counters.since(self.before, frames);
self.before = counters;
- let cost = self.cost.as_secs_f64() * 1e6 / frames;
let ms = elapsed.as_secs_f64() * 1e3 / frames;
- let pc = self.sample(1e3 / ms.max(0.001), host);
- self.lines = text(&c, ms, self.worst, cost, pc, self.output, host);
+ let fps = 1e3 / ms.max(0.001);
+ let (fps_low1, fps_max) = frametime_stats(&self.frametimes, fps);
+
+ let idle_ms = (c[1] / 1e3).min(ms);
+ let gpu_ms = (ms - idle_ms).max(0.0);
+ let gpu_pct = (gpu_ms / ms.max(0.001) * 100.0).clamp(0.0, 100.0);
+ let sub_ms = (c[11] / 1e3).max(0.0);
+
+ let now_cpu = (cpu_times(), Instant::now());
+ let cores = std::thread::available_parallelism().map_or(1, |n| n.get()) as f64;
+ let (_, cpu_pc_pct) = match self.cpu.replace(now_cpu) {
+ Some((before, at)) => cpu_percent(before, now_cpu.0, (now_cpu.1 - at).as_secs_f64(), cores),
+ None => (0.0, 0.0),
+ };
+ let core_loads = match per_core_times() {
+ Some(now_cores) => match self.core_prev.replace(now_cores) {
+ Some(prev) => {
+ let current = self.core_prev.as_deref().unwrap_or(&[]);
+ core_busy_fractions(&prev, current)
+ }
+ None => Vec::new(),
+ },
+ None => Vec::new(),
+ };
+
+ let (ram_free, ram_total, _) = pc_memory();
+ let (proc_ws, proc_commit) = process_memory();
+ let [vram_budget, vram_used, _, vram_shared] = host.video_memory().unwrap_or_default();
+ let (gpu_name, vram_ded_cap) = adapter_info(host);
+ let dlss = crate::streamline::upscaled_lately().map(|(mode, _, _, preset)| (mode, preset));
+ let console_tag = match crate::console::current() {
+ crate::console::Console::SeriesS => "SERIES S",
+ crate::console::Console::SeriesX => "SERIES X",
+ };
+ let snapshot = HudSnapshot {
+ fps,
+ fg_mult: crate::streamline::shown_per_frame(),
+ upscaler_tag: short_upscaler(dlss),
+ console_tag,
+ output: self.output,
+ draws: c[10],
+ dropped: c[8],
+ frame_ms: ms,
+ sub_ms,
+ gpu_ms,
+ fps_low1,
+ fps_max,
+ gpu_name: gpu_name.to_owned(),
+ gpu_pct,
+ vram_used,
+ vram_budget,
+ vram_ded_cap,
+ vram_shared,
+ cpu_name: cpu_brand().to_owned(),
+ cpu_pc_pct,
+ core_loads,
+ proc_ws,
+ proc_commit,
+ ram_free,
+ ram_total,
+ frametimes: self.frametimes.iter().copied().collect(),
+ };
+ self.canvas = Some(render_hud_canvas(&snapshot));
self.changed = true;
- (self.since, self.frames, self.worst) = (now, 0, 0.0);
- self.cost = now.elapsed();
+ (self.since, self.frames) = (now, 0);
}
- /// Records the copy of the box onto `back`, a buffer of the swap chain of
- /// that size and format in the state to be copied into.
+ /// Records the copy of the HUD (upper-right) and shader banner (top-centre)
+ /// onto `back`, a swap chain back buffer in `COPY_DEST` state.
pub(super) fn draw(
&mut self,
host: &Host,
@@ -594,34 +1336,34 @@ impl Panel {
(width, height): (u32, u32),
format: DXGI_FORMAT,
) {
- // A failed making of the buffers gives up on this picture only: a
- // resize (or a format change) tries again.
- let scale = scale(height);
+ self.output = (width, height);
+ self.shader_banner.draw(host, list, back, (width, height), format);
+ let scale = hud_scale(height);
if self.failed && self.failed_at == Some((format, scale)) {
return;
}
- if !shown().load(Ordering::Relaxed) || self.lines.is_empty() {
+ if !shown().load(Ordering::Relaxed) {
return;
}
- let began = Instant::now();
- self.output = (width, height);
+ let Some(canvas) = &self.canvas else { return };
// Not the title's: the frame recorder leaves it out.
#[cfg(feature = "diagnostics")]
let _ours = crate::replay::record::unrecorded();
if self.buffers.as_ref().is_none_or(|b| (b.format, b.scale) != (format, scale)) {
// (What the card may still read stays: a picture's size changes once or twice in a run.)
std::mem::forget(self.buffers.take());
- self.buffers = Buffers::new(host, PANEL, format, scale);
+ self.buffers = ColorBuffers::new(host, (HUD_W, HUD_H), format, scale);
self.failed = self.buffers.is_none();
self.failed_at = self.failed.then_some((format, scale));
self.changed = true;
}
let Some(buffers) = &mut self.buffers else { return };
if std::mem::take(&mut self.changed) {
- buffers.write(&self.lines, &self.history);
+ buffers.write(canvas);
}
- buffers.copy(&list.list, back, (0, 0), (width, height));
- self.cost += began.elapsed();
+ let (w, _) = buffers.pixel_size();
+ let at = (width.saturating_sub(w), 0);
+ buffers.copy(&list.list, back, at, (width, height));
}
}
@@ -1000,7 +1742,7 @@ mod tests {
/// alike.
#[test]
fn characters_differ() {
- let used: Vec<u8> = (b'0'..=b'9').chain(b'A'..=b'Z').chain(*b"./- %:").collect();
+ let used: Vec<u8> = (b'0'..=b'9').chain(b'A'..=b'Z').chain(*b"./- %:|").collect();
for (i, a) in used.iter().enumerate() {
assert_ne!(glyph(*a), glyph(b'#'), "{} has a picture", *a as char);
assert!(glyph(*a).iter().all(|row| row >> GLYPH.0 == 0));
@@ -1063,23 +1805,16 @@ mod tests {
let top = RIM + LINES * CELL.1;
let right = RIM + COLUMNS * CELL.0 - 1;
let at = |x: u32, y: u32| lit(&lines, &graphs, PANEL, x, y);
- // First graph, newest sample 1.0: lit from its top down.
assert!(at(right, top));
assert!(at(right, top + GRAPH - 2));
- // The one before it, 0.0: dark above the bottom line.
assert!(!at(right - 1, top));
assert!(!at(right - 1, top + GRAPH - 2));
- // No sample further left: dark.
assert!(!at(right - 5, top + GRAPH - 2));
- // The bottom line is dotted.
assert_ne!(at(RIM, top + GRAPH - 1), at(RIM + 1, top + GRAPH - 1));
- // Second graph, 0.5: dark at its top, lit near its bottom.
let second = top + GRAPH + GRAPH_GAP;
assert!(!at(right, second));
assert!(at(right, second + GRAPH - 3));
- // The gap between graphs is dark.
assert!(!at(right, top + GRAPH));
- // The box holds the graphs.
let (_, height) = size(PANEL, 1);
assert_eq!(height, top + GRAPHS * (GRAPH + GRAPH_GAP) + RIM);
}
@@ -1088,8 +1823,6 @@ mod tests {
/// busy time.
#[test]
fn cpu_use_is_told_in_percent() {
- // One second on 4 processors; the game used 2 s of CPU; the PC was
- // idle 1 s of 4.
let (game, pc) = cpu_percent((0, 0, 0), (20_000_000, 10_000_000, 40_000_000), 1.0, 4.0);
assert!((game - 50.0).abs() < 1e-6);
assert!((pc - 75.0).abs() < 1e-6);
@@ -1114,6 +1847,78 @@ mod tests {
assert_eq!((c[0], c[1]), (2.0, 2.0));
}
+ #[test]
+ fn hardware_names_and_per_core_busy_are_clean() {
+ assert_eq!(clean_hardware_name("AMD Ryzen 5 5600GT with Radeon Graphics", 30), "AMD RYZEN 5 5600GT");
+ assert_eq!(clean_hardware_name("Intel(R) Core(TM) i5-10400F CPU @ 2.90GHz", 30), "INTEL CORE I5-10400F");
+ assert_eq!(clean_hardware_name("NVIDIA GeForce RTX 3060", 30), "NVIDIA GEFORCE RTX 3060");
+ let busy = core_busy_fractions(&[(100, 200), (50, 150)], &[(125, 300), (150, 250)]);
+ assert!((busy[0] - 0.75).abs() < 1e-5);
+ assert!((busy[1] - 0.0).abs() < 1e-5);
+ assert_eq!(size_of::<SystemProcessorPerformanceInfo>(), 48);
+ }
+
+ #[test]
+ fn frametime_stats_and_hud_canvas_encode_cleanly() {
+ let mut samples = VecDeque::new();
+ for _ in 0..95 {
+ samples.push_back(50.0);
+ }
+ for _ in 0..5 {
+ samples.push_back(100.0);
+ }
+ let (low1, max_fps) = frametime_stats(&samples, 18.0);
+ assert!((low1 - 10.0).abs() < 0.5, "low1={low1}");
+ assert!((max_fps - 20.0).abs() < 0.5, "max={max_fps}");
+
+ let snap = HudSnapshot {
+ fps: 15.4,
+ fg_mult: 1,
+ upscaler_tag: short_upscaler(Some(("performance", Some('K')))),
+ console_tag: "SERIES S",
+ output: (1920, 1080),
+ draws: 1842.0,
+ dropped: 0.0,
+ frame_ms: 64.9,
+ sub_ms: 46.2,
+ gpu_ms: 40.5,
+ fps_low1: 11.0,
+ fps_max: 18.0,
+ gpu_name: "NVIDIA GEFORCE RTX 3060".to_owned(),
+ gpu_pct: 62.0,
+ vram_used: 7_900_000_000,
+ vram_budget: 12_000_000_000,
+ vram_ded_cap: 12_884_901_888,
+ vram_shared: 1_500_000_000,
+ cpu_name: "AMD RYZEN 5 5600GT".to_owned(),
+ cpu_pc_pct: 78.0,
+ core_loads: vec![0.4, 0.7, 0.9, 0.98, 0.5, 0.6, 0.3, 0.8, 0.55, 0.45, 0.72, 0.66],
+ proc_ws: 5_500_000_000,
+ proc_commit: 15_500_000_000,
+ ram_free: 10_400_000_000,
+ ram_total: 25_600_000_000,
+ frametimes: samples.into_iter().collect(),
+ };
+ let canvas = render_hud_canvas(&snap);
+ assert_eq!(canvas.dots[0], palette::BORDER);
+ assert_eq!(canvas.dots[(HUD_W + 1) as usize], palette::BG);
+ for fmt in [
+ DXGI_FORMAT_R8G8B8A8_UNORM,
+ DXGI_FORMAT_B8G8R8A8_UNORM,
+ DXGI_FORMAT_R10G10B10A2_UNORM,
+ DXGI_FORMAT_R16G16B16A16_FLOAT,
+ ] {
+ let (_, bpp) = encode_rgb(fmt, [0, 0, 0]).unwrap();
+ let pitch = ((HUD_W * 2) * bpp as u32).next_multiple_of(256) as usize;
+ let bytes = canvas.encode(fmt, 2, pitch).unwrap();
+ assert_eq!(bytes.len(), pitch * (HUD_H * 2) as usize);
+ }
+
+ let banner = render_shader_banner_canvas(1713, 2000);
+ assert_eq!(banner.dots[0], palette::AMBER);
+ assert_eq!(banner.dots[(BANNER_W + 1) as usize], palette::BG);
+ }
+
#[test]
fn the_advisor_names_what_limits_the_frame_rate() {
let base = Sample {
diff --git a/crates/victory-gpu/src/host/send.rs b/crates/victory-gpu/src/host/send.rs
index a5ce5a0..ee392be 100644
--- a/crates/victory-gpu/src/host/send.rs
+++ b/crates/victory-gpu/src/host/send.rs
@@ -176,6 +176,11 @@ fn kept() -> u64 {
}
}
+/// The bytes [`SPARE`] keeps.
+pub(super) fn spare_bytes() -> u64 {
+ SPARE.lock().unwrap_or_else(|e| e.into_inner()).iter().map(|m| m.size).sum()
+}
+
/// Under host memory pressure the spares go down to a hot floor, all gone
/// when commit is critical (as the copy sources' spares are, `spare_trim_to`
/// in `host.rs`). The sweep calls this with the others.
@@ -583,56 +588,136 @@ pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc<Shadow>, crate::shadow:
}
let memory = memory(host, summary.used)?;
scratch.0.moves.reserve(plan.runs.len());
+ let mut title_moves: Vec<(usize, usize, usize)> = Vec::new();
for ((shadow, _), copy) in dirty.iter().zip(&plan.copies) {
let copy_runs = plan.copy_runs(copy);
if !copy_runs.is_empty() {
- let from = shadow.card_data() as usize;
- scratch.0.moves.extend(copy_runs.iter().map(|&(a, to, n)| (from + a, memory.data + to as usize, n)));
+ let ptr = shadow.card_data();
+ let from_title = ptr.is_null();
+ let from = if from_title { shadow.span().0 as usize } else { ptr as usize };
+ if from_title {
+ title_moves.extend(copy_runs.iter().map(|&(a, to, n)| (from + a, memory.data + to as usize, n)));
+ } else {
+ scratch.0.moves.extend(copy_runs.iter().map(|&(a, to, n)| (from + a, memory.data + to as usize, n)));
+ }
}
}
let chunk_plans = &scratch.0.chunk_plans;
let copies = &plan.copies;
let run_scatter = |i: usize| {
+ const BURST: usize = 64;
let (dirty_idx, start, end, rel_bytes) = chunk_plans[i];
let (shadow, ranges) = &dirty[dirty_idx];
- let from = shadow.card_data() as usize;
+ let ptr = shadow.card_data();
+ let from_title = ptr.is_null();
+ let from = if from_title { shadow.span().0 as usize } else { ptr as usize };
let to = memory.data + copies[dirty_idx].pairs.0 as usize + rel_bytes as usize;
let mut to = to as *mut [u32; 2];
- for &(a, b) in ranges[start..end].iter().filter(|&&(a, b)| short(a, b - a)) {
+ let mut stage = [[0u32; 2]; BURST];
+ let mut staged = 0usize;
+ let flush = |to: &mut *mut [u32; 2], stage: &[[u32; 2]; BURST], staged: &mut usize| {
+ if *staged > 0 {
+ // SAFETY: caller pre-sized `memory` for every pair in this chunk.
+ unsafe {
+ std::ptr::copy_nonoverlapping(stage.as_ptr(), *to, *staged);
+ *to = to.add(*staged);
+ }
+ *staged = 0;
+ }
+ };
+ let mut buf = [0u8; SHORT];
+ let mut page_base = usize::MAX;
+ let mut page_buf = [0u8; 4096];
+ let mut short_iter = ranges[start..end].iter().copied().filter(|&(a, b)| short(a, b - a)).peekable();
+ while let Some((a, b)) = short_iter.next() {
+ if from_title {
+ let len = b - a;
+ let src_addr = from + a;
+ let base = src_addr & !4095;
+ let off = src_addr - base;
+ let slice: &[u8] = if off + len <= 4096 {
+ let cached = page_base == base;
+ let same_next = !cached
+ && short_iter
+ .peek()
+ .is_some_and(|&(na, nb)| ((from + na) & !4095) == base && ((from + na) - base) + (nb - na) <= 4096);
+ if cached {
+ &page_buf[off..off + len]
+ } else if same_next {
+ if !crate::host::read_into(base as *const u8, &mut page_buf) {
+ page_buf.fill(0);
+ }
+ page_base = base;
+ &page_buf[off..off + len]
+ } else {
+ if !crate::host::read_into(src_addr as *const u8, &mut buf[..len]) {
+ buf[..len].fill(0);
+ }
+ &buf[..len]
+ }
+ } else {
+ buf[..len].fill(0);
+ crate::host::copy_mapped(buf.as_mut_ptr(), src_addr as *const u8, len, false);
+ &buf[..len]
+ };
+ for (offset, bytes) in (a..b).step_by(4).zip(slice.chunks_exact(4)) {
+ let word = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
+ stage[staged] = [offset as u32, word];
+ staged += 1;
+ if staged == BURST {
+ flush(&mut to, &stage, &mut staged);
+ }
+ }
+ continue;
+ }
for offset in (a..b).step_by(4) {
// SAFETY: inside the copy's mapping (its CPU side, which
// the thread that asked, and waits, alone writes in these
// ranges) and inside the memory, which has room for every
// pair, a piece of work's behind the last one's.
- unsafe {
- let word = ((from + offset) as *const u32).read_unaligned();
- to.write([offset as u32, word]);
- to = to.add(1);
+ let word = unsafe { ((from + offset) as *const u32).read_unaligned() };
+ stage[staged] = [offset as u32, word];
+ staged += 1;
+ if staged == BURST {
+ flush(&mut to, &stage, &mut staged);
}
}
}
+ flush(&mut to, &stage, &mut staged);
};
STATS[0].fetch_add(summary.total_run_bytes, Ordering::Relaxed);
- STATS[1].fetch_add(scratch.0.moves.len() as u64, Ordering::Relaxed);
+ let total_move_count = scratch.0.moves.len() + title_moves.len();
+ STATS[1].fetch_add(total_move_count as u64, Ordering::Relaxed);
let beside = beside();
- let parallelize_copies = parallel_copy_work(beside, scratch.0.moves.len(), summary.total_run_bytes, !chunk_plans.is_empty());
+ let parallelize_copies = parallel_copy_work(beside, total_move_count, summary.total_run_bytes, !chunk_plans.is_empty());
let mut copying = None;
if parallelize_copies {
pack_copy_tasks_into(&scratch.0.moves, &mut scratch.0.copy_pieces, &mut scratch.0.copy_tasks);
+ let mut title_pieces = Vec::new();
+ let mut title_tasks = Vec::new();
+ if !title_moves.is_empty() {
+ pack_copy_tasks_into(&title_moves, &mut title_pieces, &mut title_tasks);
+ }
let copy_pieces = &scratch.0.copy_pieces;
let copy_tasks = &scratch.0.copy_tasks;
let n_scatter = chunk_plans.len();
- let total_tasks = n_scatter + copy_tasks.len();
+ let n_copy = copy_tasks.len();
+ let total_tasks = n_scatter + n_copy + title_tasks.len();
let one = |i: usize| {
if i < n_scatter {
run_scatter(i);
- } else {
+ } else if i < n_scatter + n_copy {
let (lo, hi) = copy_tasks[i - n_scatter];
for &(from, to, len) in &copy_pieces[lo..hi] {
// SAFETY: disjoint non-overlapping destination slices in
// `memory.data` and read-only CPU-side source mappings.
unsafe { std::ptr::copy_nonoverlapping(from as *const u8, to as *mut u8, len) };
}
+ } else {
+ let (lo, hi) = title_tasks[i - n_scatter - n_copy];
+ for &(from, to, len) in &title_pieces[lo..hi] {
+ crate::host::copy_mapped(to as *mut u8, from as *const u8, len, false);
+ }
}
};
if total_tasks > 1 {
@@ -649,12 +734,15 @@ pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc<Shadow>, crate::shadow:
}
}
if beside {
- copying = Some(crate::shadow::copy_beside(std::mem::take(&mut scratch.0.moves)));
+ copying = Some(crate::shadow::copy_beside_mixed(std::mem::take(&mut scratch.0.moves), title_moves));
} else {
for &(from, to, len) in &scratch.0.moves {
// SAFETY: inside the CPU-side mapping and `memory.data`.
unsafe { std::ptr::copy_nonoverlapping(from as *const u8, to as *mut u8, len) };
}
+ for &(from, to, len) in &title_moves {
+ crate::host::copy_mapped(to as *mut u8, from as *const u8, len, false);
+ }
}
}
STATS[2].fetch_add(summary.total_pair_words, Ordering::Relaxed);
diff --git a/crates/victory-gpu/src/land.rs b/crates/victory-gpu/src/land.rs
index 8e0a942..9217b60 100644
--- a/crates/victory-gpu/src/land.rs
+++ b/crates/victory-gpu/src/land.rs
@@ -52,7 +52,13 @@ fn threads() -> usize {
static THREADS: OnceLock<usize> = OnceLock::new();
*THREADS.get_or_init(|| {
let asked = std::env::var("VICTORY_LAND_THREADS").ok().and_then(|v| v.trim().parse().ok());
- asked.unwrap_or_else(|| std::thread::available_parallelism().map_or(2, |n| n.get() / 4).clamp(1, 4)).clamp(1, 16)
+ asked
+ .unwrap_or_else(|| {
+ let logical = std::thread::available_parallelism().map_or(2, |n| n.get() / 4).clamp(1, 4);
+ // `VICTORY_THREADS_BY_CORES=1`: a third of the physical cores, rounded up, 1 to 4.
+ crate::cores::sized("victory-land", logical, |cores| cores.div_ceil(3).clamp(1, 4))
+ })
+ .clamp(1, 16)
})
}
@@ -360,7 +366,10 @@ pub(crate) fn each(count: usize, f: &(dyn Fn(usize) + Sync)) {
pub(crate) fn each_under(count: usize, f: &(dyn Fn(usize) + Sync)) {
static POOL: OnceLock<&'static Pool> = OnceLock::new();
POOL.get_or_init(|| {
- let threads = std::env::var("VICTORY_UNDER_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(6usize);
+ let threads = std::env::var("VICTORY_UNDER_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or_else(|| {
+ // `VICTORY_THREADS_BY_CORES=1`: half the physical cores and this one, 2 to 6.
+ crate::cores::sized("victory-under", 6usize, |cores| (cores / 2 + 1).clamp(2, 6))
+ });
Pool::new("victory-under", threads.clamp(1, 16))
})
.each(count, f);
@@ -375,7 +384,15 @@ pub(crate) fn each_view(records: bool, count: usize, f: &(dyn Fn(usize) + Sync))
static POOLS: [OnceLock<&'static Pool>; 2] = [const { OnceLock::new() }; 2];
POOLS[usize::from(records)]
.get_or_init(|| {
- let threads = std::env::var("VICTORY_VIEW_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(if records { 6usize } else { 4 });
+ let threads = std::env::var("VICTORY_VIEW_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or_else(|| {
+ // `VICTORY_THREADS_BY_CORES=1`: half the physical cores and this one (records, 2 to 6),
+ // half of them (views, 2 to 4).
+ if records {
+ crate::cores::sized("victory-records", 6usize, |cores| (cores / 2 + 1).clamp(2, 6))
+ } else {
+ crate::cores::sized("victory-views", 4usize, |cores| (cores / 2).clamp(2, 4))
+ }
+ });
Pool::new(if records { "victory-records" } else { "victory-views" }, threads.clamp(1, 16))
})
.each(count, f);
diff --git a/crates/victory-gpu/src/list/thin.rs b/crates/victory-gpu/src/list/thin.rs
index 786aae6..1f976aa 100644
--- a/crates/victory-gpu/src/list/thin.rs
+++ b/crates/victory-gpu/src/list/thin.rs
@@ -488,17 +488,31 @@ fn back_list(kind: u32) -> This {
list
}
+/// `VICTORY_THIN_THREADS`: a number (1 to 32), or `auto`, the physical cores
+/// but two, at least two (the submitting thread and the title's recording
+/// keep the rest); unset, 8 as before. `auto` on 6 cores is 4: with about
+/// 300 ms of translation a frame (81,000 calls at 3.5-4 us) that is 75 ms a
+/// frame on each, which puts translation on the frame's path once the
+/// submitting thread is faster, so it is not the default.
+fn threads_for(asked: Option<&str>, physical: impl FnOnce() -> usize) -> usize {
+ match asked.map(str::trim) {
+ Some("auto") => physical().saturating_sub(2).clamp(2, 32),
+ Some(v) => v.parse().ok().unwrap_or(8usize).clamp(1, 32),
+ None => 8,
+ }
+}
+
fn start() {
- // Cap default workers at half the logical processors (2..=8) so 8-vCPU
- // machines are not oversubscribed while 16+-vCPU rigs keep 8 workers.
+ // An explicit `VICTORY_THIN_THREADS` (a number, or `auto`) wins; else
+ // `VICTORY_THREADS_BY_CORES=1`: one a physical core, 2 to 8.
+ let asked = std::env::var("VICTORY_THIN_THREADS").ok();
let default_threads = std::thread::available_parallelism()
.map(|n| (n.get() / 2).clamp(2, 8))
.unwrap_or(4);
- let threads = std::env::var("VICTORY_THIN_THREADS")
- .ok()
- .and_then(|v| v.trim().parse().ok())
- .unwrap_or(default_threads)
- .clamp(1, 32);
+ let threads = match asked.as_deref() {
+ None => crate::cores::sized("victory-list", default_threads, |cores| cores.clamp(2, 8)),
+ asked => threads_for(asked, crate::cores::physical_cores),
+ };
for i in 0..threads {
let worker = move || {
crate::cores::keep_list_worker("victory-list");
@@ -523,7 +537,11 @@ fn start() {
tracing::warn!(error = %e, "a thread less to translate lists");
}
}
- tracing::info!(threads, "list calls are written down and translated by threads of ours (VICTORY_THIN=1)");
+ tracing::info!(
+ threads,
+ asked = asked.as_deref().unwrap_or("unset"),
+ "list calls are written down and translated by threads of ours (VICTORY_THIN=1; VICTORY_THIN_THREADS=auto: physical cores but two)"
+ );
}
/// The recordings of submitted lists, in order (one that was not begun is left
@@ -1546,6 +1564,17 @@ mod tests {
worker.join().unwrap();
}
+ #[test]
+ fn threads_by_cores() {
+ assert_eq!(super::threads_for(None, || 6), 8);
+ assert_eq!(super::threads_for(Some("auto"), || 6), 4);
+ assert_eq!(super::threads_for(Some(" auto "), || 2), 2);
+ assert_eq!(super::threads_for(Some("auto"), || 0), 2);
+ assert_eq!(super::threads_for(Some("12"), || 6), 12);
+ assert_eq!(super::threads_for(Some("bad"), || 6), 8);
+ assert_eq!(super::threads_for(Some("99"), || 6), 32);
+ }
+
/// Every method of the tables that records is written down too: what is
/// left in both tables alike records nothing.
#[test]
diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs
index 46222dc..b18255c 100644
--- a/crates/victory-gpu/src/pipeline.rs
+++ b/crates/victory-gpu/src/pipeline.rs
@@ -599,7 +599,12 @@ pub(crate) fn host_pipeline_masked<'a>(this: This) -> Option<&'a host::HostPipel
let mut shaders = p.shaders.clone();
shaders[ps] = shaders[ps].masked();
let graphics = p.host.graphics.as_deref().map(|g| Box::new(g.clone()));
- Some(Arc::new(make::Pending::new(shaders, graphics)))
+ // Booked and adopted like the plain pipeline (`hand_out`), so
+ // `warm --used` and the prefetch make the twin too, and a draw
+ // takes the one the prefetch started (#3860).
+ let masked = make::adopt(make::Pending::new(shaders.clone(), graphics));
+ known::note(masked.key(), &shaders, masked.graphics.as_deref());
+ Some(masked)
})
.as_ref()?;
make::made_or_start(masked)
diff --git a/crates/victory-gpu/src/pipeline/known.rs b/crates/victory-gpu/src/pipeline/known.rs
index d3a8428..ea4d60e 100644
--- a/crates/victory-gpu/src/pipeline/known.rs
+++ b/crates/victory-gpu/src/pipeline/known.rs
@@ -17,6 +17,12 @@
//! `known-pipelines.bin` (length, then the key, the shaders' stages and
//! hashes, and the graphics state). They hold the title's own code: they stay
//! in the cache folder.
+//!
+//! A pixel shader's masked twin (`Shader::masked`, drawn under the console's
+//! sample mask) shares its plain shader's container, so the shaders file has
+//! it once under the plain stage; a pipeline entry marks it with `MASKED`
+//! in its stage byte (#3860). A build from before that bit skips such an
+//! entry alone, by the stage table's bounds, and reads the rest.
use std::collections::{HashMap, HashSet, VecDeque};
use std::ffi::CString;
@@ -36,6 +42,8 @@ const PIPELINES: &str = "known-pipelines.bin";
/// Stages by their number in the files.
const STAGES: [&str; 8] =
["vertex", "pixel", "domain", "hull", "geometry", "compute", "amplification", "mesh"];
+/// Set in a pipeline entry's stage byte for a pixel shader's masked twin.
+const MASKED: u8 = 0x80;
/// `VICTORY_PIPELINE_BOOK=1`: the pipelines the title creates are kept.
fn on() -> bool {
@@ -122,7 +130,6 @@ impl Book {
}
prepared.push((hash, stage, new));
}
-
// Budget rejection leaves both deduplication sets untouched so
// the same pipeline can be noted again after the queue drains.
self.keys.insert(id);
@@ -134,7 +141,7 @@ impl Book {
pending.pipeline.extend(id);
pending.pipeline.push(shaders.len() as u8);
for (shader, (hash, stage, new)) in shaders.iter().zip(prepared) {
- pending.pipeline.push(stage);
+ pending.pipeline.push(stage | if shader.masked { MASKED } else { 0 });
pending.pipeline.extend(hash);
if new {
self.shaders.insert(hash);
@@ -606,7 +613,13 @@ fn parse(
rest = after;
let mut hash = [0; 32];
hash.copy_from_slice(&head[1..]);
- shaders.push(super::shader(STAGES.get(usize::from(head[0]))?, &read(&hash)?));
+ let (stage, masked) = (*STAGES.get(usize::from(head[0] & !MASKED))?, head[0] & MASKED != 0);
+ // Only a pixel shader has a masked twin: the bit elsewhere is not this build's.
+ if masked && stage != "pixel" {
+ return None;
+ }
+ let shader = super::shader(stage, &read(&hash)?);
+ shaders.push(if masked { shader.masked() } else { shader });
}
let (&graphics, rest) = rest.split_first()?;
let g = match graphics {
@@ -1192,4 +1205,86 @@ mod tests {
assert_eq!(locked.pending_bytes, 0);
let _ = std::fs::remove_dir_all(&dir);
}
+
+ /// The key a run gives these shaders (`graphics`: under the default state).
+ fn key_of(shaders: &[Arc<Shader>], graphics: bool) -> String {
+ let g = graphics.then(|| Box::new(GraphicsState::default()));
+ super::super::make::Pending::new(shaders.to_vec(), g).key().to_owned()
+ }
+
+ /// The keys of what `recipes` reads back for every key in `dir`, in order.
+ fn read_back(dir: &Path) -> Vec<String> {
+ let wanted: HashSet<String> = keys(dir).into_iter().collect();
+ recipes(dir, &wanted)
+ .into_iter()
+ .map(|(shaders, g)| super::super::make::Pending::new(shaders, g).key().to_owned())
+ .collect()
+ }
+
+ fn id(key: &str) -> [u8; 16] {
+ std::array::from_fn(|at| u8::from_str_radix(&key[2 * at..2 * at + 2], 16).unwrap())
+ }
+
+ /// A pipeline drawn under the console's sample mask (its pixel shader's
+ /// twin) noted next to its plain pipeline comes back from the files as
+ /// itself, in either order, with the container written once under the
+ /// plain stage (#3860).
+ #[test]
+ fn a_masked_twin_comes_back_masked() {
+ let sh = super::super::shader;
+ let pixel = sh("pixel", b"known test masked pixel");
+ let plain = vec![sh("vertex", b"known test masked vertex"), pixel.clone()];
+ let twin = vec![plain[0].clone(), pixel.masked()];
+ let (plain_key, twin_key) = (key_of(&plain, true), key_of(&twin, true));
+ assert_ne!(plain_key, twin_key, "the twin is a pipeline of its own");
+ let mut state = Vec::new();
+ GraphicsState::default().put(&mut state);
+ for (name, order) in [("twin-first", [(&twin_key, &twin), (&plain_key, &plain)]), ("plain-first", [(&plain_key, &plain), (&twin_key, &twin)])] {
+ let dir = scratch(name);
+ let mut book = Book::new(dir.clone());
+ book.read(HashSet::new(), HashSet::new());
+ for (key, shaders) in order {
+ book.note(id(key), shaders, Some(&state));
+ }
+ flush(&Mutex::new(book));
+ let mut stages = Vec::new();
+ walk_shaders(&dir, |stage, _, _, _| stages.push(stage));
+ assert_eq!(stages, [0, 1], "{name}: each container once, plain stage");
+ assert_eq!(read_back(&dir), order.map(|(key, _)| key.clone()), "{name}");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+ }
+
+ /// Only a pixel shader has a masked twin: the bit on another stage is not
+ /// this build's, and its entry alone is skipped.
+ #[test]
+ fn a_mask_bit_on_a_stage_other_than_pixel_is_not_read() {
+ let dir = scratch("not-pixel");
+ let (v, p): (&[u8], &[u8]) = (b"known test not-pixel vertex", b"known test not-pixel pixel");
+ let mut shaders = Vec::new();
+ for (stage, c) in [(0u8, v), (1, p)] {
+ shaders.push(stage);
+ shaders.extend(blake3::hash(c).as_bytes());
+ shaders.extend((c.len() as u32).to_le_bytes());
+ shaders.extend(c);
+ }
+ let mut pipelines = Vec::new();
+ for (n, stages) in [(1u8, [0x80, 1]), (2, [0, 0x81])] {
+ let mut entry = vec![n; 16];
+ entry.push(2);
+ for (stage, c) in stages.into_iter().zip([v, p]) {
+ entry.push(stage);
+ entry.extend(blake3::hash(c).as_bytes());
+ }
+ entry.push(0);
+ pipelines.extend((entry.len() as u32).to_le_bytes());
+ pipelines.extend(entry);
+ }
+ std::fs::write(dir.join(SHADERS), shaders).unwrap();
+ std::fs::write(dir.join(PIPELINES), pipelines).unwrap();
+ let sh = super::super::shader;
+ let back = read_back(&dir);
+ let _ = std::fs::remove_dir_all(&dir);
+ assert_eq!(back, [key_of(&[sh("vertex", v), sh("pixel", p).masked()], false)]);
+ }
}
diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs
index b719df5..8299e67 100644
--- a/crates/victory-gpu/src/pipeline/make.rs
+++ b/crates/victory-gpu/src/pipeline/make.rs
@@ -21,7 +21,7 @@
//! its end (run textures-d2, the first after a new translation; Belobug
//! 18e57db8 found the same).
-use std::collections::VecDeque;
+use std::collections::{HashSet, VecDeque};
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex, OnceLock};
@@ -218,21 +218,51 @@ fn dead_rt_left_out(shaders: &[Arc<Shader>], policy: DeadRtPolicy) -> Option<&'s
None
}
+/// Parses shader hashes from `VICTORY_LEAVE_OUT`: accepts comma/semicolon-separated
+/// 16-digit hex hashes and/or `@<path>` entries referencing files with one or more
+/// hashes per line (`#` starts a comment).
+fn parse_leave_out(raw: &str) -> HashSet<String> {
+ let mut out = HashSet::new();
+ let push_tokens = |text: &str, out: &mut HashSet<String>| {
+ for line in text.lines() {
+ let line = line.split('#').next().unwrap_or("");
+ for tok in line.split(|c: char| c == ',' || c == ';' || c.is_ascii_whitespace()) {
+ let h = tok.trim();
+ if h.len() == 16 && h.bytes().all(|b| b.is_ascii_hexdigit()) {
+ out.insert(h.to_ascii_lowercase());
+ }
+ }
+ }
+ };
+ for part in raw.split([',', ';']) {
+ let part = part.trim();
+ if let Some(path) = part.strip_prefix('@') {
+ match std::fs::read_to_string(path.trim()) {
+ Ok(contents) => push_tokens(&contents, &mut out),
+ Err(error) => tracing::warn!(path = path.trim(), %error, "VICTORY_LEAVE_OUT: failed to read hash list file"),
+ }
+ } else {
+ push_tokens(part, &mut out);
+ }
+ }
+ out
+}
+
/// Shader hashes whose pipelines are left out in every build
-/// (`VICTORY_LEAVE_OUT=<16 hex digits>[,..]`; `VICTORY_SKIP_PIPELINES` does
+/// (`VICTORY_LEAVE_OUT=<16 hex digits|@file>[,..]`; `VICTORY_SKIP_PIPELINES` does
/// the same in diagnostics builds only). The decal heap's
/// `CS_DefragHeap_ComputeRelocations` (02384a60fda6f2d0), translatable for
/// 32-lane hosts through host waves that meet by spinning, took 11.85 ms of
/// the card a frame in the first gameplay area (timing run, 2026-11-26).
-fn leave_out() -> &'static [String] {
- static HASHES: OnceLock<Vec<String>> = OnceLock::new();
+fn leave_out() -> &'static HashSet<String> {
+ static HASHES: OnceLock<HashSet<String>> = OnceLock::new();
HASHES.get_or_init(|| {
- std::env::var("VICTORY_LEAVE_OUT")
- .unwrap_or_default()
- .split(',')
- .map(|h| h.trim().to_ascii_lowercase())
- .filter(|h| h.len() == 16 && h.bytes().all(|b| b.is_ascii_hexdigit()))
- .collect()
+ let raw = std::env::var("VICTORY_LEAVE_OUT").unwrap_or_default();
+ let set = parse_leave_out(&raw);
+ if !set.is_empty() {
+ tracing::info!(count = set.len(), "VICTORY_LEAVE_OUT: shader hashes left out");
+ }
+ set
})
}
@@ -1681,7 +1711,12 @@ fn workers() -> bool {
std::env::var("VICTORY_PIPELINE_WORKERS")
.ok()
.and_then(|v| v.trim().parse().ok()),
- std::thread::available_parallelism().map_or(2, |n| n.get()),
+ // `VICTORY_THREADS_BY_CORES=1`: of the physical cores, not the logical processors.
+ if crate::cores::by_cores() {
+ crate::cores::pool_cores()
+ } else {
+ std::thread::available_parallelism().map_or(2, |n| n.get())
+ },
crate::residency::limited_host_ram(),
);
tracing::info!(workers, "pipeline workers");
@@ -2752,4 +2787,22 @@ mod tests {
);
assert_eq!(rt_skin_default.left_out, None);
}
+
+ #[test]
+ fn leave_out_parses_inline_and_at_file_hashes() {
+ let dir = tempfile::tempdir().unwrap();
+ let list = dir.path().join("skip.txt");
+ std::fs::write(
+ &list,
+ "# comment line\n02384A60FDA6F2D0 # decal defrag\n731a39171b568298,invalid_short\ncaf96a3229145fa6\n",
+ )
+ .unwrap();
+ let raw = format!("0123456789ABCDEF,@{}", list.display());
+ let parsed = parse_leave_out(&raw);
+ assert_eq!(parsed.len(), 4);
+ assert!(parsed.contains("0123456789abcdef"));
+ assert!(parsed.contains("02384a60fda6f2d0"));
+ assert!(parsed.contains("731a39171b568298"));
+ assert!(parsed.contains("caf96a3229145fa6"));
+ }
}
diff --git a/crates/victory-gpu/src/procmem.rs b/crates/victory-gpu/src/procmem.rs
index 1821a89..851dc5a 100644
--- a/crates/victory-gpu/src/procmem.rs
+++ b/crates/victory-gpu/src/procmem.rs
@@ -71,6 +71,14 @@ pub(crate) struct Region {
pub(crate) base: usize,
pub(crate) size: u64,
pub(crate) kind: Kind,
+ /// Write-combined or uncached pages (`PAGE_WRITECOMBINE`,
+ /// `PAGE_NOCACHE`): the card driver's upload memory, and with Resizable
+ /// BAR the card's own memory it maps for the CPU (see
+ /// [`Census::host_uncached_present`]).
+ pub(crate) uncached: bool,
+ /// Of an uncached region, the bytes in the process's physical memory
+ /// ([`present_uncached`]; 0 when not asked).
+ pub(crate) present: u64,
}
/// The committed bytes of the address space by owner.
@@ -84,6 +92,19 @@ pub(crate) struct Census {
pub(crate) image: u64,
/// The largest regions at host addresses: address, bytes, kind.
pub(crate) biggest: Vec<(usize, u64, Kind)>,
+ /// Private bytes at host addresses that are write-combined or uncached.
+ pub(crate) host_uncached: u64,
+ /// Of those, the bytes in the process's physical memory: upload heaps
+ /// (the PC's memory) and card memory the CPU wrote through the BAR. The
+ /// rest is the card's own memory, which the driver maps write-combined
+ /// for every allocation in it on a PC with Resizable BAR (an RTX 4060
+ /// with BAR1 at 8 GiB: a `DEFAULT` buffer of 256 MiB adds 256 MiB here
+ /// and to the private bytes, and 0 MB in memory; `examples/wc_probe.rs`).
+ pub(crate) host_uncached_present: u64,
+ /// Private regions at host addresses by size, as (regions, bytes):
+ /// under 1 MiB (heap segments, stacks, small driver blocks: what
+ /// fragments), 1 MiB to 64 MiB, 64 MiB and more.
+ pub(crate) host_sizes: [[u64; 2]; 3],
}
/// Sorts committed `regions` by owner; `in_title` says whether an address
@@ -95,7 +116,16 @@ pub(crate) fn tally(regions: impl IntoIterator<Item = Region>, in_title: impl Fn
let title = r.kind != Kind::Image && in_title(r.base);
match (r.kind, title) {
(Kind::Private, true) => c.private[0] += r.size,
- (Kind::Private, false) => c.private[1] += r.size,
+ (Kind::Private, false) => {
+ c.private[1] += r.size;
+ if r.uncached {
+ c.host_uncached += r.size;
+ c.host_uncached_present += r.present.min(r.size);
+ }
+ let class = usize::from(r.size >= 1 << 20) + usize::from(r.size >= 64 << 20);
+ c.host_sizes[class][0] += 1;
+ c.host_sizes[class][1] += r.size;
+ }
(Kind::Mapped, true) => c.mapped[0] += r.size,
(Kind::Mapped, false) => c.mapped[1] += r.size,
(Kind::Image, _) => c.image += r.size,
@@ -114,7 +144,8 @@ pub(crate) fn tally(regions: impl IntoIterator<Item = Region>, in_title: impl Fn
/// The committed regions of this process, by a walk over the address space.
fn committed_regions() -> Vec<Region> {
use windows_sys::Win32::System::Memory::{
- MEM_COMMIT, MEM_IMAGE, MEM_MAPPED, MEM_PRIVATE, MEMORY_BASIC_INFORMATION, VirtualQuery,
+ MEM_COMMIT, MEM_IMAGE, MEM_MAPPED, MEM_PRIVATE, MEMORY_BASIC_INFORMATION, PAGE_NOCACHE, PAGE_WRITECOMBINE,
+ VirtualQuery,
};
let mut out = Vec::new();
let mut at = 0usize;
@@ -134,7 +165,8 @@ fn committed_regions() -> Vec<Region> {
_ => None,
};
if let Some(kind) = kind {
- out.push(Region { base: info.BaseAddress as usize, size: info.RegionSize as u64, kind });
+ let uncached = info.Protect & (PAGE_WRITECOMBINE | PAGE_NOCACHE) != 0;
+ out.push(Region { base: info.BaseAddress as usize, size: info.RegionSize as u64, kind, uncached, present: 0 });
}
}
match (info.BaseAddress as usize).checked_add(info.RegionSize) {
@@ -145,6 +177,64 @@ fn committed_regions() -> Vec<Region> {
out
}
+/// Whether the write-combined bytes are split by what of them is in the
+/// PC's memory (`VICTORY_PROCMEM_WC_SPLIT=0`: not; on by default). One page
+/// in sixteen of each such region is asked about, on the line's own thread.
+fn wc_split() -> bool {
+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var_os("VICTORY_PROCMEM_WC_SPLIT").is_none_or(|v| v != "0"))
+}
+
+/// Fills [`Region::present`] of the uncached private regions whose base
+/// `asked_at` takes (the log: host addresses): one 4 KiB page asked about in
+/// each 64 KiB, standing for it.
+/// Upload heaps are the PC's memory and in the working set from their
+/// creation; the card's own memory the driver maps is not, until the CPU
+/// touches it through the BAR.
+fn present_uncached(regions: &mut [Region], asked_at: impl Fn(usize) -> bool) {
+ use windows_sys::Win32::System::ProcessStatus::K32QueryWorkingSetEx;
+ use windows_sys::Win32::System::Threading::GetCurrentProcess;
+ const STEP: u64 = 64 << 10;
+ // Small batches: each call holds the working set's lock a short while.
+ const BATCH: usize = 512;
+ let mut asked: Vec<[usize; 2]> = Vec::with_capacity(BATCH);
+ let mut stands: Vec<(usize, u64)> = Vec::with_capacity(BATCH);
+ let flush = |asked: &mut Vec<[usize; 2]>, stands: &mut Vec<(usize, u64)>, regions: &mut [Region]| {
+ if asked.is_empty() {
+ return;
+ }
+ // SAFETY: our own process; `asked` holds that many entries of two
+ // words each (address, attributes), as the call fills them in.
+ let ok = unsafe { K32QueryWorkingSetEx(GetCurrentProcess(), asked.as_mut_ptr().cast(), (asked.len() * 16) as u32) } != 0;
+ if ok {
+ for (a, &(i, bytes)) in asked.iter().zip(stands.iter()) {
+ // Bit 0: the page is valid in the process's working set.
+ if a[1] & 1 != 0 {
+ regions[i].present += bytes;
+ }
+ }
+ }
+ asked.clear();
+ stands.clear();
+ };
+ for i in 0..regions.len() {
+ let r = regions[i];
+ if !(r.uncached && r.kind == Kind::Private && asked_at(r.base)) {
+ continue;
+ }
+ let mut offset = 0;
+ while offset < r.size {
+ asked.push([r.base + offset as usize, 0]);
+ stands.push((i, STEP.min(r.size - offset)));
+ if asked.len() == BATCH {
+ flush(&mut asked, &mut stands, regions);
+ }
+ offset += STEP;
+ }
+ }
+ flush(&mut asked, &mut stands, regions);
+}
+
/// The process's memory in bytes: in physical memory, and committed
/// (private bytes).
pub(crate) fn process_memory() -> (u64, u64) {
@@ -218,7 +308,12 @@ fn log() {
static N: AtomicU64 = AtomicU64::new(0);
let started = std::time::Instant::now();
let (working, private) = process_memory();
- let census = tally(committed_regions(), |at| at < HOST);
+ let mut regions = committed_regions();
+ let split = wc_split();
+ if split {
+ present_uncached(&mut regions, |at| at >= HOST);
+ }
+ let census = tally(regions, |at| at < HOST);
let walked = started.elapsed();
let mb = |b: u64| b >> 20;
let (free, _) = system_memory();
@@ -246,6 +341,27 @@ fn log() {
} else {
String::new()
};
+ let wc = if split {
+ format!(
+ " ({} MB of it in the PC's memory: upload heaps, and card memory the CPU wrote through the BAR; {} MB not in the working set: \
+ the card's own memory, which the driver maps for the CPU (VICTORY_PROCMEM_WC_SPLIT))",
+ mb(census.host_uncached_present),
+ mb(census.host_uncached.saturating_sub(census.host_uncached_present))
+ )
+ } else {
+ String::new()
+ };
+ let [chunks, chunk_bytes, spare_chunks, spare_chunk_bytes] = [1, 2, 3, 4].map(|i| crate::host::ALIVE[i].load(Relaxed));
+ let [sources, shared_sources] = crate::host::upload_spare_bytes();
+ let uploads = format!(
+ "; the layer's upload pools: list scratch chunks {chunks} ({} MB; {spare_chunks} of them, {} MB, kept for the next \
+ list), copy sources kept {} MB (and {} MB shared), sends' spares {} MB",
+ mb(chunk_bytes),
+ mb(spare_chunk_bytes),
+ mb(sources),
+ mb(shared_sources),
+ mb(crate::host::send_spare_bytes())
+ );
let biggest: Vec<String> = census
.biggest
.iter()
@@ -260,7 +376,7 @@ fn log() {
containers {} ({} MB), translated shaders {} ({} MB host code), host copies of title memory {} ({} MB), XMem \
heap blocks {} ({} MB); the pipeline library file {} MB, last save {} MB, {} MB let go from memory | in the \
PC's memory shared with the card: staging of textures {} MB, upload buffers held by lists {} ({} MB) | named \
- {} MB, unnamed {} MB of the private bytes; largest at host addresses: {}{heaps}",
+ {} MB, unnamed {} MB of the private bytes; largest at host addresses: {}; private at host addresses by region: {} under 1 MiB ({} MB), {} of 1-64 MiB ({} MB), {} of 64 MiB or more ({} MB), {} MB write-combined or uncached{wc}{uploads}{heaps}",
mb(private),
mb(working),
mb(seen),
@@ -292,6 +408,13 @@ fn log() {
mb(found),
mb(private.saturating_sub(found)),
if biggest.is_empty() { "none".to_owned() } else { biggest.join(", ") },
+ census.host_sizes[0][0],
+ mb(census.host_sizes[0][1]),
+ census.host_sizes[1][0],
+ mb(census.host_sizes[1][1]),
+ census.host_sizes[2][0],
+ mb(census.host_sizes[2][1]),
+ mb(census.host_uncached),
);
}
@@ -300,7 +423,7 @@ mod tests {
use super::*;
fn region(base: usize, size: u64, kind: Kind) -> Region {
- Region { base, size, kind }
+ Region { base, size, kind, uncached: false, present: 0 }
}
#[test]
@@ -321,6 +444,60 @@ mod tests {
assert_eq!(c.mapped, [20, 40]);
assert_eq!(c.image, 110, "an image is an image wherever it lies");
assert_eq!(c.regions, 6);
+ assert_eq!(c.host_sizes, [[1, 30], [0, 0], [0, 0]], "only private regions at host addresses");
+ }
+
+ #[test]
+ fn private_regions_at_host_addresses_are_split_by_size_and_caching() {
+ let mut big = region(0x100_0000, 64 << 20, Kind::Private);
+ big.uncached = true;
+ let c = tally(
+ [region(0x1000, 4096, Kind::Private), region(0x2000, 2 << 20, Kind::Private), big, region(0x9000, 1 << 30, Kind::Mapped)],
+ |_| false,
+ );
+ assert_eq!(c.host_sizes, [[1, 4096], [1, 2 << 20], [1, 64 << 20]]);
+ assert_eq!(c.host_uncached, 64 << 20);
+ assert_eq!(c.host_uncached_present, 0);
+ }
+
+ /// Of the write-combined bytes, those in the working set are told from
+ /// those not (the card's own memory the driver maps); a cached region's
+ /// pages are never counted there.
+ #[test]
+ fn write_combined_bytes_in_memory_are_told_apart() {
+ let mut upload = region(0x100_0000, 4 << 20, Kind::Private);
+ upload.uncached = true;
+ upload.present = 4 << 20;
+ let mut card = region(0x200_0000, 256 << 20, Kind::Private);
+ card.uncached = true;
+ let mut cached = region(0x300_0000, 8 << 20, Kind::Private);
+ cached.present = 8 << 20;
+ let c = tally([upload, card, cached], |_| false);
+ assert_eq!(c.host_uncached, 260 << 20);
+ assert_eq!(c.host_uncached_present, 4 << 20);
+ }
+
+ /// The working-set query finds a written write-combined allocation of
+ /// our own in memory.
+ #[test]
+ fn present_uncached_finds_written_write_combined_pages() {
+ use windows_sys::Win32::System::Memory::{
+ MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, PAGE_WRITECOMBINE, VirtualAlloc, VirtualFree,
+ };
+ const SIZE: usize = 1 << 20;
+ // SAFETY: a fresh allocation of our own, written whole and freed below.
+ let at = unsafe { VirtualAlloc(std::ptr::null(), SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE | PAGE_WRITECOMBINE) };
+ assert!(!at.is_null());
+ // SAFETY: the allocation just made.
+ unsafe { std::ptr::write_bytes(at.cast::<u8>(), 1, SIZE) };
+ let mut regions = committed_regions();
+ present_uncached(&mut regions, |_| true);
+ let mine = regions.iter().find(|r| r.base == at as usize).copied();
+ // SAFETY: the base of the reservation above, released once.
+ unsafe { VirtualFree(at, 0, MEM_RELEASE) };
+ let mine = mine.expect("the allocation is walked");
+ assert!(mine.uncached);
+ assert_eq!(mine.present, SIZE as u64, "written pages are in the working set");
}
#[test]
diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs
index 62d3810..c7c1823 100644
--- a/crates/victory-gpu/src/resource.rs
+++ b/crates/victory-gpu/src/resource.rs
@@ -1583,6 +1583,51 @@ fn base_level(desc: &ResourceDesc, first: u32) -> u32 {
base
}
+/// The largest side a host copy of a texture the title fills may have
+/// (`VICTORY_TEXTURE_MAX`, in texels; unset or 0: any). Textures larger than
+/// that keep only their mip levels from the first that fits, saving 3/4 of
+/// VRAM and upload staging per skipped mip level.
+#[cfg(windows)]
+fn texture_max() -> u64 {
+ static MAX: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
+ *MAX.get_or_init(|| {
+ let max = std::env::var("VICTORY_TEXTURE_MAX")
+ .ok()
+ .and_then(|v| v.trim().parse().ok())
+ .unwrap_or(0);
+ if max > 0 {
+ tracing::info!(max, "VICTORY_TEXTURE_MAX: capping placed textures to this maximum side");
+ }
+ max
+ })
+}
+
+/// Pure helper computing the first mip level kept for `desc` under side limit `max`.
+#[cfg(windows)]
+fn level_cap_for(desc: &ResourceDesc, max: u64) -> u32 {
+ if max == 0 {
+ return 0;
+ }
+ let mut k = 0;
+ while (desc.width >> k > max || u64::from(desc.height) >> k > max)
+ && k + 1 < u32::from(desc.mip_levels)
+ {
+ k += 1;
+ }
+ if k == 0 { 0 } else { base_level(desc, k) }
+}
+
+/// The first level a host copy of `desc` keeps for [`texture_max`]: 0 when
+/// it fits whole or cannot begin later ([`base_level`]).
+#[cfg(windows)]
+fn level_cap(desc: &ResourceDesc) -> u32 {
+ level_cap_for(desc, texture_max())
+}
+
+/// Placed textures capped to a smaller first mip level by `VICTORY_TEXTURE_MAX`.
+#[cfg(windows)]
+static CAPPED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+
/// The bytes of title memory a placed texture with the resource description
/// `desc` is read from for a view that starts at level `first`; `None` as
/// [`placed_bytes`]. Remembered: asked for every slot that is looked at.
@@ -1640,16 +1685,11 @@ pub(crate) fn want_level(this: This, first: u32) {
r.host.wanted.fetch_min(first, Relaxed);
return;
};
- // A copy made small (for want of room, or shrunk) keeps its small levels
- // until `grow_small` lets it have more: replaced here, it was made small
- // again at once, and again at the next view of it, each old copy held for
- // a second before it went (runs lt1 and lt2: 18 GB of the card's 11 in
- // use within a minute, then a list that would not close).
if r.host.small.load(Relaxed) != 0 {
r.host.wanted.fetch_min(first, Relaxed);
return;
}
- if host.base == 0 || host.base <= base_level(&r.desc, first) {
+ if host.base == 0 || host.base <= base_level(&r.desc, first).max(level_cap(&r.desc)) {
return;
}
// One the host GPU wrote holds what title memory does not: made again
@@ -2342,6 +2382,14 @@ fn hosted_with(
// on (a level the host can have as level 0, as `base` is).
base = base.max(r.host.small.load(Relaxed));
}
+ // Large textures from the first level that fits (`VICTORY_TEXTURE_MAX`).
+ if texture.is_none() && shape_fits && r.host.placed.load(Relaxed) && !is_aliased(this) {
+ let cap = level_cap(&r.desc);
+ if cap > base {
+ base = cap;
+ CAPPED.fetch_add(1, Relaxed);
+ }
+ }
let alias = (!fills(&r.desc)).then(|| (r.data() as usize, footprint(&r.desc).map_or(0, |f| f.size)));
let created = match texture {
Some(texture) => Ok(Some((texture, None))),
@@ -2611,7 +2659,15 @@ pub(crate) fn room_for_first_upload(memory: Option<[u64; 4]>, reserve: u64) -> b
// ranges under the pool's lock otherwise.
// ponytail: a scan per over-budget decision; keep a running widest in
// pool.rs if it shows in a profile.
- if memory.is_some_and(|[budget, used, ..]| used >= budget) { crate::pool::texture_widest_free() } else { 0 },
+ // (From the margin under the budget on, `first_upload_card_line`: an
+ // upload that fits a free range there needs no new card memory.)
+ if memory.is_some_and(|[budget, used, ..]| {
+ used.saturating_add(reserve) >= first_upload_card_line(budget).unwrap_or(budget).min(budget)
+ }) {
+ crate::pool::texture_widest_free()
+ } else {
+ 0
+ },
);
FIRST_UPLOAD_REASONS[why as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
why == FirstUpload::Allow
@@ -2703,6 +2759,17 @@ fn first_upload_decision(
if needs_new_block && used.saturating_add(new_card_bytes) >= budget {
return FirstUpload::WholeCard;
}
+ // New card memory stops at a margin under the budget too
+ // (`VICTORY_FIRST_UPLOAD_CARD_PERCENT`): past the budget the system pages
+ // the card's memory to the PC's, and the card's own work (targets, buffer
+ // copies, frame generation) grows after the texture pass has filled it.
+ // An upload into a free range there now still goes in.
+ if needs_new_block
+ && let Some(card) = first_upload_card_line(budget)
+ && used.saturating_sub(free_blocks).saturating_add(reserve) >= card
+ {
+ return FirstUpload::WholeCard;
+ }
FirstUpload::Allow
}
@@ -2740,6 +2807,25 @@ fn first_upload_headroom_from(
texture_room.min(free_blocks.saturating_add(new_card_room))
}
+/// The card's use (less the free texture blocks) that first uploads past
+/// the room line stop at: `VICTORY_FIRST_UPLOAD_CARD_PERCENT` of the budget
+/// (92; 0: none, the budget alone as before), in bytes.
+///
+/// At the budget itself the system has started to page: with first uploads
+/// allowed up to it, an RTX 4060's use stood at 6.9-7.0 GB of a 6.9 GB
+/// budget, and frame generation and new targets then pushed it past.
+#[cfg(any(windows, test))]
+fn first_upload_card_line(budget: u64) -> Option<u64> {
+ static PERCENT: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
+ let percent = *PERCENT.get_or_init(|| {
+ std::env::var("VICTORY_FIRST_UPLOAD_CARD_PERCENT")
+ .ok()
+ .and_then(|v| v.trim().parse::<u64>().ok())
+ .map_or(92, |p| p.min(100))
+ });
+ (percent > 0).then(|| budget / 100 * percent)
+}
+
/// Takes the first-upload decision counters for the frame-rate line.
#[cfg(windows)]
pub(crate) fn first_upload_reasons() -> [u64; 6] {
@@ -2819,17 +2905,78 @@ pub(crate) fn targets_room_kept(memory: Option<[u64; 4]>) -> u64 {
// they last grew by that much.
static GREW: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
let now = crate::host::now_ms();
- let (last, since) = (GREW[0].load(Relaxed), GREW[1].load(Relaxed));
- let (last, since) = targets_seen(last, since, targets, now);
- GREW[0].store(last, Relaxed);
- GREW[1].store(since, Relaxed);
+ let read = (GREW[0].load(Relaxed), GREW[1].load(Relaxed));
+ let (last, since) = targets_seen(read.0, read.1, targets, now);
+ // (Only what changed, so that a caller that read an older clock does not
+ // set back one another thread just moved: `VICTORY_TARGETS_PEAK_DECAY`.)
+ if (last, since) != read {
+ GREW[0].store(last, Relaxed);
+ let _ = GREW[1].compare_exchange(read.1, since, Relaxed, Relaxed);
+ }
static FLAT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
if *FLAT.get_or_init(|| std::env::var_os("VICTORY_CARD_ROOM_FOR_TARGETS_MB").is_some()) {
return targets_kept(most, targets, now.saturating_sub(since), settle);
}
+ // The peak let down by halves once the targets have stopped growing
+ // (`VICTORY_TARGETS_PEAK_DECAY`), each step starting the clock again.
+ static DECAY: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+ let decay = *DECAY.get_or_init(|| {
+ let on = small_card_switch("VICTORY_TARGETS_PEAK_DECAY");
+ tracing::info!(on, settle_ms = settle, "render-target reserve: its peak let down once the targets stop growing (VICTORY_TARGETS_PEAK_DECAY)");
+ on
+ });
+ let peak = match targets_peak_let_down(peak, targets, now.saturating_sub(since), settle) {
+ // (Once per settle: a caller that loses the exchange keeps the peak it read.)
+ Some(lower) if decay && PEAK.compare_exchange(peak, lower, Relaxed, Relaxed).is_ok() => {
+ let _ = GREW[1].compare_exchange(since, now, Relaxed, Relaxed);
+ lower
+ }
+ _ => peak,
+ };
targets_kept_from_peak(most, targets, peak)
}
+/// What [`targets_room_kept`]'s peak comes down to once the targets have held
+/// still (no growth of 64 MiB) for `settle` ms: half of it, never under the
+/// targets now; `None` while they still grow, with `settle` 0, or once the
+/// peak is the targets' own size already.
+///
+/// The peak only ever rose. A short burst of targets (a menu, a loading
+/// screen, DLSS and frame generation remaking theirs) then kept the reserve
+/// for the whole run: on an RTX 4060 (8 GB, Series S profile, frame
+/// generation 4x, 2026-11-29) 1,706 to 2,072 MB stayed kept for render
+/// targets, 183 of 190 checks said "no room, new textures wait", and up to
+/// 7,992 textures picked by index waited for room (black or missing
+/// surfaces). Halving it every `settle` ms keeps room for a new scene that
+/// comes soon after, and gives the rest back to the textures.
+#[cfg(any(windows, test))]
+fn targets_peak_let_down(peak: u64, targets: u64, still_ms: u64, settle: u64) -> Option<u64> {
+ if settle == 0 || still_ms < settle || peak <= targets {
+ return None;
+ }
+ Some((peak / 2).max(targets))
+}
+
+/// Whether a switch for small cards is on: `1` on, `0` off, unset (or
+/// anything else) on only when the card's budget is 8.5 GiB or less (an 8 GB
+/// card's is about 7.2 GB), where textures run out of room first.
+#[cfg(windows)]
+pub(crate) fn small_card_switch(name: &str) -> bool {
+ match std::env::var(name).ok().as_deref().map(str::trim) {
+ Some("1") => true,
+ Some("0") => false,
+ _ => crate::host::host()
+ .and_then(|h| h.video_memory())
+ .is_some_and(|[budget, ..]| small_card(budget)),
+ }
+}
+
+/// A card whose memory budget is 8.5 GiB or less ([`small_card_switch`]).
+#[cfg(any(windows, test))]
+fn small_card(budget: u64) -> bool {
+ budget > 0 && budget <= (17u64 << 29)
+}
+
/// [`targets_room_kept`]'s record of the targets' bytes (`last`) and of
/// when they last grew by 64 MiB (`since`, ms), with `targets` now: a fall
/// of 64 MiB lowers the record (so that growing back counts as growth), a
@@ -2982,12 +3129,17 @@ fn face_headroom_bytes() -> u64 {
#[cfg(windows)]
pub(crate) fn room_line(budget: u64) -> u64 {
static SET: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
- let percent = if *SET.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_ROOM_PERCENT").is_some()) {
+ // (The launcher's own line for frame generation comes with
+ // `VICTORY_FRAMEGEN_ROOM_RESERVE`; it is lifted once frame generation's
+ // memory is in the card's use, `framegen_counted`. A line set by hand stays.)
+ let framegen_reserve = std::env::var_os("VICTORY_FRAMEGEN_ROOM_RESERVE").is_some();
+ let percent = if *SET.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_ROOM_PERCENT").is_some())
+ && !(framegen_reserve && framegen_counted())
+ {
Some(room_percent())
} else {
None
};
- let framegen_reserve = std::env::var_os("VICTORY_FRAMEGEN_ROOM_RESERVE").is_some();
room_line_for(budget, percent, framegen_reserve, crate::streamline::framegen_available())
}
@@ -2999,6 +3151,33 @@ fn room_line_for(budget: u64, percent: Option<u64>, framegen_reserve: bool, fram
percent.map_or_else(|| line_for(budget), |p| budget / 100 * p.clamp(50, 97))
}
+/// Whether frame generation's own memory is in the card's use already, so
+/// the lower line the launcher sets for it (`VICTORY_TEXTURE_ROOM_PERCENT`,
+/// 80 with it on) would count it a second time: DLSS frame generation has
+/// been on for `VICTORY_FG_ROOM_SETTLE_MS` (5,000) without a break, and
+/// `VICTORY_FG_ROOM_ONCE` is on (unset: on small cards, `small_card_switch`).
+/// With frame generation off again, the lower line is back.
+///
+/// The 80 % line leaves a fifth of the budget for frame generation's 1.5 to
+/// 2 GB. Once its resources are made the system counts them in the use the
+/// line is weighed against, so on an 8 GB card (budget 6,675 MB) textures
+/// were held at 5,340 MB with 5,974 MB in use: the rest of that fifth stood
+/// empty while thousands of textures waited (RTX 4060, 2026-11-29).
+#[cfg(windows)]
+fn framegen_counted() -> bool {
+ static ON: std::sync::OnceLock<(bool, u64)> = std::sync::OnceLock::new();
+ let (on, settle) = *ON.get_or_init(|| {
+ let on = small_card_switch("VICTORY_FG_ROOM_ONCE");
+ let settle = std::env::var("VICTORY_FG_ROOM_SETTLE_MS")
+ .ok()
+ .and_then(|v| v.trim().parse::<u64>().ok())
+ .unwrap_or(5_000);
+ tracing::info!(on, settle_ms = settle, "texture line: frame generation's memory counted once it is running (VICTORY_FG_ROOM_ONCE)");
+ (on, settle)
+ });
+ on && crate::streamline::framegen_presenting_ms().is_some_and(|ms| ms >= settle)
+}
+
/// The budget less what is left free for the host's own needs that are
/// made with no room test (render target bursts, buffer copies, upload
/// buffers): 768 MiB or a twentieth of the budget, whichever is more; never
@@ -3287,6 +3466,74 @@ fn empty_working_set() -> bool {
unsafe { K32EmptyWorkingSet(windows_sys::Win32::System::Threading::GetCurrentProcess()) != 0 }
}
+/// Free-RAM threshold in MiB below which the process trims its own working set
+/// (`VICTORY_WS_TRIM_MB`, default `3072`; `0` disables). Moves cold boot and
+/// shader-compiler pages to the Windows Standby list (soft-fault recovery, no
+/// global Standby purge) with a cooldown so gameplay frame pacing stays smooth.
+#[cfg(windows)]
+fn ws_trim_threshold_mb() -> u64 {
+ static MB: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
+ *MB.get_or_init(|| {
+ std::env::var("VICTORY_WS_TRIM_MB")
+ .ok()
+ .and_then(|v| v.trim().parse::<u64>().ok())
+ .unwrap_or(3072)
+ })
+}
+
+#[cfg(windows)]
+fn ws_trim_cooldown_ms() -> u64 {
+ static MS: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
+ *MS.get_or_init(|| {
+ let s = std::env::var("VICTORY_WS_TRIM_COOLDOWN_S")
+ .ok()
+ .and_then(|v| v.trim().parse::<u64>().ok())
+ .unwrap_or(60)
+ .max(10);
+ s * 1_000
+ })
+}
+
+#[cfg(windows)]
+fn should_trim_ws(free_mib: u64, threshold_mib: u64, now_ms: u64, last_ms: u64, cooldown_ms: u64) -> bool {
+ threshold_mib > 0
+ && free_mib < threshold_mib
+ && (last_ms == 0 || now_ms.saturating_sub(last_ms) >= cooldown_ms)
+}
+
+#[cfg(windows)]
+pub(crate) fn maybe_trim_working_set() {
+ use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
+ static LAST_MS: AtomicU64 = AtomicU64::new(0);
+ let threshold = ws_trim_threshold_mb();
+ if threshold == 0 {
+ return;
+ }
+ let Some(status) = crate::residency::memory_status() else {
+ return;
+ };
+ let free_before = status.ullAvailPhys >> 20;
+ let now = crate::host::coarse_ms().max(1);
+ let last = LAST_MS.load(Relaxed);
+ let cooldown = ws_trim_cooldown_ms();
+ if !should_trim_ws(free_before, threshold, now, last, cooldown) {
+ return;
+ }
+ if LAST_MS.compare_exchange(last, now, Relaxed, Relaxed).is_err() {
+ return;
+ }
+ crate::host::drop_spare_chunks();
+ let emptied = empty_working_set();
+ let free_after = crate::residency::memory_status().map_or(free_before, |s| s.ullAvailPhys >> 20);
+ tracing::info!(
+ free_before_mib = free_before,
+ free_after_mib = free_after,
+ threshold_mib = threshold,
+ emptied,
+ "trimmed process working set under RAM pressure (VICTORY_WS_TRIM_MB)"
+ );
+}
+
/// `VICTORY_TEXTURE_SOFT_MB`: past this many bytes of host copies of
/// textures the title fills, the sweep lets go of those idle
/// [`SOFT_IDLE_MS`] and more down to it ([`soft_keep`]). Unset: none.
@@ -3345,9 +3592,32 @@ fn soft_keep(filled: u64, soft: u64, kept: (u64, u64)) -> (u64, u64) {
/// `VICTORY_TEXTURE_SWEEP=0` lets nothing go.
#[cfg(windows)]
pub(crate) fn let_go_idle() {
+ let_go_idle_at(false);
+}
+
+/// [`let_go_idle`] on the sweep's own thread (`VICTORY_SWEEP_ASIDE=1`,
+/// `crate::host`): no flush (F7/F8 is left for a sweep on the thread that
+/// submits) and no [`slot_evict`]. That one empties title slots before it
+/// takes a copy, and when the take fails (a list took the copy meanwhile)
+/// the slots are made again only "before the next submission"
+/// (`crate::descriptor::make_waiting`): beside a submission being prepared,
+/// past its `make_waiting`, its lists would run with the slots empty.
+#[cfg(windows)]
+pub(crate) fn let_go_idle_aside() {
+ let_go_idle_at(true);
+}
+
+/// Whether F7/F8 asked for a flush not yet done ([`let_go_idle`]).
+#[cfg(windows)]
+pub(crate) fn flush_asked() -> bool {
+ FLUSH_ASKED.load(std::sync::atomic::Ordering::Relaxed) != 0
+}
+
+#[cfg(windows)]
+fn let_go_idle_at(aside: bool) {
use std::sync::atomic::Ordering::Relaxed;
const IDLE_FRAMES: u64 = 4;
- let flush = FLUSH_ASKED.swap(0, Relaxed);
+ let flush = if aside { 0 } else { FLUSH_ASKED.swap(0, Relaxed) };
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
if !*ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_SWEEP").is_none_or(|v| v != "0")) {
return;
@@ -3630,7 +3900,7 @@ pub(crate) fn let_go_idle() {
// Memory stack by skornuta (skornuta/victory-memory-stack 57fb136,
// GPL-3.0): `VICTORY_SLOT_EVICT=1`; without it, nothing.
let slot_idle_ms = if flush != 0 { flush_idle_ms(flush).1 } else { card_rule.0 };
- let (slot_went, slot_bytes) = slot_evict(memory, slot_idle_ms, IDLE_FRAMES, flush);
+ let (slot_went, slot_bytes) = if aside { (0, 0) } else { slot_evict(memory, slot_idle_ms, IDLE_FRAMES, flush) };
if flush == FLUSH_HARD {
let (staged, staged_bytes) = crate::texture::let_go_staging(flush_idle_ms(flush).0);
crate::host::drop_spare_chunks();
@@ -3640,6 +3910,8 @@ pub(crate) fn let_go_idle() {
working set given back: {emptied}",
staged_bytes >> 20
);
+ } else {
+ maybe_trim_working_set();
}
if flush != 0 {
let [budget, used] = memory.map_or([0, 0], |[budget, used, ..]| [budget, used]);
@@ -7959,6 +8231,40 @@ float4 lit() : SV_Target { return 1.0; }
assert_eq!(targets_kept_from_peak(most, 0, 0), 256 * MIB);
}
+ #[test]
+ fn the_targets_peak_comes_down_by_halves_once_they_hold_still() {
+ const MIB: u64 = 1 << 20;
+ let settle = 20_000;
+ // Still growing, or not still for long enough: the peak stays.
+ assert_eq!(targets_peak_let_down(2048 * MIB, 600 * MIB, 19_999, settle), None);
+ // Switched off.
+ assert_eq!(targets_peak_let_down(2048 * MIB, 600 * MIB, 60_000, 0), None);
+ // Held still: half the peak, then (another settle later) the targets themselves.
+ assert_eq!(targets_peak_let_down(2048 * MIB, 600 * MIB, 20_000, settle), Some(1024 * MIB));
+ assert_eq!(targets_peak_let_down(1024 * MIB, 600 * MIB, 20_000, settle), Some(600 * MIB));
+ // At the targets already: nothing to let down.
+ assert_eq!(targets_peak_let_down(600 * MIB, 600 * MIB, 20_000, settle), None);
+ // The RTX 4060 run: kept 1,706 MB with a peak of about 1.5 GB over 600 MB of targets;
+ // one step keeps half of it, two keep half the targets.
+ let most = 3072 * MIB;
+ let peak = 1540 * MIB;
+ let kept = |peak| targets_kept_from_peak(most, 600 * MIB, peak);
+ assert!(kept(peak) > 1600 * MIB);
+ let once = targets_peak_let_down(peak, 600 * MIB, settle, settle).unwrap();
+ assert_eq!(kept(once), 555 * MIB);
+ let twice = targets_peak_let_down(once, 600 * MIB, settle, settle).unwrap();
+ assert_eq!(kept(twice), 300 * MIB);
+ }
+
+ #[test]
+ fn small_cards_are_those_of_8_5_gib_or_less() {
+ const MIB: u64 = 1 << 20;
+ assert!(small_card(7188 * MIB)); // RTX 4060, 8 GB
+ assert!(small_card(5 * 1024 * MIB)); // 6 GB cards
+ assert!(!small_card(10_600 * MIB)); // 12 GB cards
+ assert!(!small_card(0));
+ }
+
/// A placed texture viewed from a later level has a host copy of that
/// and the smaller levels; a view from an earlier one gets another.
#[cfg(windows)]
@@ -8138,6 +8444,27 @@ float4 lit() : SV_Target { return 1.0; }
assert_eq!(cap, free_blocks);
}
+ /// The RTX 4060 run of 2026-11-29: first uploads that need new card
+ /// memory stop at 92 % of the budget (`first_upload_card_line`), not at
+ /// the budget, where the system pages the card; one that fits a free
+ /// range still goes in.
+ #[test]
+ fn new_card_memory_for_first_uploads_stops_under_the_budget() {
+ const MIB: u64 = 1 << 20;
+ let budget = 6900 * MIB;
+ let filled = 1500 * MIB;
+ let reserve = 4 * MIB;
+ let decide = |used: u64, free: u64| {
+ super::first_upload_decision(Some([budget, used, 0, 0]), reserve, false, false, 128, filled, 0, free, free)
+ };
+ // 94 % used, no free range: refused before the budget.
+ assert_eq!(decide(6500 * MIB, 0), super::FirstUpload::WholeCard);
+ // 87 % used: still under the margin.
+ assert_eq!(decide(6000 * MIB, 0), super::FirstUpload::Allow);
+ // 94 % used, but a free range takes it: no new card memory.
+ assert_eq!(decide(6500 * MIB, 64 * MIB), super::FirstUpload::Allow);
+ }
+
/// Issue #1496, the T+16 min line on a 16 GB card: 17,043 MiB in use
/// against a 14,767 MiB budget, 16 MiB "free" in texture blocks, 9,708 MiB
/// in texture copies. That free figure counts pieces still resting
@@ -8511,6 +8838,19 @@ float4 lit() : SV_Target { return 1.0; }
assert!(dead_rt_reclaimable(true, true, false, true));
}
+ #[cfg(windows)]
+ #[test]
+ fn texture_max_caps_large_textures_to_first_fitting_mip() {
+ let d4k = texture(4096, 4096, 98, 13);
+ let d2k = texture(2048, 1024, 98, 12);
+ let d1k = texture(1024, 1024, 98, 11);
+ assert_eq!(super::level_cap_for(&d4k, 0), 0);
+ assert_eq!(super::level_cap_for(&d1k, 1024), 0);
+ assert_eq!(super::level_cap_for(&d2k, 1024), 1);
+ assert_eq!(super::level_cap_for(&d4k, 1024), 2);
+ assert_eq!(super::level_cap_for(&d4k, 512), 3);
+ }
+
#[cfg(windows)]
#[test]
fn reclaim_dead_render_targets_frees_idle_superseded_and_keeps_newest_and_recent() {
@@ -8841,4 +9181,14 @@ float4 lit() : SV_Target { return 1.0; }
}
assert!(host_target(texture.0, 4).is_none(), "beyond both planes");
}
+
+ #[cfg(windows)]
+ #[test]
+ fn ws_trim_decision_respects_threshold_and_cooldown() {
+ assert!(!super::should_trim_ws(1500, 0, 100_000, 0, 60_000));
+ assert!(!super::should_trim_ws(4096, 3072, 100_000, 0, 60_000));
+ assert!(super::should_trim_ws(2500, 3072, 100_000, 0, 60_000));
+ assert!(!super::should_trim_ws(2500, 3072, 130_000, 100_000, 60_000));
+ assert!(super::should_trim_ws(2500, 3072, 160_000, 100_000, 60_000));
+ }
}
diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs
index c1fec4f..3eec6ec 100644
--- a/crates/victory-gpu/src/shadow.rs
+++ b/crates/victory-gpu/src/shadow.rs
@@ -156,14 +156,60 @@ pub(crate) struct Shadow {
taken_over: std::sync::atomic::AtomicBool,
}
+/// Demand-paged process memory for a card buffer's CPU mirror (`Private` or
+/// materialized `Lazy`). Untouched pages stay unbacked in physical RAM and do
+/// not consume DXGI non-local (`vram_shared`) memory.
+struct VirtualBuf {
+ ptr: *mut u8,
+ size: u64,
+}
+
+// SAFETY: VirtualAlloc pages are exclusively owned by `VirtualBuf` and freed on drop.
+unsafe impl Send for VirtualBuf {}
+// SAFETY: concurrent readers/writers follow `Shadow`'s per-range synchronization.
+unsafe impl Sync for VirtualBuf {}
+
+impl VirtualBuf {
+ fn new(size: u64) -> Option<Self> {
+ use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc};
+ let bytes = usize::try_from(size).ok()?;
+ if bytes == 0 {
+ return None;
+ }
+ // SAFETY: fresh, zero-filled process pages owned until this mirror drops.
+ let data = unsafe { VirtualAlloc(std::ptr::null(), bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) };
+ if data.is_null() {
+ return None;
+ }
+ PRIVATE_CPU_BYTES.fetch_add(size, Ordering::Relaxed);
+ Some(Self { ptr: data.cast(), size })
+ }
+}
+
+impl Drop for VirtualBuf {
+ fn drop(&mut self) {
+ use windows_sys::Win32::System::Memory::{MEM_RELEASE, VirtualFree};
+ // SAFETY: the base of this mirror's VirtualAlloc reservation, released once.
+ unsafe { VirtualFree(self.ptr.cast(), 0, MEM_RELEASE) };
+ PRIVATE_CPU_BYTES.fetch_sub(self.size, Ordering::Relaxed);
+ }
+}
+
/// From crossducking/RAZDA4A-XEN 76b58130 via vix0e0e/VIctory-LITE e66dcc25
/// and advantyx/VIctyx 7f5497c8. The GPU reads the submission's snapshot, so a two-sided
-/// shadow's CPU mirror can use pageable process memory. Single-sided buffers
-/// and the upload checker still need a D3D12 resource.
+/// shadow's CPU mirror can use pageable process memory — or stay unallocated (`Lazy`)
+/// until shaders write, `keep_stores`, or `placed_copy` actually need a CPU reference.
+/// Single-sided buffers and the upload checker still need a D3D12 resource.
enum CardCpu {
Shared(ID3D12Resource),
- Private { address: usize, size: u64 },
+ Private(#[allow(dead_code)] VirtualBuf),
File { _storage: crate::fileback::MappedStorage, size: u64 },
+ Lazy {
+ cpu: std::sync::OnceLock<VirtualBuf>,
+ cpu_init: Mutex<()>,
+ cpu_ptr: std::sync::atomic::AtomicPtr<u8>,
+ ever_sent: Mutex<Vec<(usize, usize)>>,
+ },
}
pub(crate) static PRIVATE_CPU_BYTES: AtomicU64 = AtomicU64::new(0);
@@ -184,8 +230,29 @@ impl CardCpu {
&& crate::host::own_sends() && !crate::host::upcheck::on()
}
+ /// Whether read-only card buffers and card windows defer allocating a CPU
+ /// mirror until first needed (on by default; `VICTORY_CARD_CPU_LAZY=0`
+ /// restores eager CPU mirrors). Saves 4–5 GiB of process RAM / `vram_shared`
+ /// on 24 GiB hosts and lets `send::take` copy directly from title memory.
+ fn lazy_enabled() -> bool {
+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+ *ON.get_or_init(|| {
+ std::env::var_os("VICTORY_CARD_CPU_LAZY").is_none_or(|v| v != "0")
+ && crate::host::own_sends()
+ && !crate::host::upcheck::on()
+ })
+ }
+
+ fn lazy() -> Self {
+ Self::Lazy {
+ cpu: std::sync::OnceLock::new(),
+ cpu_init: Mutex::new(()),
+ cpu_ptr: std::sync::atomic::AtomicPtr::new(std::ptr::null_mut()),
+ ever_sent: Mutex::default(),
+ }
+ }
+
fn allocate(size: u64) -> Option<(Self, *mut u8)> {
- use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc};
if Self::private_enabled() {
if let Some(folder) = CPU_MIRROR_FILES.get() {
match crate::fileback::MappedStorage::new(folder, usize::try_from(size).ok()?) {
@@ -202,11 +269,9 @@ impl CardCpu {
}
}
}
- // SAFETY: fresh, zero-filled process pages owned until this mirror drops.
- let data = unsafe { VirtualAlloc(std::ptr::null(), usize::try_from(size).ok()?, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) };
- if !data.is_null() {
- PRIVATE_CPU_BYTES.fetch_add(size, Ordering::Relaxed);
- return Some((Self::Private { address: data as usize, size }, data.cast()));
+ if let Some(buf) = VirtualBuf::new(size) {
+ let ptr = buf.ptr;
+ return Some((Self::Private(buf), ptr));
}
}
let (buffer, data) = host()?.shared_buffer(size)?;
@@ -214,29 +279,35 @@ impl CardCpu {
}
fn shared(&self) -> Option<&ID3D12Resource> {
- match self { Self::Shared(buffer) => Some(buffer), Self::Private { .. } | Self::File { .. } => None }
+ match self {
+ Self::Shared(buffer) => Some(buffer),
+ Self::Private(_) | Self::File { .. } | Self::Lazy { .. } => None,
+ }
}
}
impl Drop for CardCpu {
fn drop(&mut self) {
- if let Self::Private { address, size } = self {
- use windows_sys::Win32::System::Memory::{MEM_RELEASE, VirtualFree};
- // SAFETY: the base of this mirror's VirtualAlloc reservation, released once.
- unsafe { VirtualFree(*address as *mut _, 0, MEM_RELEASE) };
- PRIVATE_CPU_BYTES.fetch_sub(*size, Ordering::Relaxed);
- } else if let Self::File { size, .. } = self {
+ if let Self::File { size, .. } = self {
FILE_CPU_BYTES.fetch_sub(*size, Ordering::Relaxed);
}
}
}
-/// Allocate the GPU side first only for the private-mirror experiment. The
-/// stock path keeps its allocation order and neither path allocates an unused mirror.
+/// Allocate the GPU side first for lazy or private CPU mirrors so read-only
+/// card buffers/windows consume zero host RAM until materialized. The stock
+/// path keeps its allocation order and neither path allocates an unused mirror.
fn buffer_sides(size: u64, make_card: fn(u64) -> Option<ID3D12Resource>, counted: &AtomicU64)
-> Option<(ID3D12Resource, *mut u8, Option<CardCpu>)>
{
let host = host()?;
+ if CardCpu::lazy_enabled() {
+ if let Some(gpu) = make_card(size) {
+ return Some((gpu, std::ptr::null_mut(), Some(CardCpu::lazy())));
+ }
+ let (buffer, data) = host.shared_buffer(size)?;
+ return Some((buffer, data, None));
+ }
if CardCpu::private_enabled() {
if let Some(gpu) = make_card(size) {
if let Some((cpu, data)) = CardCpu::allocate(size) {
@@ -1317,10 +1388,14 @@ pub(crate) fn stale_pages(most: usize, say: &mut dyn FnMut(&Shadow, usize, usize
if !crate::host::read_into(lo as *const u8, title) {
continue;
}
+ let data = shadow.cpu_data();
+ if data.is_null() {
+ continue;
+ }
done += hi - lo;
// SAFETY: inside the mapping; nothing is in the air and the
// submission lock is held.
- let held = unsafe { std::slice::from_raw_parts(shadow.data.add(lo - start).cast_const(), hi - lo) };
+ let held = unsafe { std::slice::from_raw_parts(data.add(lo - start).cast_const(), hi - lo) };
if held == title {
continue;
}
@@ -2693,7 +2768,14 @@ fn wide_threads() -> usize {
tracing::info!(n, "threads kept for refreshes on several threads (VICTORY_WIDE_THREADS)");
Some(n)
});
- asked.unwrap_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get() * 3 / 8).clamp(2, 8))
+ static FOUND: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
+ asked.unwrap_or_else(|| {
+ *FOUND.get_or_init(|| {
+ let logical = std::thread::available_parallelism().map_or(4, |n| n.get() * 3 / 8).clamp(2, 8);
+ // `VICTORY_THREADS_BY_CORES=1`: half the physical cores, 2 to 8.
+ crate::cores::sized("victory-wide", logical, |cores| (cores / 2).clamp(2, 8))
+ })
+ })
}
fn run_scoped_helper(workers: &Workers, work: ScopedWork, len: usize, grain: usize, chunks: usize) {
@@ -2907,10 +2989,24 @@ impl Drop for Beside {
/// `copies` (from, to, bytes: apart) begun on the kept threads; the copies
/// are done when the result is dropped.
pub(crate) fn copy_beside(copies: Vec<(usize, usize, usize)>) -> Beside {
- if copies.is_empty() {
+ copy_beside_mixed(copies, Vec::new())
+}
+
+/// `copies` (from, to, bytes: apart) and `title_copies` (title source, to,
+/// bytes: read safely via `copy_mapped`) begun on the kept threads; all copies
+/// are done when the result is dropped.
+pub(crate) fn copy_beside_mixed(
+ copies: Vec<(usize, usize, usize)>,
+ title_copies: Vec<(usize, usize, usize)>,
+) -> Beside {
+ if copies.is_empty() && title_copies.is_empty() {
return Beside(None);
}
- Beside(Some(queued(copy_jobs(copies, false), 0)))
+ let mut jobs = if copies.is_empty() { Vec::new() } else { copy_jobs(copies, false) };
+ if !title_copies.is_empty() {
+ jobs.extend(title_copy_jobs(title_copies));
+ }
+ Beside(Some(queued(jobs, 0)))
}
/// [`wide`], for the host's own work on host copies (a submission's
@@ -3321,6 +3417,39 @@ fn copy_jobs(copies: Vec<(usize, usize, usize)>, stream: bool) -> Vec<Job> {
jobs
}
+/// Like [`copy_jobs`], but reads from title memory safely via
+/// [`crate::host::copy_mapped`] for lazy read-only card copies.
+fn title_copy_jobs(copies: Vec<(usize, usize, usize)>) -> Vec<Job> {
+ let mut jobs: Vec<Job> = Vec::new();
+ let mut group: Vec<(usize, usize, usize)> = Vec::new();
+ let mut bytes = 0;
+ let flush = |group: &mut Vec<(usize, usize, usize)>, jobs: &mut Vec<Job>| {
+ let group = std::mem::take(group);
+ if !group.is_empty() {
+ jobs.push(Box::new(move || {
+ for (src, dst, len) in group {
+ crate::host::copy_mapped(dst as *mut u8, src as *const u8, len, false);
+ }
+ }));
+ }
+ };
+ for (src, dst, len) in copies {
+ let mut at = 0;
+ while at < len {
+ let n = (WIDE_JOB - bytes).min(len - at);
+ group.push((src + at, dst + at, n));
+ at += n;
+ bytes += n;
+ if bytes >= WIDE_JOB {
+ flush(&mut group, &mut jobs);
+ bytes = 0;
+ }
+ }
+ }
+ flush(&mut group, &mut jobs);
+ jobs
+}
+
/// With [`wide_back`]: for each of `work` (a copy not in the card's memory
/// and a range `[address, end)` its shaders may have written, declared and
/// not yet done), the 64 KiB pieces that differ from the snapshot, as
@@ -5627,6 +5756,7 @@ pub(crate) fn let_go_idle() {
idle.into_iter().filter_map(|key| map.remove(&key)).collect()
};
card_late_windows();
+ let_go_idle_buffers();
if !gone.is_empty() {
let (went, bytes) = (gone.len(), gone.iter().map(|s| s.len).sum::<u64>());
crate::host::trail(|| {
@@ -5642,6 +5772,198 @@ pub(crate) fn let_go_idle() {
}
}
+/// When host copies of title buffers (not windows) nothing used for a while
+/// are let go: `VICTORY_BUFFER_COPY_IDLE_S` seconds idle (30 unless set; 0:
+/// never, as before) while the PC has less than
+/// `VICTORY_BUFFER_COPY_IDLE_FREE_MB` of physical memory free (4096 unless
+/// set; 0: whatever is free). As (idle ms, free bytes below which), or None.
+///
+/// Only windows outside buffers were ever let go ([`let_go_idle`]); a title
+/// buffer's copy stayed as long as the title kept the buffer, drawn or not:
+/// 4,355 copies held 6,047 MB of the PC's memory (D3D12 L0 buffers, plus the
+/// card side of those in the card's memory) with 572 MB of it free, and the
+/// system paging (play-20261129-141314).
+fn buffer_idle() -> Option<(u64, u64)> {
+ static POLICY: std::sync::OnceLock<(u64, u64)> = std::sync::OnceLock::new();
+ let &(seconds, free_mb) = POLICY.get_or_init(|| {
+ let read = |name: &str, default: u64| {
+ std::env::var(name).ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(default)
+ };
+ let policy = (read("VICTORY_BUFFER_COPY_IDLE_S", 30), read("VICTORY_BUFFER_COPY_IDLE_FREE_MB", 4096));
+ tracing::info!(
+ "host copies of title buffers idle {} s let go while the PC has under {} MB free (VICTORY_BUFFER_COPY_IDLE_S, 0: never; VICTORY_BUFFER_COPY_IDLE_FREE_MB, 0: always)",
+ policy.0,
+ policy.1
+ );
+ policy
+ });
+ (seconds > 0).then_some((seconds.saturating_mul(1000), free_mb.saturating_mul(1 << 20)))
+}
+
+/// Notes that a title buffer's copy was handed out now, for
+/// [`let_go_idle_buffers`] (windows note it in [`loose`]).
+#[inline]
+fn note_buffer_use(shadow: &Shadow) {
+ if buffer_idle().is_none() {
+ return;
+ }
+ let now = crate::host::moment();
+ if shadow.used.load(Ordering::Relaxed) != now {
+ shadow.used.store(now, Ordering::Relaxed);
+ }
+}
+
+/// Title buffer copies let go idle since the start: copies, bytes of title
+/// memory, bytes of the PC's memory, bytes of the card's.
+static BUFFER_LET_GO: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4];
+
+/// Lets go of the copies of title buffers that nothing used for
+/// [`buffer_idle`]'s time while the PC is short of memory. A copy goes when
+/// - only the table of buffers holds it (no list not yet reset, no pass, no
+/// snapshot) and only it holds its host buffers (no descriptor slot views
+/// them);
+/// - shaders were never declared to write it (what they wrote may live only
+/// in the copy: write-combined memory left on the card, `VICTORY_WC_NO_BACK`),
+/// nor store in it by address ([`Shadow::keep_stores`]), nothing is pending
+/// or landing in it;
+/// - it is no window, not in place, not mapped card memory, no arena's.
+///
+/// Title memory holds all of its bytes then, so the next ask makes a new
+/// copy and copies the buffer again, as on its first use. Taken out of the
+/// table under its write lock, which counts as a change ([`buffers`]):
+/// a thread's remembered answer ([`found`]) is not handed out after it.
+fn let_go_idle_buffers() {
+ const IDLE_FRAMES: u64 = 60;
+ let Some((idle_ms, free_below)) = buffer_idle() else {
+ return;
+ };
+ if free_below > 0 && crate::host::available_physical_ram().is_none_or(|free| free >= free_below) {
+ return;
+ }
+ let_go_buffers_idle_for(idle_ms, IDLE_FRAMES);
+}
+
+/// [`let_go_idle_buffers`] for copies idle `idle_ms` and `idle_frames`;
+/// how many went.
+fn let_go_buffers_idle_for(idle_ms: u64, idle_frames: u64) -> u64 {
+ let idle = |s: &Arc<Shadow>| {
+ Arc::strong_count(s) == 1
+ && !s.window
+ && s.place.is_none()
+ && !s.mapped
+ && s.card.as_ref().is_none_or(|c| c.arena == Arena::No)
+ && !s.written.load(Ordering::Relaxed)
+ // Stores by address nothing declared (`Shadow::keep_stores`) may
+ // live only in the copy.
+ && !s.stores_kept()
+ && !s.has_pending.load(Ordering::Acquire)
+ && !s.landing.load(Ordering::Acquire)
+ && crate::host::long_ago(s.used.load(Ordering::Relaxed), idle_ms, idle_frames)
+ };
+ // Looked for under the read lock; the write lock only when some are.
+ let due: Vec<(u64, usize)> = buffers_read()
+ .map
+ .iter()
+ .filter(|(_, e)| e.shadow.as_ref().is_some_and(idle))
+ .map(|(key, _)| *key)
+ .collect();
+ if due.is_empty() {
+ return 0;
+ }
+ let gone: Vec<Arc<Shadow>> = {
+ let mut map = buffers();
+ due.into_iter()
+ .filter_map(|key| {
+ let entry = map.map.get_mut(&key)?;
+ let s = entry.shadow.as_ref()?;
+ let unheld = idle(s)
+ && crate::host::references(&s.buffer) == 1
+ && s.card.as_ref().is_none_or(|c| c.staging.shared().is_none_or(|b| crate::host::references(b) == 1));
+ if unheld { entry.shadow.take() } else { None }
+ })
+ .collect()
+ };
+ if gone.is_empty() {
+ return 0;
+ }
+ let (mut title, mut ram, mut card) = (0u64, 0u64, 0u64);
+ for s in &gone {
+ title += s.len;
+ match &s.card {
+ Some(c) => {
+ ram += c.size;
+ card += c.size;
+ }
+ None => ram += s.width(),
+ }
+ }
+ let n = gone.len() as u64;
+ let total = [
+ BUFFER_LET_GO[0].fetch_add(n, Ordering::Relaxed) + n,
+ BUFFER_LET_GO[1].fetch_add(title, Ordering::Relaxed) + title,
+ BUFFER_LET_GO[2].fetch_add(ram, Ordering::Relaxed) + ram,
+ BUFFER_LET_GO[3].fetch_add(card, Ordering::Relaxed) + card,
+ ];
+ crate::host::trail(|| format!("sweep: {n} host copies of title buffers let go idle ({} KiB of the PC's memory)", ram >> 10));
+ static LOGGED: AtomicU64 = AtomicU64::new(0);
+ let now = crate::host::coarse_ms();
+ let last = LOGGED.load(Ordering::Relaxed);
+ if (last == 0 || now >= last + 5000) && LOGGED.compare_exchange(last, now.max(1), Ordering::Relaxed, Ordering::Relaxed).is_ok() {
+ tracing::info!(
+ "host copies of title buffers let go idle (VICTORY_BUFFER_COPY_IDLE_S): now {n} ({} MB of the PC's memory, {} MB of the card's); since the start {} copies of {} MB of title memory, {} MB of the PC's memory, {} MB of the card's",
+ ram >> 20,
+ card >> 20,
+ total[0],
+ total[1] >> 20,
+ total[2] >> 20,
+ total[3] >> 20
+ );
+ }
+ for s in gone {
+ crate::host::retire(s);
+ }
+ n
+}
+
+#[cfg(test)]
+mod idle_buffer_tests {
+ use super::*;
+
+ /// A title buffer's copy that only the table holds goes once idle, one
+ /// a caller holds stays, and the next ask makes a new copy with the
+ /// title's bytes.
+ #[test]
+ fn idle_buffer_copies_are_let_go_and_made_again() {
+ use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc};
+ if host().is_none() {
+ return;
+ }
+ const LEN: usize = 1 << 16;
+ // SAFETY: memory of our own that stays (copies of it may outlive the test).
+ let title = unsafe { VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) } as u64;
+ assert_ne!(title, 0);
+ let resource = 0x7e57_0001usize;
+ register(resource, title, LEN as u64);
+ let held = find(title, 256).expect("a copy");
+ let first = held.id();
+ // (Copies other tests left idle may go too: only this one is looked at.)
+ let_go_buffers_idle_for(0, 0);
+ assert!(peek(title, 256).is_some_and(|s| s.id() == first), "a held copy stays");
+ drop(held);
+ assert!(let_go_buffers_idle_for(0, 0) >= 1);
+ assert!(peek(title, 256).is_none(), "an idle copy goes");
+ let again = find(title, 256).expect("made again");
+ assert_ne!(again.id(), first);
+ // One shaders were declared to write never goes.
+ again.written.store(true, Ordering::Relaxed);
+ let id = again.id();
+ drop(again);
+ let_go_buffers_idle_for(0, 0);
+ assert!(peek(title, 256).is_some_and(|s| s.id() == id), "a written copy stays");
+ unregister(resource, title);
+ }
+}
+
/// Host copies alive and the bytes of title memory they copy (counters only:
/// the always-on process memory: line, crate::procmem).
pub(crate) fn live_copies() -> [u64; 2] {
@@ -5727,7 +6049,7 @@ fn same_bytes() {
}
copies.retain(|s| s.place.is_none());
let mapped = copies.iter().filter(|s| s.mapped).count();
- copies.retain(|s| !s.mapped && !s.data.is_null());
+ copies.retain(|s| !s.mapped && !s.cpu_data().is_null());
// Bytes: looked at, whole copies alike, pieces alike (windows,
// buffers, card copies), pieces of zeros; then the host buffers'
@@ -5746,7 +6068,7 @@ fn same_bytes() {
let len = s.len as usize;
let kind = if s.card.is_some() { 2 } else if s.window { 0 } else { 1 };
// SAFETY: the copy is alive (held here) and its mapping `len` bytes.
- let bytes = unsafe { std::slice::from_raw_parts(s.data.cast_const(), len) };
+ let bytes = unsafe { std::slice::from_raw_parts(s.cpu_data().cast_const(), len) };
let mut whole = blake3::Hasher::new();
for piece in bytes.chunks(PIECE) {
let hash = blake3::hash(piece);
@@ -5854,6 +6176,14 @@ impl Shadow {
self.watched.load(Ordering::Relaxed) == NOT_WATCHED
}
+ /// Whether the copy's memory was write-watched by the kernel when last
+ /// asked about (not guarded, not copied whole): its refresh asks the
+ /// journal and reads what was written, without a guard to set again
+ /// (`crate::host::refresh_inline`).
+ pub(crate) fn kernel_watched(&self) -> bool {
+ self.watched.load(Ordering::Relaxed) == 1
+ }
+
/// Whether a submission asks the kernel about the copy's ranges ahead:
/// not of memory that is not watched, nor of view memory, which the
/// kernel would refuse (and with it the ranges asked about together).
@@ -6250,8 +6580,10 @@ impl Shadow {
}
// In the card's memory: no snapshot. What shaders wrote is found on
// the card (`Host::card_before` reads the declared ranges from the
- // lists).
+ // lists). Materialize a lazy CPU mirror before the first shader write
+ // so copy-back merges have the pre-shader reference bytes.
if self.card.is_some() {
+ self.ensure_card_cpu();
pending.push(range);
self.has_pending.store(true, Ordering::Release);
return;
@@ -6804,7 +7136,7 @@ impl Shadow {
let merging = self.merge_write_pages(a / PAGE, e.div_ceil(PAGE));
let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner());
let held = if self.card.is_some() {
- self.data as usize
+ self.cpu_data() as usize
} else {
before.as_mut().map_or(0, |snapshot| snapshot.as_mut_ptr() as usize)
};
@@ -7010,7 +7342,12 @@ impl Shadow {
pub(crate) fn update(&self, address: usize, len: usize) -> usize {
let n = self.update_ranges(address, len);
#[cfg(feature = "diagnostics")]
- crate::facewatch::looked(self.face_side(), address as u64, len as u64, self.data.cast_const());
+ {
+ let data = self.cpu_data();
+ if !data.is_null() {
+ crate::facewatch::looked(self.face_side(), address as u64, len as u64, data.cast_const());
+ }
+ }
n
}
@@ -7347,6 +7684,10 @@ impl Shadow {
// Blocks found differing: how many refreshes in a row.
static DIFFERING: Mutex<Option<std::collections::HashMap<usize, u32>>> = Mutex::new(None);
static SAID: AtomicU64 = AtomicU64::new(0);
+ let data = self.cpu_data();
+ if data.is_null() {
+ return;
+ }
let start = self.start as usize;
let mut title = [0u8; SAMPLE];
let mut at = from;
@@ -7355,7 +7696,7 @@ impl Shadow {
if crate::host::read_into(at as *const u8, &mut title[..n]) {
// SAFETY: `[from, to)` lies inside the buffer (`update`),
// so these bytes are inside the copy's mapping.
- let copy = unsafe { std::slice::from_raw_parts(self.data.add(at - start).cast_const(), n) };
+ let copy = unsafe { std::slice::from_raw_parts(data.add(at - start).cast_const(), n) };
let mut map = DIFFERING.lock().unwrap_or_else(|e| e.into_inner());
let map = map.get_or_insert_with(Default::default);
if copy == &title[..n] {
@@ -7407,6 +7748,38 @@ impl Shadow {
// Bytes the memo keeps from being copied in this refresh: of pages
// the two slots alone would have had copied ([`MEMO_SAVED`]).
let mut memo_kept = 0usize;
+ let first = from / PAGE;
+ let last = (to - 1) / PAGE;
+ if first == last {
+ let copied = &self.copied[first - base];
+ let cur = copied.load(Ordering::Relaxed);
+ let taken = cur.max(ranged);
+ let write = written.first().map_or(0, |&(_, write)| write);
+ if ranged > ranged_slots && !(taken == 0 || write > taken) {
+ let without = cur.max(ranged_slots);
+ if without == 0 || write > without {
+ MEMO_SAVED[2].fetch_add((to - from) as u64, Ordering::Relaxed);
+ }
+ }
+ let mut bytes = 0;
+ if taken == 0 || write > taken {
+ let page = first * PAGE;
+ let parts = if taken == 0 { u16::MAX } else { crate::watch::page_parts_written(first, taken) };
+ for (lo, hi) in crate::watch::part_runs(parts) {
+ let a = from.max(page + lo * (PAGE / 16));
+ let b = to.min(page + hi * (PAGE / 16));
+ if a < b {
+ self.take(a, b, taken != 0);
+ bytes += b - a;
+ }
+ }
+ if page.max(self.start as usize) >= from && (page + PAGE).min((self.start + self.len) as usize) <= to {
+ copied.store(now, Ordering::Release);
+ }
+ }
+ self.stamp_range(from, to, now);
+ return bytes;
+ }
let (mut runs, mut run) = (Vec::new(), None::<(usize, bool)>);
// Pages taken before and written since: in the order of their runs.
let mut again_at: Vec<(usize, u64)> = Vec::new();
@@ -7414,8 +7787,7 @@ impl Shadow {
// lock-free `nothing_new_with` / `nothing_new_single` readers load `copied`
// without `copy_lock`, so stamps must be published only after their bytes land.
let mut stamp: Vec<usize> = Vec::new();
- let last = (to - 1) / PAGE;
- for page in from / PAGE..=last {
+ for page in first..=last {
let write = match writes.peek() {
Some(&&(p, w)) if p == page => {
writes.next();
@@ -7472,6 +7844,16 @@ impl Shadow {
for i in stamp {
self.copied[i].store(now, Ordering::Release);
}
+ self.stamp_range(from, to, now);
+ if memo_kept != 0 {
+ MEMO_SAVED[2].fetch_add(memo_kept as u64, Ordering::Relaxed);
+ }
+ bytes
+ }
+
+ /// Publish only after the corresponding bytes are in the host copy.
+ /// The caller holds `copy_lock` throughout the copy and the publication.
+ fn stamp_range(&self, from: usize, to: usize, now: u64) {
if crate::watch::light() {
// All of the range is in the copy as of this asking.
let prev1_len = self.ranged[1].1.load(Ordering::Relaxed).saturating_sub(self.ranged[1].0.load(Ordering::Relaxed));
@@ -7497,10 +7879,6 @@ impl Shadow {
}
self.ranged_seq.store(seq + 2, Ordering::Release);
}
- if memo_kept != 0 {
- MEMO_SAVED[2].fetch_add(memo_kept as u64, Ordering::Relaxed);
- }
- bytes
}
/// [`Shadow::take`] of `runs` (from, to, known), on several threads if
@@ -7579,6 +7957,13 @@ impl Shadow {
at = next;
}
}
+ let data = self.cpu_data();
+ if data.is_null() {
+ return self.copy(from, to);
+ }
+ if runs.len() == 1 && !runs[0].2 {
+ return self.copy(runs[0].0, runs[0].1);
+ }
let mut dirty_runs: Vec<(usize, usize)> = Vec::new();
let (mut echo_same, mut echo_diff) = (0u64, 0u64);
TITLE.with_borrow_mut(|title| {
@@ -7597,7 +7982,7 @@ impl Shadow {
// SAFETY: inside the mapping of the copy's CPU side, which
// nothing else reads or writes there: no shader's range
// holds it, and the parts of a refresh lie apart.
- let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at - start), next - at) };
+ let held = unsafe { std::slice::from_raw_parts_mut(data.add(at - start), next - at) };
if title == held {
echo_same += (next - at) as u64;
} else {
@@ -7639,6 +8024,10 @@ impl Shadow {
}
return self.copy(from, to);
};
+ let data = self.ensure_card_cpu();
+ if data.is_null() {
+ return self.copy(from, to);
+ }
let whole = !known && card.before.get().is_none();
let start = self.start as usize;
let upcheck = crate::host::upcheck::on();
@@ -7656,7 +8045,7 @@ impl Shadow {
// nothing else reads or writes there (the card copies from
// it): no shader's range holds it, and the parts of a
// refresh lie apart.
- let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at - start), n) };
+ let held = unsafe { std::slice::from_raw_parts_mut(data.add(at - start), n) };
let was = upcheck.then(|| held.to_vec());
if whole {
held.copy_from_slice(title);
@@ -7708,13 +8097,24 @@ impl Shadow {
fn copy(&self, from: usize, to: usize) -> usize {
let (start, end) = (self.start as usize, (self.start + self.len) as usize);
let (from, to) = (from.max(start), to.min(end));
+ if from >= to {
+ return 0;
+ }
+ let data = self.cpu_data();
+ if self.card.is_some() && data.is_null() {
+ // Lazy read-only card copy: `send::take` reads `[from, to)`
+ // directly from title memory via `copy_mapped`.
+ self.changed(from - start, to - start);
+ self.card_changed(from - start, to - start);
+ return to - from;
+ }
// SAFETY: inside the mapping (`from` and `to` are within the buffer).
- let at = unsafe { self.data.add(from - start) };
- if self.card.is_some() && from < to && crate::host::upcheck::on() {
+ let at = unsafe { data.add(from - start) };
+ if self.card.is_some() && crate::host::upcheck::on() {
for_pieces_of(from - start, to - start, |a, b| {
let was = self.card_held(a, b - a);
// SAFETY: inside the mapping, as above.
- crate::host::copy_mapped(unsafe { self.data.add(a) }, (start + a) as *const u8, b - a, false);
+ crate::host::copy_mapped(unsafe { data.add(a) }, (start + a) as *const u8, b - a, false);
crate::host::upcheck::note(self.id, a, &was, &self.card_held(a, b - a));
});
} else {
@@ -7726,6 +8126,71 @@ impl Shadow {
to - from
}
+ /// Pointer to the copy's CPU-side bytes, or null for a lazy read-only card
+ /// copy that has not needed a CPU mirror yet.
+ fn cpu_data(&self) -> *mut u8 {
+ match &self.card {
+ Some(card) => match &card.staging {
+ CardCpu::Lazy { cpu_ptr, .. } => cpu_ptr.load(Ordering::Acquire),
+ CardCpu::Shared(_) | CardCpu::Private(_) | CardCpu::File { .. } => self.data,
+ },
+ None => self.data,
+ }
+ }
+
+ /// Materializes a lazy card copy's demand-paged CPU mirror on first need,
+ /// populating and marking dirty only the ranges previously sent to the
+ /// card so untouched pages stay zeroed without faulting physical RAM.
+ fn ensure_card_cpu(&self) -> *mut u8 {
+ let Some(card) = &self.card else {
+ return self.data;
+ };
+ let CardCpu::Lazy { cpu, cpu_init, cpu_ptr, ever_sent } = &card.staging else {
+ return self.data;
+ };
+ let ptr = cpu_ptr.load(Ordering::Acquire);
+ if !ptr.is_null() {
+ return ptr;
+ }
+ let _init = cpu_init.lock().unwrap_or_else(|e| e.into_inner());
+ let ptr = cpu_ptr.load(Ordering::Acquire);
+ if !ptr.is_null() {
+ return ptr;
+ }
+ let Some(buf) = VirtualBuf::new(self.len) else {
+ tracing::warn!(start = format_args!("{:#x}", self.start), len = self.len, "no CPU side for card buffer");
+ return std::ptr::null_mut();
+ };
+ let ptr = buf.ptr;
+ let mut ever = {
+ let mut recorded = ever_sent.lock().unwrap_or_else(|e| e.into_inner());
+ joined(std::mem::take(&mut *recorded))
+ };
+ let start = self.start as usize;
+ for &(a, b) in &ever {
+ // SAFETY: `a < b <= self.len`, inside `buf`.
+ crate::host::copy_mapped(unsafe { ptr.add(a) }, (start + a) as *const u8, b - a, false);
+ }
+ let _ = cpu.set(buf);
+ cpu_ptr.store(ptr, Ordering::Release);
+ let extra = {
+ let mut recorded = ever_sent.lock().unwrap_or_else(|e| e.into_inner());
+ joined(std::mem::take(&mut *recorded))
+ };
+ if !extra.is_empty() {
+ for &(a, b) in &extra {
+ // SAFETY: `a < b <= self.len`, inside `buf`.
+ crate::host::copy_mapped(unsafe { ptr.add(a) }, (start + a) as *const u8, b - a, false);
+ }
+ ever.extend(extra);
+ ever = joined(ever);
+ }
+ if !ever.is_empty() {
+ self.card_changed_runs(ever.into_iter());
+ }
+ ptr
+ }
+
/// Whether shaders read and write this copy in the card's own memory
/// ([`cards`]).
pub(crate) fn carded(&self) -> bool {
@@ -7735,6 +8200,7 @@ impl Shadow {
/// Shaders store in it what is not declared: from here on only the dwords
/// the title changes go up ([`by_address`]).
pub(crate) fn keep_stores(&self) {
+ self.ensure_card_cpu();
self.changes_only.store(true, Ordering::Relaxed);
}
@@ -7765,7 +8231,23 @@ impl Shadow {
return;
}
let mut dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner());
- push_dirty_runs(&mut dirty, runs);
+ let mut ever = match &card.staging {
+ CardCpu::Lazy { cpu_ptr, ever_sent, .. } if cpu_ptr.load(Ordering::Acquire).is_null() => {
+ Some(ever_sent.lock().unwrap_or_else(|e| e.into_inner()))
+ }
+ _ => None,
+ };
+ if let Some(ever) = &mut ever {
+ for (from, to) in runs {
+ push_dirty_runs(&mut dirty, std::iter::once((from, to)));
+ push_dirty_runs(ever, std::iter::once((from, to)));
+ }
+ if ever.len() > 256 {
+ **ever = joined(std::mem::take(&mut **ever));
+ }
+ } else {
+ push_dirty_runs(&mut dirty, runs);
+ }
// (Under the lock: what takes the list sees it or finds it set.)
if !card.touched.swap(true, Ordering::AcqRel)
&& let Some(me) = card.me.get()
@@ -7796,9 +8278,12 @@ impl Shadow {
(self.start as usize + to).div_ceil(PAGE),
);
if self.card.is_some() {
- // SAFETY: inside the mapping of the CPU's side, in a range no
- // refresh writes; the lock keeps the landing out.
- unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), self.data.add(from), bytes.len()) };
+ let data = self.ensure_card_cpu();
+ if !data.is_null() {
+ // SAFETY: inside the mapping of the CPU's side, in a range no
+ // refresh writes; the lock keeps the landing out.
+ unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), data.add(from), bytes.len()) };
+ }
} else if let Some(snapshot) = self.before.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
// SAFETY: the snapshot's allocation holds the copy's length.
unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), snapshot.as_mut_ptr().add(from), bytes.len()) };
@@ -7806,9 +8291,9 @@ impl Shadow {
self.changed(from, to);
}
- /// Of a copy in the card's memory: where its CPU side is.
+ /// Of a copy in the card's memory: where its CPU side is (null while lazy).
pub(crate) fn card_data(&self) -> *const u8 {
- self.data
+ self.cpu_data().cast_const()
}
/// Diagnostics: of a copy in the card's memory, what its CPU side holds
@@ -7818,9 +8303,15 @@ impl Shadow {
if self.card.is_none() || at >= to {
return Vec::new();
}
+ let data = self.cpu_data();
+ if data.is_null() {
+ let mut out = vec![0u8; to - at];
+ crate::host::copy_mapped(out.as_mut_ptr(), (self.start as usize + at) as *const u8, to - at, false);
+ return out;
+ }
// SAFETY: inside the mapping; the caller holds the submission lock,
// under which it is written but for what is being landed.
- unsafe { std::slice::from_raw_parts(self.data.add(at).cast_const(), to - at) }.to_vec()
+ unsafe { std::slice::from_raw_parts(data.add(at).cast_const(), to - at) }.to_vec()
}
/// Diagnostics: the offsets whose bytes have not gone to the card's side
@@ -7981,9 +8472,13 @@ impl Shadow {
if self.card.is_none() || at + gpu.len() > self.len as usize {
return 0;
}
+ let data = self.cpu_data();
+ if data.is_null() {
+ return 0;
+ }
// SAFETY: inside the mapping (checked above); only the submitting
// thread writes it.
- let old = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), gpu.len()) };
+ let old = unsafe { std::slice::from_raw_parts_mut(data.add(at), gpu.len()) };
let Some(first) = first_difference(gpu, old) else {
return 0;
};
@@ -8052,11 +8547,15 @@ impl Shadow {
return 0;
}
let _side = self.before.lock().unwrap_or_else(|e| e.into_inner());
+ let data = self.cpu_data();
+ if data.is_null() {
+ return 0;
+ }
// SAFETY: inside the mapping (checked above). The offsets are in a
// range declared and not done with, which no refresh writes; what
// does write it (the title's bytes put in under shader writes)
// holds the lock held here.
- let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), gpu.len()) };
+ let held = unsafe { std::slice::from_raw_parts_mut(data.add(at), gpu.len()) };
let Some(first) = first_difference(gpu, held) else {
return 0;
};
@@ -8121,6 +8620,27 @@ impl Shadow {
shadow
}
+ /// A lazy card copy with no host buffer and no initial CPU side.
+ pub(crate) fn unbacked_lazy_card(start: u64, len: u64) -> Arc<Shadow> {
+ // SAFETY: an interface pointer nothing calls.
+ let none = || unsafe { std::mem::transmute::<usize, ID3D12Resource>(8) };
+ let mut shadow = Shadow::new(none(), std::ptr::null_mut(), 0, start, len);
+ shadow.card = Some(Card {
+ staging: CardCpu::lazy(),
+ before: std::sync::OnceLock::new(),
+ before_lock: Mutex::new(()),
+ dirty: Mutex::default(),
+ sent: Mutex::default(),
+ touched: Default::default(),
+ me: std::sync::OnceLock::new(),
+ size: len.next_multiple_of(PIECE as u64),
+ arena: Arena::No,
+ });
+ let shadow = Arc::new(shadow);
+ std::mem::forget(shadow.clone());
+ shadow
+ }
+
/// What shaders wrote goes into title memory ([`put_changed`]).
pub(crate) fn put(at: usize, title: &[u8], merged: &[u8]) {
put_changed(at, title, merged);
@@ -8181,6 +8701,10 @@ impl Shadow {
skip
};
let skip = if skip.is_empty() { skip } else { joined(skip) };
+ let data = self.cpu_data();
+ if data.is_null() {
+ return 0;
+ }
let mut parts: Vec<(usize, usize)> = Vec::new();
let mut put = 0;
for &(lo, hi, now) in pieces {
@@ -8199,7 +8723,7 @@ impl Shadow {
// Where title memory is not mapped the CPU's side keeps what
// the card wrote, as before.
let merged =
- unsafe { crate::land::piece(self.start as usize + lo, now as *const u8, self.data.add(lo), slice, true, notes, self) };
+ unsafe { crate::land::piece(self.start as usize + lo, now as *const u8, data.add(lo), slice, true, notes, self) };
self.walls_merged(hi - lo, merged as usize);
if merged > 0 {
self.check_gpu_ro_merge(self.start as usize + lo, hi - lo, "land_card");
@@ -8321,6 +8845,60 @@ mod land_tests {
assert_eq!(FILE_CPU_BYTES.load(Ordering::Relaxed), 0);
}
+ #[test]
+ fn lazy_card_copy_stays_unallocated_until_written_and_materializes_sent_ranges() {
+ const LEN: usize = 256 * 1024;
+ let mut title = vec![0u8; LEN];
+ title[4096..8192].fill(0x5A);
+ title[65536..69632].fill(0xC3);
+ let start = title.as_ptr() as u64;
+ let shadow = Shadow::unbacked_lazy_card(start, LEN as u64);
+
+ // Read-only card copy starts with no CPU mirror allocated.
+ assert!(shadow.card_data().is_null());
+ assert_eq!(shadow.copy(start as usize + 4096, start as usize + 8192), 4096);
+ assert!(shadow.card_data().is_null());
+ assert_eq!(shadow.take_dirty(), vec![(4096, 8192)]);
+
+ // Diagnostic `card_held` reads directly from title memory while lazy.
+ assert_eq!(shadow.card_held(4096, 16), vec![0x5A; 16]);
+ assert!(shadow.card_data().is_null());
+
+ // Declaring a shader write materializes the CPU mirror and populates
+ // previously sent ranges without touching unsent pages.
+ shadow.writing(start as usize + 4096, 4096);
+ let ptr = shadow.card_data();
+ assert!(!ptr.is_null());
+ // SAFETY: materialized mirror owns `LEN` readable bytes.
+ let mirrored = unsafe { std::slice::from_raw_parts(ptr, LEN) };
+ assert!(mirrored[4096..8192].iter().all(|&b| b == 0x5A));
+ assert!(mirrored[65536..69632].iter().all(|&b| b == 0));
+ assert_eq!(shadow.take_dirty(), vec![(4096, 8192)]);
+ }
+
+ #[test]
+ fn lazy_card_keep_stores_and_placed_copy_materialize_cpu_mirror() {
+ const LEN: usize = 64 * 1024;
+ let title = vec![0x33u8; LEN];
+ let start = title.as_ptr() as u64;
+
+ let s1 = Shadow::unbacked_lazy_card(start, LEN as u64);
+ assert!(s1.card_data().is_null());
+ s1.keep_stores();
+ assert!(!s1.card_data().is_null());
+ assert!(s1.stores_kept());
+
+ let s2 = Shadow::unbacked_lazy_card(start, LEN as u64);
+ assert!(s2.card_data().is_null());
+ let patch = [0x99u8; 32];
+ s2.placed_copy(start as usize + 128, &patch);
+ let ptr = s2.card_data();
+ assert!(!ptr.is_null());
+ // SAFETY: materialized mirror owns `LEN` readable bytes.
+ let slice = unsafe { std::slice::from_raw_parts(ptr.add(128), 32) };
+ assert_eq!(slice, &patch);
+ }
+
/// A copy in the card's memory of title memory at `title` (its card side
/// is never looked at here), all bytes 0 on the CPU's side.
fn copy_of(title: usize, len: usize) -> Option<Shadow> {
@@ -8633,7 +9211,11 @@ fn found(address: u64, len: u64) -> Option<Arc<Shadow>> {
// Whoever takes the map to let a copy go that nobody holds finds it held
// now, or had counted before: then it is not handed out.
std::sync::atomic::fence(Ordering::SeqCst);
- (BUFFERS_CHANGED.load(Ordering::SeqCst) == changed).then_some(shadow)
+ if BUFFERS_CHANGED.load(Ordering::SeqCst) != changed {
+ return None;
+ }
+ note_buffer_use(&shadow);
+ Some(shadow)
}
/// Remembers an answer given while `changed` was the count.
@@ -8980,6 +9562,7 @@ fn lookup_buffer(address: u64, len: u64) -> BufferHit {
match find_buffer(&state.map, state.max_size(), address, end).and_then(|k| state.map.get(&k)) {
// The copy is made already (nearly always).
Some(Entry { shadow: Some(shadow), .. }) => {
+ note_buffer_use(shadow);
if quick {
// (Nobody changes the map while this lock is held.)
remember(address, len, BUFFERS_CHANGED.load(Ordering::SeqCst), shadow);
@@ -9106,6 +9689,8 @@ fn lookup_buffer(address: u64, len: u64) -> BufferHit {
carded(&shadow);
}
entry.shadow = Some(shadow);
+ } else if let Some(shadow) = &entry.shadow {
+ note_buffer_use(shadow);
}
BufferHit::Found(entry.shadow.clone())
}
diff --git a/crates/victory-gpu/src/streamline.rs b/crates/victory-gpu/src/streamline.rs
index 9096102..889342d 100644
--- a/crates/victory-gpu/src/streamline.rs
+++ b/crates/victory-gpu/src/streamline.rs
@@ -2238,8 +2238,9 @@ fn record_mode(list: *mut c_void, textures: &Textures, camera: &plan::Camera, pr
// upscaling was dropped (a black picture). DLSS takes any render between the mode's
// minimum and maximum: where the optimal size is smaller than the scene but the range
// holds it, the mode is offered at its maximum. `VICTORY_DLSS_RANGE=0`: as before.
- // Decided here, not cached: the same output and mode see other render sizes.
- let range = std::env::var_os("VICTORY_DLSS_RANGE").is_none_or(|v| v != "0");
+ // Decided here, not cached per mode: the same output and mode see other render sizes.
+ static DLSS_RANGE: OnceLock<bool> = OnceLock::new();
+ let range = *DLSS_RANGE.get_or_init(|| std::env::var_os("VICTORY_DLSS_RANGE").is_none_or(|v| v != "0"));
let render = camera.render;
let optimal = |calls: &mut Calls, mode: u32| -> Option<[u32; 2]> {
let [opt, min, max] = answered(calls, mode)?;
@@ -2443,18 +2444,22 @@ pub(crate) fn before_target_draw(
let composite = triangle && INTERFACE_COMPOSITE.iter().all(|hash| pipeline.stages.iter().any(|s| s.shader.hash == *hash));
if !composite {
HUD_COUNTS[HUD_OTHERS].fetch_add(1, Relaxed);
- static SEEN: Mutex<Vec<usize>> = Mutex::new(Vec::new());
- let key = std::ptr::from_ref(pipeline) as usize;
- let mut seen = lock(&SEEN);
- if !seen.contains(&key) && seen.len() < 24 {
- seen.push(key);
- tracing::info!(
- pipeline = %pipeline.name,
- state = %pipeline.state,
- triangle,
- after_the_copy_in_its_list = list.hudless() != 0,
- "DLSS Frame Generation: this pipeline draws into the texture the title presents (the scene's composite does; an interface drawn here before the interface composite would be in the colour without the interface)"
- );
+ static SEEN_COUNT: AtomicUsize = AtomicUsize::new(0);
+ if SEEN_COUNT.load(Relaxed) < 24 {
+ static SEEN: Mutex<Vec<usize>> = Mutex::new(Vec::new());
+ let key = std::ptr::from_ref(pipeline) as usize;
+ let mut seen = lock(&SEEN);
+ if !seen.contains(&key) && seen.len() < 24 {
+ seen.push(key);
+ SEEN_COUNT.store(seen.len(), Relaxed);
+ tracing::info!(
+ pipeline = %pipeline.name,
+ state = %pipeline.state,
+ triangle,
+ after_the_copy_in_its_list = list.hudless() != 0,
+ "DLSS Frame Generation: this pipeline draws into the texture the title presents (the scene's composite does; an interface drawn here before the interface composite would be in the colour without the interface)"
+ );
+ }
}
return;
}
@@ -2790,6 +2795,12 @@ pub(crate) fn present_begins(frame: u64, planes: Planes<'_>, video: bool) -> Opt
}
if calls.framegen_on {
FG_ON.fetch_add(1, Relaxed);
+ let now = crate::host::now_ms().max(1);
+ // (After a gap as long as `FG_GAP_MS`, its resources may be made anew: counted from now.)
+ let gap = now.saturating_sub(FG_PRESENTED_MS.swap(now, Relaxed)) >= FG_GAP_MS;
+ if gap || FG_PRESENTING_SINCE_MS.load(Relaxed) == 0 {
+ FG_PRESENTING_SINCE_MS.store(now, Relaxed);
+ }
// What it takes of the card's memory: before its first present and
// some seconds of presents later.
let presents = FG_ON_ALL.fetch_add(1, Relaxed) + 1;
@@ -2805,6 +2816,10 @@ pub(crate) fn present_begins(frame: u64, planes: Planes<'_>, video: bool) -> Opt
}
} else {
FG_OFF.fetch_add(1, Relaxed);
+ // (A pause of frame generation shorter than `FG_GAP_MS` is no break.)
+ if crate::host::now_ms().saturating_sub(FG_PRESENTED_MS.load(Relaxed)) >= FG_GAP_MS {
+ FG_PRESENTING_SINCE_MS.store(0, Relaxed);
+ }
}
drop(calls);
mark(abi::PRESENT_START);
@@ -2908,6 +2923,29 @@ pub(crate) fn framegen_live() -> bool {
FG_READY.load(Acquire) && SWAP_CHAIN_PROXIED.load(Acquire) || fsr::live_swap_chain()
}
+/// When (`crate::host::now_ms`, from 1) the presents last began to have DLSS frame generation on
+/// without a break; 0 while they have it off.
+static FG_PRESENTING_SINCE_MS: AtomicU64 = AtomicU64::new(0);
+/// When the last present with DLSS frame generation on was (`crate::host::now_ms`).
+static FG_PRESENTED_MS: AtomicU64 = AtomicU64::new(0);
+/// Presents without frame generation for less than this long (a menu, a load, a present the
+/// title made without upscaling) do not break [`FG_PRESENTING_SINCE_MS`]: its resources stay
+/// made (`DLSSG_RETAIN_RESOURCES_WHEN_OFF`), and the texture line would flap between two
+/// heights at every pause (`crate::resource::room_line`).
+const FG_GAP_MS: u64 = 10_000;
+
+/// For how long, in ms, the presents have had DLSS frame generation on without a break: `None`
+/// while it is off. Some seconds in, its own resources are made and the system counts them in
+/// the card's use (`crate::resource::room_line`).
+pub(crate) fn framegen_presenting_ms() -> Option<u64> {
+ let now = crate::host::now_ms();
+ match FG_PRESENTING_SINCE_MS.load(Relaxed) {
+ 0 => None,
+ _ if now.saturating_sub(FG_PRESENTED_MS.load(Relaxed)) >= FG_GAP_MS => None,
+ since => Some(now.saturating_sub(since)),
+ }
+}
+
/// Which frame generation provider is ready at the presenter.
pub(crate) fn framegen_kind() -> Option<&'static str> {
if FG_READY.load(Acquire) && SWAP_CHAIN_PROXIED.load(Acquire) {
diff --git a/crates/victory-gpu/src/streamline/fg_rect.rs b/crates/victory-gpu/src/streamline/fg_rect.rs
index 05f964a..cd526a4 100644
--- a/crates/victory-gpu/src/streamline/fg_rect.rs
+++ b/crates/victory-gpu/src/streamline/fg_rect.rs
@@ -250,8 +250,6 @@ pub(crate) struct Bars {
clear: bool,
hysteresis: Hysteresis,
slots: Vec<Slot>,
- /// Resources replaced while a list may still use them.
- kept: Vec<ID3D12Resource>,
zero: Option<(ID3D12Resource, u64)>,
frame: u64,
/// The band last given, and the one last logged.
@@ -272,7 +270,7 @@ impl Bars {
if mode != Mode::Off || clear {
tracing::info!(?mode, clear, "FSR 3 frame generation: generation rectangle switches");
}
- Bars { mode, clear, hysteresis: Hysteresis::default(), slots: Vec::new(), kept: Vec::new(), zero: None, frame: 0, band: None, logged: None }
+ Bars { mode, clear, hysteresis: Hysteresis::default(), slots: Vec::new(), zero: None, frame: 0, band: None, logged: None }
}
/// The band the configuration names (`None`: the whole back buffer).
@@ -363,8 +361,9 @@ impl Bars {
]
};
let result = detected(runs(false), runs(true), layout.display_height.max(display));
- // SAFETY: mapped above.
- unsafe { slot.buffer.Unmap(0, None) };
+ // SAFETY: mapped above; read-only map wrote no bytes back to the buffer.
+ let written = D3D12_RANGE { Begin: 0, End: 0 };
+ unsafe { slot.buffer.Unmap(0, Some(&written)) };
Some(result)
}
@@ -402,7 +401,7 @@ impl Bars {
let fresh = Slot { buffer, size, layout: None };
if index < self.slots.len() {
let old = std::mem::replace(&mut self.slots[index], fresh);
- self.kept.push(old.buffer);
+ crate::host::retire_resource(old.buffer);
} else {
self.slots.resize_with(index, || Slot { buffer: fresh.buffer.clone(), size: 0, layout: None });
self.slots.push(fresh);
@@ -475,7 +474,7 @@ impl Bars {
let need = pitch * u64::from(rows);
if self.zero.as_ref().is_none_or(|(_, size)| *size < need) {
if let Some((old, _)) = self.zero.take() {
- self.kept.push(old);
+ crate::host::retire_resource(old);
}
self.zero = host.upload_buffer(need).map(|(buffer, _)| (buffer, need));
}
diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs
index f487e0f..078df17 100644
--- a/crates/victory-gpu/src/watch.rs
+++ b/crates/victory-gpu/src/watch.rs
@@ -95,6 +95,10 @@ pub(crate) fn parts_written(pages: &[(usize, u64)]) -> Vec<u16> {
pages.iter().map(|&(page, taken)| j.parts_since(page, taken)).collect()
}
+pub(crate) fn page_parts_written(page: usize, taken: u64) -> u16 {
+ journal().parts_since(page, taken)
+}
+
/// Consecutive written 4 KiB parts within one 64 KiB page, in address order.
pub(crate) fn part_runs(parts: u16) -> impl Iterator<Item = (usize, usize)> {
// Widen so clearing a run ending at bit 16 is an ordinary shift.
@@ -1422,16 +1426,45 @@ pub(crate) fn wrote(at: usize, len: usize) {
// PR 410): answers older than the writes in them made every refresh
// until the next asking copy the pages again.
j.ahead_asked = now;
+ let parts = |page: usize| if wrote_parts_on() { parts_met(page, at, len) } else { WHOLE };
for page in at / PAGE..at.saturating_add(len).div_ceil(PAGE) {
- j.note(page, WHOLE, now);
+ j.note(page, parts(page), now);
}
- for (_, others) in elsewhere(at, len) {
+ for (page, others) in elsewhere(at, len) {
+ // The same bytes of the page, wherever else it is shown.
+ let parts = parts(page / PAGE);
for other in others {
- j.note(other / PAGE, WHOLE, now);
+ j.note(other / PAGE, parts, now);
}
}
}
+/// Whether [`wrote`] marks only the 4 KiB parts of a page that a write of
+/// ours met (`VICTORY_WROTE_PARTS=0`: the whole 64 KiB page, as before).
+///
+/// The title's buffer copies done at submission are about 14,000 a frame of
+/// about 480 bytes each. Marked whole, each made the next refresh of every
+/// copy holding its page take all 16 parts again, and send them up, where
+/// one part changed. The parts are what the kernel's answers keep already
+/// (`VICTORY_PAGE_PARTS`), so a refresh trims to them the same way.
+fn wrote_parts_on() -> bool {
+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var_os("VICTORY_WROTE_PARTS").is_none_or(|v| v != "0"))
+}
+
+/// The 4 KiB parts of page `page` (a number of [`PAGE`]s) that
+/// `[at, at + len)` meets, a bit each; none if it does not meet the page.
+fn parts_met(page: usize, at: usize, len: usize) -> u16 {
+ let start = page.saturating_mul(PAGE);
+ let (from, to) = (at.max(start), at.saturating_add(len).min(start.saturating_add(PAGE)));
+ if from >= to {
+ return 0;
+ }
+ let (first, last) = ((from - start) / KERNEL_PAGE, (to - 1 - start) / KERNEL_PAGE);
+ let bits = (1u32 << (last + 1)) - (1u32 << first);
+ if bits as u16 == WHOLE { WHOLE } else { bits as u16 }
+}
+
/// The blocks of `[at, at + len)` whose pages the title shows at other
/// addresses too, and there.
fn elsewhere(at: usize, len: usize) -> Vec<(usize, Vec<usize>)> {
@@ -4849,6 +4882,27 @@ mod parts_tests {
assert!(!table.all_within(high, high + 1, &one, 0));
assert!(table.all_within(high, high + 1, &one, 12));
}
+
+ #[test]
+ fn a_write_of_ours_meets_only_its_parts() {
+ let page = 5;
+ let start = page * PAGE;
+ // 480 bytes inside part 3.
+ assert_eq!(parts_met(page, start + 3 * KERNEL_PAGE + 16, 480), 0b1000);
+ // Across the line between parts 3 and 4.
+ assert_eq!(parts_met(page, start + 4 * KERNEL_PAGE - 8, 16), 0b1_1000);
+ // Ending right at a part's end: that part only.
+ assert_eq!(parts_met(page, start, KERNEL_PAGE), 0b1);
+ // From the page before into part 0, and from part 15 into the next page.
+ assert_eq!(parts_met(page, start - 100, 200), 0b1);
+ assert_eq!(parts_met(page, start + PAGE - 1, 2), 1 << 15);
+ // The whole page, and more.
+ assert_eq!(parts_met(page, start, PAGE), WHOLE);
+ assert_eq!(parts_met(page, start - 1, PAGE + 2), WHOLE);
+ // Not on the page.
+ assert_eq!(parts_met(page, start + PAGE, 64), 0);
+ assert_eq!(parts_met(page, start - 64, 64), 0);
+ }
}
#[cfg(test)]
diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs
index 20fc1ed..2976504 100644
--- a/crates/victory-hle/src/modules/dstorage.rs
+++ b/crates/victory-hle/src/modules/dstorage.rs
@@ -21,6 +21,8 @@
#![allow(non_snake_case)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]
+mod stream_cache;
+
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
use std::ffi::{CStr, c_char, c_void};
use std::os::windows::fs::FileExt;
@@ -172,7 +174,7 @@ type Factory = *const Object;
/// Opens `path` for reading; the file object owns the handle.
extern "system" fn open_file(_: Factory, path: *const u16, iid: *const Guid, out: Out) -> HRESULT {
const GENERIC_READ: u32 = 0x8000_0000;
- const FILE_SHARE_READ: u32 = 1;
+ const FILE_SHARE_READ_WRITE: u32 = 1 | 2;
const OPEN_EXISTING: u32 = 3;
if path.is_null() {
return E_INVALIDARG;
@@ -181,7 +183,7 @@ extern "system" fn open_file(_: Factory, path: *const u16, iid: *const Guid, out
let handle = super::files::CreateFileW(
path,
GENERIC_READ,
- FILE_SHARE_READ,
+ FILE_SHARE_READ_WRITE,
std::ptr::null(),
OPEN_EXISTING,
0,
@@ -201,9 +203,18 @@ extern "system" fn open_file(_: Factory, path: *const u16, iid: *const Guid, out
tracing::info!(path = name, iid = iid_text(iid), "dstorage: file opened");
// SAFETY: a handle we just opened and nobody else owns.
let file = unsafe { std::fs::File::from_raw_handle(handle) };
+ stream_cache::StreamCache::global().note_archive_file(&file, &kept);
+ let file_id = file.metadata().ok().map_or(0, |meta| {
+ let mtime_ns = meta
+ .modified()
+ .ok()
+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
+ .map_or(0, |d| d.as_nanos());
+ stream_cache::file_identity(&kept, meta.len(), mtime_ns)
+ });
let files = Files::new(file, Io::chosen());
let path = kept.encode_utf16().collect();
- let file = File { files, path, name: kept.clone() };
+ let file = File { files, file_id, path, name: kept.clone() };
let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), file);
if stream_log::on() {
stream_log::line(format_args!("F\t{:x}\t{kept}", file as usize));
@@ -414,6 +425,7 @@ static FACTORY_VTABLE: Methods<16> = Methods([
struct File {
files: Files,
+ file_id: u64,
/// The path the title opened it by, for what is said of a request of
/// it that fails ([`source_path`]).
name: String,
@@ -421,6 +433,11 @@ struct File {
path: Vec<u16>,
}
+fn elevator_on() -> bool {
+ static ON: OnceLock<bool> = OnceLock::new();
+ *ON.get_or_init(|| std::env::var_os("VICTORY_DSTORAGE_ELEVATOR").is_none_or(|v| v != "0"))
+}
+
/// The path of the file `request` reads from; empty for a request whose
/// source is memory. A request that fails says it (#812: every chunk of two
/// entries failed, and only the order of the log said which archive).
@@ -579,10 +596,17 @@ impl Files {
/// Reads guest destinations through the original retryable Win32 path.
fn read_at(&self, out: &mut [u8], offset: u64) -> std::io::Result<usize> {
- use windows_sys::Win32::Storage::FileSystem::{FILE_FLAG_NO_BUFFERING, FILE_FLAG_OVERLAPPED};
+ use windows_sys::Win32::Storage::FileSystem::{
+ FILE_FLAG_NO_BUFFERING, FILE_FLAG_OVERLAPPED, FILE_FLAG_SEQUENTIAL_SCAN,
+ };
+ let seq = if stream_cache::StreamCache::global().hdd_active() {
+ FILE_FLAG_SEQUENTIAL_SCAN
+ } else {
+ 0
+ };
let flags = match self.io {
- Io::One | Io::Handles | Io::Windows => 0,
- Io::Overlapped => FILE_FLAG_OVERLAPPED,
+ Io::One | Io::Handles | Io::Windows => seq,
+ Io::Overlapped => FILE_FLAG_OVERLAPPED | seq,
Io::Direct => FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING,
};
let other = match self.others.len() {
@@ -632,7 +656,7 @@ fn reopen(file: &std::fs::File, flags: u32) -> Option<std::fs::File> {
}
/// A read through a handle opened for overlapped reads, waited for.
-fn read_overlapped(file: &std::fs::File, out: &mut [u8], offset: u64) -> std::io::Result<usize> {
+pub(super) fn read_overlapped(file: &std::fs::File, out: &mut [u8], offset: u64) -> std::io::Result<usize> {
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Foundation::{CloseHandle, ERROR_HANDLE_EOF, ERROR_IO_PENDING, HANDLE};
use windows_sys::Win32::Storage::FileSystem::ReadFile;
@@ -980,6 +1004,7 @@ struct Lanes {
/// BCPack bytes written and time spent on them.
bcpack: (u64, std::time::Duration),
since: Option<std::time::Instant>,
+ cache_since: Option<std::time::Instant>,
/// For [`stuck`]: when each running read started.
running_since: HashMap<(u64, u64), stuck::Started>,
}
@@ -1004,6 +1029,10 @@ struct Lane {
/// sequence number.
error_event: usize,
errors: (u32, Option<(u64, Box<ErrorRecord>)>),
+ /// Last file source pointer and end offset dispatched for elevator locality.
+ last_source: usize,
+ last_end: u64,
+ elevator_skips: u32,
closed: bool,
/// Submits itself once half full (the queue's options did not disable
/// it).
@@ -1048,12 +1077,14 @@ fn scheduler() -> Option<&'static Scheduler> {
refused: 0,
bcpack: Default::default(),
since: None,
+ cache_since: None,
running_since: HashMap::new(),
}),
work: Condvar::new(),
finished: Condvar::new(),
});
let started = STARTED.get_or_init(|| {
+ let _ = stream_cache::StreamCache::global();
// As many workers as processors, those of the half that is not the frame's where the
// process was placed (`VICTORY_DSTORAGE_WORKERS=<n>`: that many), below
// normal priority (`VICTORY_DSTORAGE_PRIORITY=<-2..2>`, 0: normal, as before
@@ -1483,6 +1514,9 @@ impl Lanes {
"dstorage: native bridge counters");
}
}
+ let sc = stream_cache::StreamCache::global();
+ let (ram_hits, disk_hits, cache_misses, cache_written_mb) = sc.stats();
+ let (slab_hits, slab_coalesced, slab_misses, slab_read_mb) = sc.slab_stats();
tracing::debug!(
requests = *requests,
mb_per_s = format_args!("{:.1}", *bytes as f64 / elapsed.as_secs_f64() / 1e6),
@@ -1499,10 +1533,37 @@ impl Lanes {
guest_win32_reads_total = GUEST_WIN32_READS.load(Ordering::Relaxed),
bcpack_mb = self.bcpack.0 / 1_000_000,
bcpack_workers = format_args!("{:.2}", self.bcpack.1.as_secs_f64() / elapsed.as_secs_f64()),
+ ram_hits,
+ disk_hits,
+ cache_misses,
+ cache_written_mb,
waiting,
"dstorage: last {:.1} s",
elapsed.as_secs_f64()
);
+ let cache_since = *self.cache_since.get_or_insert(started);
+ if cache_since.elapsed().as_secs() >= 30 {
+ let total = ram_hits + disk_hits + cache_misses;
+ let hit_pct = if total > 0 {
+ (ram_hits + disk_hits) as f64 * 100.0 / total as f64
+ } else {
+ 0.0
+ };
+ tracing::info!(
+ hdd_mode = sc.hdd_active(),
+ ram_hits,
+ disk_hits,
+ cache_misses,
+ hit_pct = format_args!("{hit_pct:.1}%"),
+ cache_written_mb,
+ slab_hits,
+ slab_coalesced,
+ slab_misses,
+ slab_read_mb,
+ "dstorage: stream cache summary"
+ );
+ self.cache_since = Some(std::time::Instant::now());
+ }
self.done = Default::default();
self.bcpack = Default::default();
self.since = None;
@@ -1529,14 +1590,53 @@ impl Lanes {
}
let lane = self.lanes.get_mut(&id)?;
let class = lane.class;
- let (_, read) = lane.reads.front()?;
- let staging = staging_bytes(&read.request);
+ let next_status = lane.statuses.front().map(|s| s.0);
+ let (el_window, el_skips) = stream_cache::StreamCache::global().elevator_params();
+ let mut idx = if elevator_on() {
+ stream_cache::pick_elevator_index(
+ &lane.reads,
+ next_status,
+ lane.last_source,
+ lane.last_end,
+ el_window,
+ el_skips,
+ &mut lane.elevator_skips,
+ |&(seq, ref read)| {
+ let src = if read.request.options & MEMORY_SOURCE != 0 {
+ 0
+ } else {
+ read.request.source as usize
+ };
+ (seq, src, read.request.offset)
+ },
+ )
+ } else {
+ 0
+ };
+ let &(_, Read { request, .. }) = lane.reads.get(idx)?;
+ let mut staging = staging_bytes(&request);
if self.staged > 0 && self.staged + staging > self.staging {
- self.starved = true;
- self.refused += 1;
- return None;
+ if idx != 0 {
+ idx = 0;
+ let &(_, Read { request: req0, .. }) = lane.reads.front()?;
+ let st0 = staging_bytes(&req0);
+ if self.staged + st0 > self.staging {
+ self.starved = true;
+ self.refused += 1;
+ return None;
+ }
+ staging = st0;
+ } else {
+ self.starved = true;
+ self.refused += 1;
+ return None;
+ }
+ }
+ let (seq, Read { request, note, file }) = lane.reads.remove(idx)?;
+ if request.options & MEMORY_SOURCE == 0 && !request.source.is_null() {
+ lane.last_source = request.source as usize;
+ lane.last_end = request.offset.saturating_add(u64::from(request.source_size));
}
- let (seq, Read { request, note, file }) = lane.reads.pop_front()?;
lane.running.insert(seq);
if stuck::on() {
self.running_since.insert((id, seq), stuck::Started::new(&request));
@@ -1654,6 +1754,9 @@ impl Lane {
failures: BTreeMap::new(),
error_event: 0,
errors: (0, None),
+ last_source: 0,
+ last_end: 0,
+ elevator_skips: 0,
closed: false,
auto_submit: false,
}
@@ -2416,23 +2519,43 @@ fn execute(request: &Request, landed: impl FnOnce()) -> Result<(), HRESULT> {
.map_err(|hr| fail(hr, "copying"));
}
let tables = if bc != 0 { Some(bcpack_tables()?) } else { None };
- let source = read_source(request).map_err(|hr| fail(hr, "reading the source"))?;
- landed();
- // The console's order: zlib first, then BCPack.
- let source = if bc != 0 && options & ZLIB != 0 {
- let mut packed = Scratch::zeroed(request.intermediate_size as usize);
- let n = inflate(&source, &mut packed).map_err(|hr| fail(hr, "zlib"))?;
- packed.truncate(n);
- Held::Scratch(packed)
- } else {
- source
+ let decode = |source: &[u8]| -> Result<(), HRESULT> {
+ // The console's order: zlib first, then BCPack.
+ let packed_storage;
+ let payload = if bc != 0 && options & ZLIB != 0 {
+ let mut packed = Scratch::zeroed(request.intermediate_size as usize);
+ let n = inflate(source, &mut packed).map_err(|hr| fail(hr, "zlib"))?;
+ packed.truncate(n);
+ packed_storage = packed;
+ &packed_storage[..]
+ } else {
+ source
+ };
+ into_destination(request, size, |out| match tables {
+ Some(tables) => bcpack::decode(bc, payload, out, tables)
+ .map(|()| out.len())
+ .map_err(|e| fail(INVALID_DATA, &e.to_string())),
+ None => inflate(payload, out).map_err(|hr| fail(hr, "zlib")),
+ })
};
- into_destination(request, size, |out| match tables {
- Some(tables) => bcpack::decode(bc, &source, out, tables)
- .map(|()| out.len())
- .map_err(|e| fail(INVALID_DATA, &e.to_string())),
- None => inflate(&source, out).map_err(|hr| fail(hr, "zlib")),
- })?;
+ let (source, from_cache) =
+ read_source_cached(request, true, true).map_err(|hr| fail(hr, "reading the source"))?;
+ landed();
+ if let Err(hr) = decode(&source) {
+ if from_cache {
+ tracing::warn!(
+ offset = request.offset,
+ source_size = request.source_size,
+ "dstorage: cached compressed block failed decode; retrying from archive"
+ );
+ drop(source);
+ let (fresh, _) = read_source_cached(request, false, false)
+ .map_err(|hr| fail(hr, "reading the source (cache fallback)"))?;
+ decode(&fresh)?;
+ } else {
+ return Err(hr);
+ }
+ }
tracing::trace!(
options = format_args!("{options:#x}"),
offset = request.offset,
@@ -2530,17 +2653,21 @@ fn load_bcpack_tables() -> Result<Tables, String> {
}
/// A compressed request's source: borrowed from memory, or read from the
-/// file.
-fn read_source(request: &Request) -> Result<Held, HRESULT> {
+/// file (optionally through the streaming cache).
+fn read_source_cached(
+ request: &Request,
+ use_cache: bool,
+ self_checked: bool,
+) -> Result<(Held, bool), HRESULT> {
let size = request.source_size as usize;
if request.options & MEMORY_SOURCE != 0 {
// SAFETY: the title's source holds `size` bytes until completion.
let bytes = unsafe { std::slice::from_raw_parts(request.source.cast(), size) };
- return Ok(Held::Borrowed(bytes));
+ return Ok((Held::Borrowed(bytes), false));
}
let mut bytes = Scratch::zeroed(size);
- read_into_owned(request, &mut bytes.bytes)?;
- Ok(Held::Scratch(bytes))
+ let from_cache = read_into_source(request, ReadBuffer::Owned(&mut bytes.bytes), use_cache, self_checked)?;
+ Ok((Held::Scratch(bytes), from_cache))
}
/// A request's source bytes: the title's own memory, or a buffer.
@@ -2757,12 +2884,42 @@ impl ReadBuffer<'_> {
}
}
fn read_into(request: &Request, out: &mut [u8]) -> Result<(), HRESULT> {
- read_into_buffer(request, ReadBuffer::Guest(out))
-}
-fn read_into_owned(request: &Request, out: &mut Vec<u8>) -> Result<(), HRESULT> {
- read_into_buffer(request, ReadBuffer::Owned(out))
+ read_into_source(request, ReadBuffer::Guest(out), true, false).map(|_| ())
+}
+
+/// Reads an aligned sequential slab (`<= 2 MiB`) from `files` in a single
+/// spindle-serialized burst for **Modo HD Turbo** (`HddSlabCache`). Loops on
+/// short OS reads until either `dst` is full or `Ok(0)` (EOF).
+fn read_full_slab(files: &Files, dst: &mut [u8], base_offset: u64) -> std::io::Result<usize> {
+ let mut done = 0usize;
+ let mut tries = 0u32;
+ while done < dst.len() {
+ match files.read_at(&mut dst[done..], base_offset + done as u64) {
+ Ok(0) => break,
+ Ok(n) => {
+ done += n;
+ tries = 0;
+ }
+ Err(err) if tries < READ_RETRIES => {
+ tries += 1;
+ std::thread::sleep(std::time::Duration::from_millis(1 << tries));
+ tracing::warn!(%err, base_offset, done, tries, "dstorage: retrying HDD slab read");
+ }
+ Err(err) => return Err(err),
+ }
+ }
+ Ok(done)
}
-fn read_into_buffer(request: &Request, mut out: ReadBuffer<'_>) -> Result<(), HRESULT> {
+
+/// Fills `out` from the request's file or memory, returning whether the bytes
+/// came from the streaming cache. `self_checked` is true for ZLIB/BCPack
+/// payloads whose decoder independently verifies stream integrity.
+fn read_into_source(
+ request: &Request,
+ mut out: ReadBuffer<'_>,
+ use_cache: bool,
+ self_checked: bool,
+) -> Result<bool, HRESULT> {
if request.source.is_null() {
return Err(E_INVALIDARG);
}
@@ -2770,21 +2927,64 @@ fn read_into_buffer(request: &Request, mut out: ReadBuffer<'_>) -> Result<(), HR
let bytes = out.slice();
// SAFETY: the title's source holds `bytes.len()` bytes until completion.
bytes.copy_from_slice(unsafe { std::slice::from_raw_parts(request.source.cast(), bytes.len()) });
- return Ok(());
+ return Ok(false);
}
// SAFETY: the queued request holds a reference to this file object.
- let files = &unsafe { &*request.source.cast::<Instance<File>>() }.state.files;
+ let file_state = &unsafe { &*request.source.cast::<Instance<File>>() }.state;
+ let cache = stream_cache::StreamCache::global();
+ let len = out.slice().len();
+ let cache_key = (file_state.file_id != 0 && len != 0).then_some(stream_cache::BlockKey {
+ file_id: file_state.file_id,
+ offset: request.offset,
+ size: len as u32,
+ });
+ if use_cache
+ && let Some(key) = cache_key
+ && cache.try_read(key, out.slice(), self_checked)
+ {
+ return Ok(true);
+ }
+ let files = &file_state.files;
let started = std::time::Instant::now();
+ // Modo HD Turbo: serve cold reads <= 4 MiB through aligned 2 MiB sequential
+ // slabs with singleflight deduplication so dozens of small `.rpf` reads share
+ // one physical HDD seek instead of thrashing the platter head.
+ if use_cache && cache.hdd_active() && file_state.file_id != 0 {
+ match cache.read_through_slab(file_state.file_id, request.offset, out.slice(), |slab_base, slab_buf| {
+ let _io = cache.acquire_io();
+ read_full_slab(files, slab_buf, slab_base)
+ }) {
+ Ok(true) => {
+ READING.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed);
+ if let Some(key) = cache_key {
+ cache.record_miss(key, out.slice());
+ }
+ return Ok(false);
+ }
+ Ok(false) => {} // Large sequential read (> 2 slabs): fall through to direct sequential read.
+ Err(err) if err.kind() == std::io::ErrorKind::UnexpectedEof => {
+ READING.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed);
+ return Err(END_OF_FILE);
+ }
+ Err(err) => {
+ tracing::warn!(%err, offset = request.offset, size = len, "dstorage: HDD slab read failed; falling back to direct read");
+ }
+ }
+ }
let (mut done, mut tries) = (0, 0);
- let len = out.slice().len();
let result = loop {
- if done == len { break Ok(()); }
- let read = match &mut out {
- ReadBuffer::Guest(bytes) => {
- GUEST_WIN32_READS.fetch_add(1, Ordering::Relaxed);
- files.read_at(&mut bytes[done..], request.offset + done as u64)
+ if done == len {
+ break Ok(false);
+ }
+ let read = {
+ let _io = cache.acquire_io();
+ match &mut out {
+ ReadBuffer::Guest(bytes) => {
+ GUEST_WIN32_READS.fetch_add(1, Ordering::Relaxed);
+ files.read_at(&mut bytes[done..], request.offset + done as u64)
+ }
+ ReadBuffer::Owned(bytes) => files.read_owned_at(bytes, done, request.offset + done as u64),
}
- ReadBuffer::Owned(bytes) => files.read_owned_at(bytes, done, request.offset + done as u64),
};
let error = match read {
Ok(0) => break Err(END_OF_FILE),
@@ -2799,6 +2999,11 @@ fn read_into_buffer(request: &Request, mut out: ReadBuffer<'_>) -> Result<(), HR
victory_gpu::kernel_will_write(out.slice().as_ptr() as usize + done, len - done);
};
READING.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed);
+ if result.is_ok()
+ && let Some(key) = cache_key
+ {
+ cache.record_miss(key, out.slice());
+ }
result
}
@@ -3999,6 +4204,7 @@ mod tests {
refused: 0,
bcpack: Default::default(),
since: None,
+ cache_since: None,
running_since: HashMap::new(),
}
}
@@ -4595,6 +4801,62 @@ mod tests {
.join()
.expect("the worker");
}
+
+ #[test]
+ fn repeated_file_reads_hit_stream_cache() {
+ let plain = pattern(16_384);
+ let (_dir, file) = file_with(&plain);
+ let (before_ram, _, _, _) = stream_cache::StreamCache::global().stats();
+ let mut first = vec![0u8; 4096];
+ let mut second = vec![0u8; 4096];
+ let r1 = request(0, first.as_mut_ptr().cast(), 4096, file, 2048, 4096);
+ let r2 = request(0, second.as_mut_ptr().cast(), 4096, file, 2048, 4096);
+ assert_eq!(execute(&r1, || ()), Ok(()));
+ assert_eq!(execute(&r2, || ()), Ok(()));
+ assert_eq!(first, plain[2048..6144]);
+ assert_eq!(second, plain[2048..6144]);
+ let (after_ram, _, _, _) = stream_cache::StreamCache::global().stats();
+ assert!(after_ram > before_ram, "second identical read must hit RAM stream cache");
+ }
+
+ #[test]
+ fn elevator_reorders_within_batch_before_status_barrier() {
+ let mut l = lanes(STAGING);
+ l.lanes.insert(0, Lane::new(0, 64));
+ let fake_file = 0x1000usize as *const c_void;
+ let push_file_read = |l: &mut Lanes, offset: u64| {
+ let r = request(0, std::ptr::null_mut(), 4096, fake_file, offset, 4096);
+ l.lanes
+ .get_mut(&0)
+ .unwrap()
+ .unsubmitted
+ .push(Command::Read(Read { request: r, note: Note::default(), file: HeldFile(None) }));
+ };
+ let array = status_array(1).cast::<Instance<StatusArray>>();
+ push_file_read(&mut l, 100_000); // dispatched first -> last_end = 104_096
+ push_file_read(&mut l, 900_000);
+ push_file_read(&mut l, 120_000); // nearest forward before status
+ add_ref_instance(array);
+ l.lanes
+ .get_mut(&0)
+ .unwrap()
+ .unsubmitted
+ .push(Command::Status(Status { array, index: 0, enqueued: 0 }));
+ push_file_read(&mut l, 105_000); // AFTER status -> must not jump ahead!
+ l.submit(0, false);
+
+ let j0 = l.start().unwrap();
+ let j1 = l.start().unwrap();
+ let j2 = l.start().unwrap();
+ let j3 = l.start().unwrap();
+ assert_eq!(j0.request.offset, 100_000);
+ assert_eq!(j1.request.offset, 120_000);
+ assert_eq!(j2.request.offset, 900_000);
+ assert_eq!(j3.request.offset, 105_000);
+ for j in [j0, j1, j2, j3] {
+ l.finish(j, Ok(()));
+ }
+ }
}
/// Sizes and offsets as the console lays them out.
diff --git a/crates/victory-hle/src/modules/dstorage/stream_cache.rs b/crates/victory-hle/src/modules/dstorage/stream_cache.rs
new file mode 100644
index 0000000..df12f7b
--- /dev/null
+++ b/crates/victory-hle/src/modules/dstorage/stream_cache.rs
@@ -0,0 +1,2017 @@
+//! Bounded two-tier streaming cache (hot RAM LRU + persistent Warzone-style
+//! segmented disk cache) and SATA-friendly cold-read concurrency limiter for
+//! DirectStorage archive reads.
+
+use std::collections::{HashMap, VecDeque};
+use std::fs::{File, OpenOptions};
+use std::os::windows::fs::{FileExt, OpenOptionsExt};
+use std::os::windows::io::AsRawHandle;
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
+use std::sync::{Arc, Condvar, Mutex, OnceLock, RwLock};
+use std::time::{Duration, Instant};
+
+/// Opens a segment reader with `FILE_FLAG_OVERLAPPED | FILE_FLAG_RANDOM_ACCESS`
+/// so concurrent DirectStorage workers reading the same 64 MiB NVMe cache
+/// segment execute in parallel instead of serializing on Windows's synchronous
+/// `FILE_OBJECT` kernel lock.
+fn open_overlapped_reader(path: &Path) -> std::io::Result<File> {
+ use windows_sys::Win32::Storage::FileSystem::{FILE_FLAG_OVERLAPPED, FILE_FLAG_RANDOM_ACCESS};
+ OpenOptions::new()
+ .read(true)
+ .custom_flags(FILE_FLAG_OVERLAPPED | FILE_FLAG_RANDOM_ACCESS)
+ .open(path)
+}
+
+fn read_all_overlapped(file: &File, out: &mut [u8], offset: u64) -> bool {
+ let mut done = 0usize;
+ while done < out.len() {
+ match super::read_overlapped(file, &mut out[done..], offset + done as u64) {
+ Ok(0) | Err(_) => return false,
+ Ok(n) => done += n,
+ }
+ }
+ true
+}
+
+const MAGIC_SEG: [u8; 4] = *b"VSCG";
+const MAGIC_REC: [u8; 4] = *b"VSCR";
+const MAGIC_IDX: [u8; 4] = *b"VSCI";
+const INDEX_VERSION: u32 = 1;
+const SEG_HEADER_LEN: u32 = 16;
+const REC_HEADER_LEN: usize = 32;
+const DEFAULT_SEGMENT_BYTES: u64 = 64 << 20;
+const MAX_RAM_BLOCK_BYTES: usize = 512 << 10;
+const RAM_SHARDS: usize = 8;
+const MAX_ASYNC_QUEUE_BYTES: usize = 32 << 20;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub(super) struct BlockKey {
+ pub(super) file_id: u64,
+ pub(super) offset: u64,
+ pub(super) size: u32,
+}
+
+#[inline]
+fn mix64(mut x: u64) -> u64 {
+ x ^= x >> 30;
+ x = x.wrapping_mul(0xbf58_476d_1ce4_e5b9);
+ x ^= x >> 27;
+ x = x.wrapping_mul(0x94d0_49bb_1331_11eb);
+ x ^ (x >> 31)
+}
+
+/// Stable 64-bit identity for an archive file based on its normalized path,
+/// byte length, and last-modified timestamp. Any change to the underlying file
+/// produces a new identity so stale cached bytes are never returned.
+pub(super) fn file_identity(path: &str, file_len: u64, mtime_ns: u128) -> u64 {
+ let mut h: u64 = 0xcbf2_9ce4_8422_2325;
+ for b in path.bytes() {
+ let norm = match b {
+ b'\\' => b'/',
+ b'A'..=b'Z' => b + 32,
+ other => other,
+ };
+ h ^= u64::from(norm);
+ h = h.wrapping_mul(0x0000_0100_0000_01b3);
+ }
+ h ^= mix64(file_len);
+ h = h.wrapping_mul(0x9e37_79b9_7f4a_7c15);
+ h ^= mix64(mtime_ns as u64);
+ h = h.wrapping_mul(0x9e37_79b9_7f4a_7c15);
+ h ^= mix64((mtime_ns >> 64) as u64);
+ let out = mix64(h);
+ if out == 0 { 1 } else { out }
+}
+
+/// Fast 64-bit integrity checksum over cached payload bytes.
+pub(super) fn payload_checksum(bytes: &[u8]) -> u64 {
+ let mut h = mix64(bytes.len() as u64 ^ 0x517c_c1b7_2722_0a95);
+ let mut chunks = bytes.chunks_exact(8);
+ for chunk in &mut chunks {
+ let word = u64::from_le_bytes([
+ chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7],
+ ]);
+ h = (h ^ word).wrapping_mul(0x9e37_79b9_7f4a_7c15).rotate_left(27);
+ }
+ let rem = chunks.remainder();
+ if !rem.is_empty() {
+ let mut tail = 0u64;
+ for (i, &b) in rem.iter().enumerate() {
+ tail |= u64::from(b) << (i * 8);
+ }
+ h = (h ^ tail).wrapping_mul(0x9e37_79b9_7f4a_7c15).rotate_left(27);
+ }
+ mix64(h)
+}
+
+struct RamEntry {
+ data: Arc<[u8]>,
+ epoch: u64,
+}
+
+struct RamState {
+ entries: HashMap<BlockKey, RamEntry>,
+ order: VecDeque<(BlockKey, u64)>,
+ used: usize,
+ tick: u64,
+}
+
+struct RamShard {
+ budget: usize,
+ state: Mutex<RamState>,
+}
+
+pub(super) struct RamCache {
+ budget: usize,
+ max_block: usize,
+ shards: Vec<RamShard>,
+}
+
+impl RamCache {
+ pub(super) fn new(budget_bytes: usize, max_block_bytes: usize) -> Self {
+ let shard_count = if budget_bytes >= max_block_bytes.saturating_mul(RAM_SHARDS).max(RAM_SHARDS) {
+ RAM_SHARDS
+ } else {
+ 1
+ };
+ let per_shard = budget_bytes / shard_count;
+ let rem = budget_bytes % shard_count;
+ let shards = (0..shard_count)
+ .map(|i| RamShard {
+ budget: per_shard + usize::from(i < rem),
+ state: Mutex::new(RamState {
+ entries: HashMap::new(),
+ order: VecDeque::new(),
+ used: 0,
+ tick: 0,
+ }),
+ })
+ .collect();
+ Self { budget: budget_bytes, max_block: max_block_bytes, shards }
+ }
+
+ #[inline]
+ fn shard(&self, key: BlockKey) -> &RamShard {
+ if self.shards.len() == 1 {
+ return &self.shards[0];
+ }
+ let h = mix64(key.file_id ^ key.offset.rotate_left(17) ^ u64::from(key.size));
+ &self.shards[(h as usize) % self.shards.len()]
+ }
+
+ pub(super) fn get_into(&self, key: BlockKey, out: &mut [u8]) -> bool {
+ if self.budget == 0 || out.len() > self.max_block {
+ return false;
+ }
+ let shard = self.shard(key);
+ let data = {
+ let mut s = shard.state.lock().unwrap_or_else(|e| e.into_inner());
+ let next_tick = s.tick.wrapping_add(1);
+ let Some(entry) = s.entries.get_mut(&key) else {
+ return false;
+ };
+ if entry.data.len() != out.len() {
+ return false;
+ }
+ let data = Arc::clone(&entry.data);
+ entry.epoch = next_tick;
+ s.tick = next_tick;
+ s.order.push_back((key, next_tick));
+ if s.order.len() > s.entries.len().saturating_mul(4).saturating_add(64) {
+ Self::compact_order(&mut s);
+ }
+ data
+ };
+ // Copy bytes outside the shard lock so concurrent readers never stall on memcpy.
+ out.copy_from_slice(&data);
+ true
+ }
+
+ pub(super) fn put(&self, key: BlockKey, data: &[u8]) {
+ if self.budget == 0 || data.is_empty() || data.len() > self.max_block {
+ return;
+ }
+ let shard = self.shard(key);
+ if data.len() > shard.budget {
+ return;
+ }
+ // Allocate outside the shard lock to minimize critical section time.
+ let boxed: Arc<[u8]> = Arc::from(data);
+ let mut s = shard.state.lock().unwrap_or_else(|e| e.into_inner());
+ if s.entries.contains_key(&key) {
+ return;
+ }
+ let target = shard.budget.saturating_sub(boxed.len());
+ Self::evict_to(&mut s, target);
+ let tick = s.tick.wrapping_add(1);
+ s.tick = tick;
+ s.used += boxed.len();
+ s.entries.insert(key, RamEntry { data: boxed, epoch: tick });
+ s.order.push_back((key, tick));
+ }
+
+ pub(super) fn trim_to(&self, limit_bytes: usize) {
+ let per_shard = limit_bytes / self.shards.len();
+ for shard in &self.shards {
+ let mut s = shard.state.lock().unwrap_or_else(|e| e.into_inner());
+ Self::evict_to(&mut s, per_shard);
+ if per_shard == 0 {
+ s.entries.shrink_to_fit();
+ s.order.shrink_to_fit();
+ }
+ }
+ }
+
+ #[cfg(test)]
+ pub(super) fn len_bytes(&self) -> usize {
+ self.shards
+ .iter()
+ .map(|sh| sh.state.lock().unwrap_or_else(|e| e.into_inner()).used)
+ .sum()
+ }
+
+ fn evict_to(s: &mut RamState, limit_bytes: usize) {
+ while s.used > limit_bytes {
+ let Some((key, epoch)) = s.order.pop_front() else {
+ s.entries.clear();
+ s.used = 0;
+ break;
+ };
+ let is_live = s.entries.get(&key).is_some_and(|e| e.epoch == epoch);
+ if is_live && let Some(removed) = s.entries.remove(&key) {
+ s.used = s.used.saturating_sub(removed.data.len());
+ }
+ }
+ }
+
+ fn compact_order(s: &mut RamState) {
+ let entries = &s.entries;
+ s.order.retain(|(k, g)| entries.get(k).is_some_and(|e| e.epoch == *g));
+ }
+}
+
+#[derive(Clone, Copy, Debug)]
+struct DiskLoc {
+ seg: u16,
+ pos: u32,
+ size: u32,
+ checksum: u64,
+ epoch: u64,
+}
+
+struct WriterState {
+ active_seg: u16,
+ active_pos: u32,
+ active_file: Option<File>,
+ dirty: bool,
+}
+
+/// Warzone-style persistent ring-segmented fast-disk streaming cache.
+pub(super) struct DiskCache {
+ dir: PathBuf,
+ segment_bytes: u64,
+ max_segments: usize,
+ seg_gens: Box<[AtomicU64]>,
+ readers: RwLock<Vec<Option<Arc<File>>>>,
+ index: RwLock<HashMap<BlockKey, DiskLoc>>,
+ writer: Mutex<WriterState>,
+}
+
+impl DiskCache {
+ pub(super) fn open(dir: &Path, budget_bytes: u64, segment_bytes: u64) -> std::io::Result<Self> {
+ std::fs::create_dir_all(dir)?;
+ let segment_bytes = segment_bytes.max(1024);
+ let max_segments = ((budget_bytes / segment_bytes) as usize).clamp(2, 1024);
+ let seg_gens: Box<[AtomicU64]> = (0..max_segments).map(|_| AtomicU64::new(0)).collect();
+ let mut readers: Vec<Option<Arc<File>>> = vec![None; max_segments];
+ let mut index = HashMap::new();
+ let mut active_seg: u16 = 0;
+ let mut active_pos: u32 = SEG_HEADER_LEN;
+
+ if let Some(loaded) = Self::try_load_index(dir, max_segments, segment_bytes) {
+ let mut valid_segs = vec![false; max_segments];
+ let mut seg_lens = vec![0u64; max_segments];
+ for (seg, &epoch) in loaded.seg_gens.iter().enumerate() {
+ if epoch == 0 {
+ continue;
+ }
+ let path = Self::seg_path(dir, seg as u16);
+ if let Ok(file) = open_overlapped_reader(&path)
+ && let Ok(meta) = file.metadata()
+ && Self::read_seg_header(&file) == Some(epoch)
+ {
+ seg_gens[seg].store(epoch, Ordering::Relaxed);
+ seg_lens[seg] = meta.len();
+ readers[seg] = Some(Arc::new(file));
+ valid_segs[seg] = true;
+ }
+ }
+ for (key, loc) in loaded.entries {
+ let seg = usize::from(loc.seg);
+ if seg < max_segments && valid_segs[seg] {
+ let expected_epoch = seg_gens[seg].load(Ordering::Relaxed);
+ let end = u64::from(loc.pos) + REC_HEADER_LEN as u64 + u64::from(loc.size);
+ if loc.epoch == expected_epoch && end <= seg_lens[seg] {
+ index.insert(key, loc);
+ }
+ }
+ }
+ let a_idx = usize::from(loaded.active_seg);
+ if a_idx < max_segments
+ && valid_segs[a_idx]
+ && u64::from(loaded.active_pos) <= seg_lens[a_idx]
+ {
+ active_seg = loaded.active_seg;
+ active_pos = loaded.active_pos.max(SEG_HEADER_LEN);
+ }
+ }
+
+ let cache = Self {
+ dir: dir.to_path_buf(),
+ segment_bytes,
+ max_segments,
+ seg_gens,
+ readers: RwLock::new(readers),
+ index: RwLock::new(index),
+ writer: Mutex::new(WriterState {
+ active_seg,
+ active_pos,
+ active_file: None,
+ dirty: false,
+ }),
+ };
+ Ok(cache)
+ }
+
+ fn seg_path(dir: &Path, seg: u16) -> PathBuf {
+ dir.join(format!("seg-{seg:03}.bin"))
+ }
+
+ fn read_seg_header(file: &File) -> Option<u64> {
+ let mut hdr = [0u8; SEG_HEADER_LEN as usize];
+ if !read_all_overlapped(file, &mut hdr, 0) {
+ return None;
+ }
+ if hdr[0..4] != MAGIC_SEG {
+ return None;
+ }
+ Some(u64::from_le_bytes(hdr[4..12].try_into().ok()?))
+ }
+
+ fn write_seg_header(file: &File, epoch: u64) -> std::io::Result<()> {
+ let mut hdr = [0u8; SEG_HEADER_LEN as usize];
+ hdr[0..4].copy_from_slice(&MAGIC_SEG);
+ hdr[4..12].copy_from_slice(&epoch.to_le_bytes());
+ write_all_at(file, &hdr, 0)
+ }
+
+ #[cfg(test)]
+ pub(super) fn get_into(&self, key: BlockKey, out: &mut [u8]) -> bool {
+ self.get_into_checked(key, out, true)
+ }
+
+ pub(super) fn get_into_checked(&self, key: BlockKey, out: &mut [u8], verify: bool) -> bool {
+ let loc = {
+ let idx = self.index.read().unwrap_or_else(|e| e.into_inner());
+ let Some(&loc) = idx.get(&key) else {
+ return false;
+ };
+ loc
+ };
+ if loc.size as usize != out.len() {
+ return false;
+ }
+ let seg_idx = usize::from(loc.seg);
+ if self.seg_gens[seg_idx].load(Ordering::Acquire) != loc.epoch {
+ return false;
+ }
+ let reader = {
+ let readers = self.readers.read().unwrap_or_else(|e| e.into_inner());
+ readers.get(seg_idx).and_then(|r| r.as_ref().cloned())
+ };
+ let Some(file) = reader else {
+ return false;
+ };
+ let data_off = u64::from(loc.pos) + REC_HEADER_LEN as u64;
+ if !read_all_overlapped(&file, out, data_off) {
+ return false;
+ }
+ if self.seg_gens[seg_idx].load(Ordering::Acquire) != loc.epoch {
+ return false;
+ }
+ !verify || payload_checksum(out) == loc.checksum
+ }
+
+ pub(super) fn contains(&self, key: BlockKey) -> bool {
+ self.index.read().unwrap_or_else(|e| e.into_inner()).contains_key(&key)
+ }
+
+ pub(super) fn put_sync(&self, key: BlockKey, data: &[u8]) {
+ if data.is_empty() {
+ return;
+ }
+ let rec_len = (REC_HEADER_LEN + data.len()).next_multiple_of(8);
+ if rec_len as u64 + u64::from(SEG_HEADER_LEN) > self.segment_bytes {
+ return;
+ }
+ if self.contains(key) {
+ return;
+ }
+ let checksum = payload_checksum(data);
+ let mut w = self.writer.lock().unwrap_or_else(|e| e.into_inner());
+ if self.contains(key) {
+ return;
+ }
+ let need_roll = w.active_file.is_none()
+ || u64::from(w.active_pos) + rec_len as u64 > self.segment_bytes;
+ if need_roll {
+ let next_seg = if w.active_file.is_none()
+ && self.seg_gens[usize::from(w.active_seg)].load(Ordering::Relaxed) != 0
+ && u64::from(w.active_pos) + rec_len as u64 <= self.segment_bytes
+ {
+ // Reopen existing active segment without wiping it.
+ let seg = w.active_seg;
+ let path = Self::seg_path(&self.dir, seg);
+ match OpenOptions::new().read(true).write(true).open(&path) {
+ Ok(f) => {
+ w.active_file = Some(f);
+ None
+ }
+ Err(_) => Some(seg),
+ }
+ } else if w.active_file.is_none() {
+ Some(w.active_seg)
+ } else {
+ Some(((usize::from(w.active_seg) + 1) % self.max_segments) as u16)
+ };
+
+ if let Some(seg) = next_seg {
+ let seg_idx = usize::from(seg);
+ let new_gen = self.seg_gens[seg_idx].fetch_add(1, Ordering::AcqRel) + 1;
+ {
+ let mut idx = self.index.write().unwrap_or_else(|e| e.into_inner());
+ idx.retain(|_, loc| loc.seg != seg);
+ }
+ let path = Self::seg_path(&self.dir, seg);
+ let Ok(file) = OpenOptions::new().read(true).write(true).create(true).truncate(true).open(&path) else {
+ return;
+ };
+ if Self::write_seg_header(&file, new_gen).is_err() {
+ return;
+ }
+ if let Ok(reader) = open_overlapped_reader(&path) {
+ let mut readers = self.readers.write().unwrap_or_else(|e| e.into_inner());
+ readers[seg_idx] = Some(Arc::new(reader));
+ }
+ w.active_seg = seg;
+ w.active_pos = SEG_HEADER_LEN;
+ w.active_file = Some(file);
+ w.dirty = true;
+ }
+ }
+
+ let seg = w.active_seg;
+ let pos = w.active_pos;
+ let epoch = self.seg_gens[usize::from(seg)].load(Ordering::Acquire);
+ let Some(file) = w.active_file.as_ref() else {
+ return;
+ };
+
+ let mut hdr = [0u8; REC_HEADER_LEN];
+ hdr[0..4].copy_from_slice(&MAGIC_REC);
+ hdr[4..8].copy_from_slice(&(data.len() as u32).to_le_bytes());
+ hdr[8..16].copy_from_slice(&key.file_id.to_le_bytes());
+ hdr[16..24].copy_from_slice(&key.offset.to_le_bytes());
+ hdr[24..32].copy_from_slice(&checksum.to_le_bytes());
+
+ if write_all_at(file, &hdr, u64::from(pos)).is_err()
+ || write_all_at(file, data, u64::from(pos) + REC_HEADER_LEN as u64).is_err()
+ {
+ return;
+ }
+ let pad = rec_len - (REC_HEADER_LEN + data.len());
+ if pad > 0 {
+ let zeros = [0u8; 8];
+ let _ = write_all_at(file, &zeros[..pad], u64::from(pos) + (REC_HEADER_LEN + data.len()) as u64);
+ }
+ w.active_pos = pos.saturating_add(rec_len as u32);
+ w.dirty = true;
+ drop(w);
+
+ let mut idx = self.index.write().unwrap_or_else(|e| e.into_inner());
+ idx.insert(
+ key,
+ DiskLoc { seg, pos, size: data.len() as u32, checksum, epoch },
+ );
+ }
+
+ pub(super) fn flush_index(&self) -> std::io::Result<()> {
+ let (active_seg, active_pos, dirty) = {
+ let mut w = self.writer.lock().unwrap_or_else(|e| e.into_inner());
+ let d = w.dirty;
+ w.dirty = false;
+ (w.active_seg, w.active_pos, d)
+ };
+ if !dirty {
+ return Ok(());
+ }
+ let entries: Vec<(BlockKey, DiskLoc)> = {
+ let idx = self.index.read().unwrap_or_else(|e| e.into_inner());
+ idx.iter().map(|(&k, &v)| (k, v)).collect()
+ };
+ let mut buf = Vec::with_capacity(24 + self.max_segments * 8 + entries.len() * 36);
+ buf.extend_from_slice(&MAGIC_IDX);
+ buf.extend_from_slice(&INDEX_VERSION.to_le_bytes());
+ buf.extend_from_slice(&u32::from(active_seg).to_le_bytes());
+ buf.extend_from_slice(&active_pos.to_le_bytes());
+ buf.extend_from_slice(&(self.max_segments as u32).to_le_bytes());
+ buf.extend_from_slice(&(entries.len() as u32).to_le_bytes());
+ for g in self.seg_gens.iter() {
+ buf.extend_from_slice(&g.load(Ordering::Acquire).to_le_bytes());
+ }
+ for (k, loc) in &entries {
+ buf.extend_from_slice(&k.file_id.to_le_bytes());
+ buf.extend_from_slice(&k.offset.to_le_bytes());
+ buf.extend_from_slice(&loc.size.to_le_bytes());
+ buf.extend_from_slice(&loc.seg.to_le_bytes());
+ buf.extend_from_slice(&0u16.to_le_bytes());
+ buf.extend_from_slice(&loc.pos.to_le_bytes());
+ buf.extend_from_slice(&loc.checksum.to_le_bytes());
+ }
+ let tmp = self.dir.join("index.tmp");
+ let dst = self.dir.join("index.bin");
+ std::fs::write(&tmp, &buf)?;
+ if std::fs::rename(&tmp, &dst).is_err() {
+ let _ = std::fs::remove_file(&dst);
+ std::fs::rename(&tmp, &dst)?;
+ }
+ Ok(())
+ }
+
+ pub(super) fn entry_count(&self) -> usize {
+ self.index.read().unwrap_or_else(|e| e.into_inner()).len()
+ }
+
+ fn try_load_index(dir: &Path, max_segments: usize, segment_bytes: u64) -> Option<LoadedIndex> {
+ let bytes = std::fs::read(dir.join("index.bin")).ok()?;
+ if bytes.len() < 24 || bytes[0..4] != MAGIC_IDX {
+ return None;
+ }
+ let version = u32::from_le_bytes(bytes[4..8].try_into().ok()?);
+ if version != INDEX_VERSION {
+ return None;
+ }
+ let active_seg = u32::from_le_bytes(bytes[8..12].try_into().ok()?) as u16;
+ let active_pos = u32::from_le_bytes(bytes[12..16].try_into().ok()?);
+ let stored_segs = u32::from_le_bytes(bytes[16..20].try_into().ok()?) as usize;
+ let count = u32::from_le_bytes(bytes[20..24].try_into().ok()?) as usize;
+ if stored_segs != max_segments {
+ return None;
+ }
+ let gens_end = 24 + stored_segs * 8;
+ let expected_len = gens_end.checked_add(count.checked_mul(36)?)?;
+ if bytes.len() < expected_len {
+ return None;
+ }
+ let mut seg_gens = Vec::with_capacity(stored_segs);
+ for i in 0..stored_segs {
+ let off = 24 + i * 8;
+ seg_gens.push(u64::from_le_bytes(bytes[off..off + 8].try_into().ok()?));
+ }
+ let mut entries = Vec::with_capacity(count);
+ for i in 0..count {
+ let off = gens_end + i * 36;
+ let file_id = u64::from_le_bytes(bytes[off..off + 8].try_into().ok()?);
+ let offset = u64::from_le_bytes(bytes[off + 8..off + 16].try_into().ok()?);
+ let size = u32::from_le_bytes(bytes[off + 16..off + 20].try_into().ok()?);
+ let seg = u16::from_le_bytes(bytes[off + 20..off + 22].try_into().ok()?);
+ let pos = u32::from_le_bytes(bytes[off + 24..off + 28].try_into().ok()?);
+ let checksum = u64::from_le_bytes(bytes[off + 28..off + 36].try_into().ok()?);
+ if usize::from(seg) >= max_segments
+ || u64::from(pos) + REC_HEADER_LEN as u64 + u64::from(size) > segment_bytes
+ {
+ continue;
+ }
+ let epoch = seg_gens[usize::from(seg)];
+ entries.push((
+ BlockKey { file_id, offset, size },
+ DiskLoc { seg, pos, size, checksum, epoch },
+ ));
+ }
+ Some(LoadedIndex { active_seg, active_pos, seg_gens, entries })
+ }
+}
+
+struct LoadedIndex {
+ active_seg: u16,
+ active_pos: u32,
+ seg_gens: Vec<u64>,
+ entries: Vec<(BlockKey, DiskLoc)>,
+}
+
+fn write_all_at(file: &File, mut buf: &[u8], mut offset: u64) -> std::io::Result<()> {
+ while !buf.is_empty() {
+ let n = file.seek_write(buf, offset)?;
+ if n == 0 {
+ return Err(std::io::Error::new(std::io::ErrorKind::WriteZero, "short cache write"));
+ }
+ buf = &buf[n..];
+ offset += n as u64;
+ }
+ Ok(())
+}
+
+struct AsyncDiskCache {
+ disk: Arc<DiskCache>,
+ queue: Mutex<(VecDeque<(BlockKey, Vec<u8>)>, usize)>,
+ wake: Condvar,
+ written_bytes: AtomicU64,
+}
+
+impl AsyncDiskCache {
+ fn open(dir: &Path, budget_bytes: u64) -> std::io::Result<Arc<Self>> {
+ let disk = Arc::new(DiskCache::open(dir, budget_bytes, DEFAULT_SEGMENT_BYTES)?);
+ let loaded = disk.entry_count();
+ tracing::info!(
+ dir = %dir.display(),
+ budget_mb = budget_bytes >> 20,
+ loaded_blocks = loaded,
+ "dstorage: persistent streaming cache ready (VICTORY_DSTORAGE_CACHE_DIR)"
+ );
+ let shared = Arc::new(Self {
+ disk,
+ queue: Mutex::new((VecDeque::new(), 0)),
+ wake: Condvar::new(),
+ written_bytes: AtomicU64::new(0),
+ });
+ let bg = shared.clone();
+ let _ = std::thread::Builder::new()
+ .name("dstorage-cache-writer".into())
+ .spawn(move || bg.writer_loop());
+ Ok(shared)
+ }
+
+ fn get_into_checked(&self, key: BlockKey, out: &mut [u8], verify: bool) -> bool {
+ self.disk.get_into_checked(key, out, verify)
+ }
+
+ fn enqueue(&self, key: BlockKey, data: &[u8]) {
+ if data.is_empty() || data.len() > (4 << 20) || self.disk.contains(key) {
+ return;
+ }
+ let mut q = self.queue.lock().unwrap_or_else(|e| e.into_inner());
+ if q.1 + data.len() > MAX_ASYNC_QUEUE_BYTES {
+ return;
+ }
+ q.1 += data.len();
+ q.0.push_back((key, data.to_vec()));
+ self.wake.notify_one();
+ }
+
+ fn writer_loop(self: Arc<Self>) {
+ // SAFETY: lowering our own background cache writer thread priority.
+ unsafe {
+ use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_BELOW_NORMAL};
+ SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
+ }
+ let mut last_flush = Instant::now();
+ let mut pending_flush = false;
+ loop {
+ let item = {
+ let mut q = self.queue.lock().unwrap_or_else(|e| e.into_inner());
+ while q.0.is_empty() {
+ if !pending_flush {
+ q = self.wake.wait(q).unwrap_or_else(|e| e.into_inner());
+ continue;
+ }
+ let wait = Duration::from_secs(2).saturating_sub(last_flush.elapsed());
+ if wait.is_zero() {
+ drop(q);
+ let _ = self.disk.flush_index();
+ last_flush = Instant::now();
+ pending_flush = false;
+ q = self.queue.lock().unwrap_or_else(|e| e.into_inner());
+ continue;
+ }
+ let (guard, timed_out) = self
+ .wake
+ .wait_timeout(q, wait)
+ .unwrap_or_else(|e| e.into_inner());
+ q = guard;
+ if timed_out.timed_out() && q.0.is_empty() {
+ drop(q);
+ let _ = self.disk.flush_index();
+ last_flush = Instant::now();
+ pending_flush = false;
+ q = self.queue.lock().unwrap_or_else(|e| e.into_inner());
+ }
+ }
+ let popped = q.0.pop_front();
+ if let Some((_, ref bytes)) = popped {
+ q.1 = q.1.saturating_sub(bytes.len());
+ }
+ popped
+ };
+ if let Some((key, data)) = item {
+ let len = data.len() as u64;
+ self.disk.put_sync(key, &data);
+ self.written_bytes.fetch_add(len, Ordering::Relaxed);
+ pending_flush = true;
+ }
+ if pending_flush && last_flush.elapsed() >= Duration::from_secs(5) {
+ let _ = self.disk.flush_index();
+ last_flush = Instant::now();
+ pending_flush = false;
+ }
+ }
+ }
+}
+
+pub(super) struct IoLimiter {
+ state: Mutex<usize>,
+ ready: Condvar,
+ limit: AtomicUsize,
+}
+
+pub(super) struct IoPermit<'a>(&'a IoLimiter);
+
+impl IoLimiter {
+ pub(super) fn new(limit: usize) -> Self {
+ Self {
+ state: Mutex::new(0),
+ ready: Condvar::new(),
+ limit: AtomicUsize::new(limit.max(1)),
+ }
+ }
+
+ pub(super) fn set_limit(&self, new_limit: usize) {
+ let clamped = new_limit.max(1);
+ let prev = self.limit.swap(clamped, Ordering::AcqRel);
+ if clamped > prev {
+ let _guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
+ self.ready.notify_all();
+ }
+ }
+
+ pub(super) fn limit(&self) -> usize {
+ self.limit.load(Ordering::Acquire)
+ }
+
+ pub(super) fn acquire(&self) -> IoPermit<'_> {
+ let mut active = self.state.lock().unwrap_or_else(|e| e.into_inner());
+ while *active >= self.limit.load(Ordering::Acquire) {
+ active = self.ready.wait(active).unwrap_or_else(|e| e.into_inner());
+ }
+ *active += 1;
+ IoPermit(self)
+ }
+}
+
+impl Drop for IoPermit<'_> {
+ fn drop(&mut self) {
+ let mut active = self.0.state.lock().unwrap_or_else(|e| e.into_inner());
+ *active = active.saturating_sub(1);
+ self.0.ready.notify_one();
+ }
+}
+
+// --- Mechanical HDD auto-detection (zero-admin Win32 seek-penalty query) ---
+
+/// Extracts an ASCII uppercase drive letter (`b'A'..=b'Z'`) from a Windows path
+/// (supporting `X:\...`, `X:/...`, `\\?\X:\...`, `\\.\X:\...`). Returns `None`
+/// for UNC paths, device paths without a drive letter, or relative paths.
+pub(super) fn extract_drive_letter(path: &str) -> Option<u8> {
+ let trimmed = path
+ .strip_prefix(r"\\?\")
+ .or_else(|| path.strip_prefix(r"\\.\"))
+ .unwrap_or(path);
+ let bytes = trimmed.as_bytes();
+ if bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' {
+ Some(bytes[0].to_ascii_uppercase())
+ } else {
+ None
+ }
+}
+
+/// Queries Windows's `StorageDeviceSeekPenaltyProperty` (`IOCTL_STORAGE_QUERY_PROPERTY`)
+/// for volume `\\.\X:` with `dwDesiredAccess = 0` (requires NO administrator
+/// privileges). Returns `Some(true)` for a mechanical HDD (seek penalty),
+/// `Some(false)` for an SSD/NVMe, or `None` if unavailable/virtual.
+pub(super) fn drive_has_seek_penalty(drive_letter: u8) -> Option<bool> {
+ if !drive_letter.is_ascii_alphabetic() {
+ return None;
+ }
+ let idx = (drive_letter.to_ascii_uppercase() - b'A') as usize;
+ static CACHE: [OnceLock<Option<bool>>; 26] = [const { OnceLock::new() }; 26];
+ *CACHE[idx].get_or_init(|| query_seek_penalty_uncached(drive_letter.to_ascii_uppercase()))
+}
+
+fn query_seek_penalty_uncached(letter: u8) -> Option<bool> {
+ use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
+ use windows_sys::Win32::Storage::FileSystem::{
+ CreateFileW, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING,
+ };
+ use windows_sys::Win32::System::IO::DeviceIoControl;
+
+ const IOCTL_STORAGE_QUERY_PROPERTY: u32 = 0x002D_1400;
+ const STORAGE_DEVICE_SEEK_PENALTY_PROPERTY: u32 = 7;
+ const PROPERTY_STANDARD_QUERY: u32 = 0;
+
+ #[repr(C)]
+ struct StoragePropertyQuery {
+ property_id: u32,
+ query_type: u32,
+ additional_parameters: [u8; 4],
+ }
+
+ #[repr(C)]
+ struct DeviceSeekPenaltyDescriptor {
+ version: u32,
+ size: u32,
+ incurs_seek_penalty: u8,
+ _pad: [u8; 3],
+ }
+
+ let vol: Vec<u16> = format!(r"\\.\{}:", letter as char)
+ .encode_utf16()
+ .chain(std::iter::once(0))
+ .collect();
+ // SAFETY: zero access asks only for device metadata; no elevation required.
+ let handle = unsafe {
+ CreateFileW(
+ vol.as_ptr(),
+ 0,
+ FILE_SHARE_READ | FILE_SHARE_WRITE,
+ std::ptr::null(),
+ OPEN_EXISTING,
+ 0,
+ std::ptr::null_mut(),
+ )
+ };
+ if handle == INVALID_HANDLE_VALUE || handle.is_null() {
+ return None;
+ }
+ let query = StoragePropertyQuery {
+ property_id: STORAGE_DEVICE_SEEK_PENALTY_PROPERTY,
+ query_type: PROPERTY_STANDARD_QUERY,
+ additional_parameters: [0; 4],
+ };
+ let mut desc = DeviceSeekPenaltyDescriptor {
+ version: 0,
+ size: 0,
+ incurs_seek_penalty: 0,
+ _pad: [0; 3],
+ };
+ let mut returned: u32 = 0;
+ // SAFETY: both structs are plain repr(C) POD with matching sizes.
+ let ok = unsafe {
+ DeviceIoControl(
+ handle,
+ IOCTL_STORAGE_QUERY_PROPERTY,
+ (&raw const query).cast(),
+ std::mem::size_of::<StoragePropertyQuery>() as u32,
+ (&raw mut desc).cast(),
+ std::mem::size_of::<DeviceSeekPenaltyDescriptor>() as u32,
+ &mut returned,
+ std::ptr::null_mut(),
+ )
+ };
+ // SAFETY: valid handle returned by `CreateFileW` above.
+ unsafe { CloseHandle(handle) };
+ if ok != 0 && returned >= 9 {
+ Some(desc.incurs_seek_penalty != 0)
+ } else {
+ None
+ }
+}
+
+/// Resolves a filesystem path (including relative paths) to its underlying
+/// physical drive letter and reports whether it incurs mechanical seek penalty.
+pub(super) fn is_rotational_drive(path: &Path) -> Option<bool> {
+ let raw = path.to_string_lossy();
+ let letter = extract_drive_letter(&raw).or_else(|| {
+ std::fs::canonicalize(path)
+ .ok()
+ .and_then(|canon| extract_drive_letter(&canon.to_string_lossy()))
+ })?;
+ drive_has_seek_penalty(letter)
+}
+
+/// Resolves an open host `File` handle via `GetFinalPathNameByHandleW` (which
+/// sees through Xbox virtual drives like `G:\` and NTFS symlinks/junctions)
+/// and reports whether the backing drive is a mechanical HDD.
+pub(super) fn is_rotational_file(file: &File) -> Option<bool> {
+ use windows_sys::Win32::Storage::FileSystem::GetFinalPathNameByHandleW;
+
+ let mut buf = [0u16; 512];
+ // SAFETY: `file` is a live Win32 file handle and `buf` has capacity 512 UTF-16 units.
+ let len = unsafe {
+ GetFinalPathNameByHandleW(file.as_raw_handle(), buf.as_mut_ptr(), buf.len() as u32, 0)
+ } as usize;
+ if len == 0 || len >= buf.len() {
+ return None;
+ }
+ let resolved = String::from_utf16_lossy(&buf[..len]);
+ let letter = extract_drive_letter(&resolved)?;
+ drive_has_seek_penalty(letter)
+}
+
+// --- Aligned Sequential Slab Readahead + Singleflight Dedup (Modo HD Turbo) ---
+
+/// 512 KiB aligned sequential slabs balance seek coalescing (8-16 typical
+/// `.rpf` micro-reads per seek, ~3.4 ms transfer @ 150 MB/s) against read
+/// amplification and LRU slot density (4x more slabs in RAM than 2 MiB).
+const DEFAULT_HDD_SLAB_BYTES: usize = 512 << 10;
+const SLAB_SHARDS: usize = 8;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+struct SlabKey {
+ file_id: u64,
+ slab_idx: u64,
+}
+
+struct SlabEntry {
+ data: Arc<[u8]>,
+ epoch: u64,
+}
+
+struct SlabShardState {
+ entries: HashMap<SlabKey, SlabEntry>,
+ order: VecDeque<(SlabKey, u64)>,
+ used: usize,
+ tick: u64,
+}
+
+struct SlabShard {
+ budget: usize,
+ state: Mutex<SlabShardState>,
+}
+
+struct InflightSlot {
+ done: Mutex<Option<Result<Arc<[u8]>, std::io::ErrorKind>>>,
+ ready: Condvar,
+}
+
+struct InflightGuard<'a> {
+ cache: &'a HddSlabCache,
+ key: SlabKey,
+ slot: Arc<InflightSlot>,
+ finished: bool,
+}
+
+impl InflightGuard<'_> {
+ fn complete(mut self, result: Result<Arc<[u8]>, std::io::ErrorKind>) {
+ self.finished = true;
+ {
+ let mut map = self.cache.inflight.lock().unwrap_or_else(|e| e.into_inner());
+ map.remove(&self.key);
+ }
+ {
+ let mut done = self.slot.done.lock().unwrap_or_else(|e| e.into_inner());
+ *done = Some(result);
+ }
+ self.slot.ready.notify_all();
+ }
+}
+
+impl Drop for InflightGuard<'_> {
+ fn drop(&mut self) {
+ if !self.finished {
+ {
+ let mut map = self.cache.inflight.lock().unwrap_or_else(|e| e.into_inner());
+ map.remove(&self.key);
+ }
+ {
+ let mut done = self.slot.done.lock().unwrap_or_else(|e| e.into_inner());
+ *done = Some(Err(std::io::ErrorKind::Other));
+ }
+ self.slot.ready.notify_all();
+ }
+ }
+}
+
+/// Aligned sequential slab cache for mechanical HDDs (`Modo HD Turbo`).
+///
+/// Turns dozens of scattered 4–256 KiB random `.rpf` reads (each costing ~10 ms
+/// head seek on a 7200 RPM platter = ~6 MB/s) into single aligned 2 MiB
+/// sequential reads (~13 ms transfer @ 150 MB/s) served to all concurrent
+/// workers from sharded RAM with per-slab singleflight deduplication.
+pub(super) struct HddSlabCache {
+ slab_size: usize,
+ budget: usize,
+ shards: Vec<SlabShard>,
+ inflight: Mutex<HashMap<SlabKey, Arc<InflightSlot>>>,
+ hits: AtomicU64,
+ coalesced: AtomicU64,
+ misses: AtomicU64,
+ bytes_read: AtomicU64,
+ inserts: AtomicU64,
+}
+
+impl HddSlabCache {
+ pub(super) fn new(budget_bytes: usize, slab_size: usize) -> Self {
+ let slab_size = slab_size.max(4096);
+ let shard_count = if budget_bytes >= slab_size.saturating_mul(SLAB_SHARDS) {
+ SLAB_SHARDS
+ } else {
+ 1
+ };
+ let per_shard = budget_bytes / shard_count;
+ let rem = budget_bytes % shard_count;
+ let shards = (0..shard_count)
+ .map(|i| SlabShard {
+ budget: per_shard + usize::from(i < rem),
+ state: Mutex::new(SlabShardState {
+ entries: HashMap::new(),
+ order: VecDeque::new(),
+ used: 0,
+ tick: 0,
+ }),
+ })
+ .collect();
+ Self {
+ slab_size,
+ budget: budget_bytes,
+ shards,
+ inflight: Mutex::new(HashMap::new()),
+ hits: AtomicU64::new(0),
+ coalesced: AtomicU64::new(0),
+ misses: AtomicU64::new(0),
+ bytes_read: AtomicU64::new(0),
+ inserts: AtomicU64::new(0),
+ }
+ }
+
+ pub(super) fn from_env() -> Self {
+ let slab_kb = std::env::var("VICTORY_DSTORAGE_SLAB_KB")
+ .ok()
+ .and_then(|v| v.trim().parse::<usize>().ok())
+ .unwrap_or(DEFAULT_HDD_SLAB_BYTES >> 10)
+ .clamp(64, 8192);
+ let slab_bytes = (slab_kb << 10).next_multiple_of(64 << 10);
+ let total_ram = total_physical_ram();
+ let default_budget_mb: usize = if total_ram <= (16 << 30) {
+ 256
+ } else if total_ram <= (24 << 30) {
+ 384
+ } else {
+ 768
+ };
+ let budget_mb = std::env::var("VICTORY_DSTORAGE_SLAB_BUDGET_MB")
+ .ok()
+ .and_then(|v| v.trim().parse::<usize>().ok())
+ .unwrap_or(default_budget_mb)
+ .clamp(32, 2048);
+ tracing::info!(
+ slab_kb = slab_bytes >> 10,
+ slab_budget_mb = budget_mb,
+ "dstorage: Modo HD Turbo aligned sequential slab readahead active"
+ );
+ Self::new(budget_mb << 20, slab_bytes)
+ }
+
+ #[inline]
+ fn shard(&self, key: SlabKey) -> &SlabShard {
+ if self.shards.len() == 1 {
+ return &self.shards[0];
+ }
+ let h = mix64(key.file_id ^ key.slab_idx.rotate_left(23));
+ &self.shards[(h as usize) % self.shards.len()]
+ }
+
+ fn get_slab(&self, key: SlabKey) -> Option<Arc<[u8]>> {
+ let shard = self.shard(key);
+ let mut s = shard.state.lock().unwrap_or_else(|e| e.into_inner());
+ let next_tick = s.tick.wrapping_add(1);
+ let entry = s.entries.get_mut(&key)?;
+ let data = Arc::clone(&entry.data);
+ entry.epoch = next_tick;
+ s.tick = next_tick;
+ s.order.push_back((key, next_tick));
+ if s.order.len() > s.entries.len().saturating_mul(4).saturating_add(32) {
+ let state = &mut *s;
+ let entries = &state.entries;
+ state.order.retain(|(k, g)| entries.get(k).is_some_and(|e| e.epoch == *g));
+ }
+ Some(data)
+ }
+
+ fn put_slab_checked(&self, key: SlabKey, data: Arc<[u8]>) {
+ if self.budget == 0 || data.is_empty() {
+ return;
+ }
+ let n = self.inserts.fetch_add(1, Ordering::Relaxed);
+ if n.is_multiple_of(32)
+ && let Some(avail) = available_physical_ram()
+ && avail < (2 << 30)
+ {
+ // Never push Windows into an HDD pagefile: drop slab cache immediately under < 2 GiB free RAM.
+ self.trim_to(0);
+ return;
+ }
+ let shard = self.shard(key);
+ if data.len() > shard.budget {
+ return;
+ }
+ let mut s = shard.state.lock().unwrap_or_else(|e| e.into_inner());
+ if s.entries.contains_key(&key) {
+ return;
+ }
+ let target = shard.budget.saturating_sub(data.len());
+ Self::evict_to(&mut s, target);
+ let tick = s.tick.wrapping_add(1);
+ s.tick = tick;
+ s.used += data.len();
+ s.entries.insert(key, SlabEntry { data, epoch: tick });
+ s.order.push_back((key, tick));
+ }
+
+ pub(super) fn trim_to(&self, limit_bytes: usize) {
+ let per_shard = limit_bytes / self.shards.len();
+ for shard in &self.shards {
+ let mut s = shard.state.lock().unwrap_or_else(|e| e.into_inner());
+ Self::evict_to(&mut s, per_shard);
+ if per_shard == 0 {
+ s.entries.shrink_to_fit();
+ s.order.shrink_to_fit();
+ }
+ }
+ }
+
+ fn evict_to(s: &mut SlabShardState, limit_bytes: usize) {
+ while s.used > limit_bytes {
+ let Some((key, epoch)) = s.order.pop_front() else {
+ s.entries.clear();
+ s.used = 0;
+ break;
+ };
+ let is_live = s.entries.get(&key).is_some_and(|e| e.epoch == epoch);
+ if is_live && let Some(removed) = s.entries.remove(&key) {
+ s.used = s.used.saturating_sub(removed.data.len());
+ }
+ }
+ }
+
+ #[cfg(test)]
+ pub(super) fn len_bytes(&self) -> usize {
+ self.shards
+ .iter()
+ .map(|sh| sh.state.lock().unwrap_or_else(|e| e.into_inner()).used)
+ .sum()
+ }
+
+ pub(super) fn stats(&self) -> (u64, u64, u64, u64) {
+ (
+ self.hits.load(Ordering::Relaxed),
+ self.coalesced.load(Ordering::Relaxed),
+ self.misses.load(Ordering::Relaxed),
+ self.bytes_read.load(Ordering::Relaxed) >> 20,
+ )
+ }
+
+ /// Reads `[offset, offset + out.len())` through aligned sequential slabs.
+ ///
+ /// - Returns `Ok(true)` if served completely through `HddSlabCache`.
+ /// - Returns `Ok(false)` if the read is larger than `2 * slab_size` (already
+ /// large sequential I/O) or the slab cache is disabled, signalling the
+ /// caller to perform a direct read.
+ /// - Returns `Err(io::Error)` on EOF or backing-file read error.
+ pub(super) fn read_through<F>(
+ &self,
+ file_id: u64,
+ offset: u64,
+ out: &mut [u8],
+ mut fetch_slab: F,
+ ) -> std::io::Result<bool>
+ where
+ F: FnMut(u64, &mut [u8]) -> std::io::Result<usize>,
+ {
+ if out.is_empty() {
+ return Ok(true);
+ }
+ if self.budget == 0
+ || self.slab_size == 0
+ || file_id == 0
+ || out.len() > self.slab_size.saturating_mul(2)
+ {
+ return Ok(false);
+ }
+ let slab_size_u64 = self.slab_size as u64;
+ let mut cur_off = offset;
+ let mut written = 0usize;
+ while written < out.len() {
+ let slab_idx = cur_off / slab_size_u64;
+ let slab_base = slab_idx * slab_size_u64;
+ let in_slab = (cur_off - slab_base) as usize;
+ let take = (out.len() - written).min(self.slab_size - in_slab);
+ let key = SlabKey { file_id, slab_idx };
+
+ let slab = self.fetch_or_coalesce(key, slab_base, &mut fetch_slab)?;
+ if in_slab + take > slab.len() {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::UnexpectedEof,
+ "dstorage: HDD slab read hit EOF",
+ ));
+ }
+ out[written..written + take].copy_from_slice(&slab[in_slab..in_slab + take]);
+ written += take;
+ cur_off += take as u64;
+ }
+ Ok(true)
+ }
+
+ fn fetch_or_coalesce<F>(
+ &self,
+ key: SlabKey,
+ slab_base: u64,
+ fetch_slab: &mut F,
+ ) -> std::io::Result<Arc<[u8]>>
+ where
+ F: FnMut(u64, &mut [u8]) -> std::io::Result<usize>,
+ {
+ // Fast path: already warm in sharded RAM LRU.
+ if let Some(slab) = self.get_slab(key) {
+ self.hits.fetch_add(1, Ordering::Relaxed);
+ return Ok(slab);
+ }
+ // Singleflight check: if another worker is already reading this exact 2 MiB
+ // slab from the HDD, wait on its Condvar instead of issuing a second seek!
+ let role = {
+ let mut map = self.inflight.lock().unwrap_or_else(|e| e.into_inner());
+ // Re-check LRU under inflight lock to avoid missing a just-finished fill.
+ if let Some(slab) = self.get_slab(key) {
+ self.hits.fetch_add(1, Ordering::Relaxed);
+ return Ok(slab);
+ }
+ if let Some(existing) = map.get(&key) {
+ Err(Arc::clone(existing))
+ } else {
+ let slot = Arc::new(InflightSlot {
+ done: Mutex::new(None),
+ ready: Condvar::new(),
+ });
+ map.insert(key, Arc::clone(&slot));
+ Ok(slot)
+ }
+ };
+ match role {
+ Err(wait_slot) => {
+ let mut done = wait_slot.done.lock().unwrap_or_else(|e| e.into_inner());
+ while done.is_none() {
+ done = wait_slot.ready.wait(done).unwrap_or_else(|e| e.into_inner());
+ }
+ match done.as_ref().unwrap() {
+ Ok(slab) => {
+ self.coalesced.fetch_add(1, Ordering::Relaxed);
+ Ok(Arc::clone(slab))
+ }
+ Err(kind) => Err(std::io::Error::new(*kind, "dstorage: coalesced HDD slab read failed")),
+ }
+ }
+ Ok(lead_slot) => {
+ let guard = InflightGuard {
+ cache: self,
+ key,
+ slot: lead_slot,
+ finished: false,
+ };
+ let mut buf = vec![0u8; self.slab_size];
+ match fetch_slab(slab_base, &mut buf) {
+ Ok(actual) => {
+ buf.truncate(actual.min(self.slab_size));
+ let slab: Arc<[u8]> = Arc::from(buf);
+ self.misses.fetch_add(1, Ordering::Relaxed);
+ self.bytes_read.fetch_add(slab.len() as u64, Ordering::Relaxed);
+ self.put_slab_checked(key, Arc::clone(&slab));
+ guard.complete(Ok(Arc::clone(&slab)));
+ Ok(slab)
+ }
+ Err(err) => {
+ let kind = err.kind();
+ guard.complete(Err(kind));
+ Err(err)
+ }
+ }
+ }
+ }
+ }
+}
+
+/// Picks the best index within the first `window` pending reads of a lane
+/// before `next_status_seq` (the earliest pending status barrier) to maximize
+/// sequential forward offset locality on SATA drives while bounding starvation
+/// via `max_skips`.
+pub(super) fn pick_elevator_index<T>(
+ reads: &VecDeque<T>,
+ next_status_seq: Option<u64>,
+ last_source: usize,
+ last_end: u64,
+ window: usize,
+ max_skips: u32,
+ skips: &mut u32,
+ meta: impl Fn(&T) -> (u64, usize, u64),
+) -> usize {
+ if reads.len() <= 1 || window <= 1 || last_source == 0 {
+ *skips = 0;
+ return 0;
+ }
+ if *skips >= max_skips {
+ *skips = 0;
+ return 0;
+ }
+ let limit = reads.len().min(window);
+ let mut best_forward: Option<(u64, usize)> = None;
+ let mut best_same_file: Option<(u64, usize)> = None;
+ for (idx, item) in reads.iter().take(limit).enumerate() {
+ let (seq, source, offset) = meta(item);
+ if next_status_seq.is_some_and(|s| seq >= s) {
+ break;
+ }
+ if source != last_source {
+ continue;
+ }
+ if offset >= last_end {
+ let dist = offset - last_end;
+ if best_forward.is_none_or(|(d, _)| dist < d) {
+ best_forward = Some((dist, idx));
+ }
+ } else {
+ let dist = last_end - offset;
+ if best_same_file.is_none_or(|(d, _)| dist < d) {
+ best_same_file = Some((dist, idx));
+ }
+ }
+ }
+ let chosen = best_forward.or(best_same_file).map_or(0, |(_, idx)| idx);
+ if chosen == 0 {
+ *skips = 0;
+ } else {
+ *skips = skips.saturating_add(1);
+ }
+ chosen
+}
+
+fn available_physical_ram() -> Option<u64> {
+ use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
+ // SAFETY: plain sized output struct.
+ let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
+ m.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
+ (unsafe { GlobalMemoryStatusEx(&mut m) } != 0).then_some(m.ullAvailPhys)
+}
+
+fn total_physical_ram() -> u64 {
+ use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
+ // SAFETY: plain sized output struct.
+ let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
+ m.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
+ if unsafe { GlobalMemoryStatusEx(&mut m) } != 0 {
+ m.ullTotalPhys
+ } else {
+ 32 << 30
+ }
+}
+
+fn parse_hdd_env() -> Option<bool> {
+ let raw = std::env::var("VICTORY_DSTORAGE_HDD").ok()?;
+ match raw.trim().to_ascii_lowercase().as_str() {
+ "1" | "on" | "true" | "hdd" | "turbo" => Some(true),
+ "0" | "off" | "false" | "ssd" => Some(false),
+ _ => None, // "auto" or empty
+ }
+}
+
+pub(super) struct StreamCache {
+ ram: RamCache,
+ disk: Option<Arc<AsyncDiskCache>>,
+ slab: OnceLock<HddSlabCache>,
+ io_limiter: IoLimiter,
+ io_conc_override: bool,
+ hdd_override: Option<bool>,
+ hdd_active: AtomicBool,
+ elevator_override: Option<usize>,
+ verify_compressed: bool,
+ ram_hits: AtomicU64,
+ disk_hits: AtomicU64,
+ misses: AtomicU64,
+ inserts: AtomicU64,
+}
+
+impl StreamCache {
+ pub(super) fn global() -> &'static Self {
+ static CACHE: OnceLock<StreamCache> = OnceLock::new();
+ CACHE.get_or_init(Self::from_env)
+ }
+
+ fn from_env() -> Self {
+ let hdd_override = parse_hdd_env();
+ let detected_game_hdd = std::env::var_os("VICTORY_GAME_DIR")
+ .filter(|v| !v.is_empty())
+ .and_then(|dir| is_rotational_drive(Path::new(&dir)))
+ .unwrap_or(false);
+ let initial_hdd = hdd_override.unwrap_or(detected_game_hdd);
+
+ let limited_ram = total_physical_ram() <= (32 << 30);
+ let default_ram_mb: u64 = if limited_ram { 64 } else { 128 };
+ let ram_mb = std::env::var("VICTORY_DSTORAGE_RAM_CACHE_MB")
+ .ok()
+ .and_then(|v| v.trim().parse::<u64>().ok())
+ .unwrap_or(default_ram_mb)
+ .min(1024);
+ let disk_mb = std::env::var("VICTORY_DSTORAGE_CACHE_MB")
+ .ok()
+ .and_then(|v| v.trim().parse::<u64>().ok())
+ .unwrap_or(6144)
+ .clamp(0, 32768);
+ let allow_hdd_cache = std::env::var("VICTORY_DSTORAGE_CACHE_ALLOW_HDD")
+ .ok()
+ .is_some_and(|v| v.trim() == "1");
+ let disk = std::env::var_os("VICTORY_DSTORAGE_CACHE_DIR")
+ .filter(|v| !v.is_empty() && disk_mb >= 64)
+ .and_then(|dir| {
+ let cache_path = Path::new(&dir);
+ if !allow_hdd_cache && is_rotational_drive(cache_path) == Some(true) {
+ tracing::warn!(
+ dir = %cache_path.display(),
+ "dstorage: cache dir is on a mechanical HDD — disabling writeback DiskCache to avoid read/write head thrashing (set VICTORY_DSTORAGE_CACHE_DIR to an SSD for Hybrid SSD+HDD acceleration)"
+ );
+ return None;
+ }
+ AsyncDiskCache::open(cache_path, disk_mb << 20)
+ .inspect_err(|e| tracing::warn!(error = %e, "dstorage: streaming disk cache disabled"))
+ .ok()
+ });
+ let explicit_io_conc = std::env::var("VICTORY_DSTORAGE_IO_CONCURRENCY")
+ .ok()
+ .and_then(|v| v.trim().parse::<usize>().ok());
+ let io_conc = explicit_io_conc
+ .unwrap_or(if initial_hdd { 1 } else { 4 })
+ .clamp(1, 32);
+ let elevator_override = std::env::var("VICTORY_DSTORAGE_ELEVATOR_WINDOW")
+ .ok()
+ .and_then(|v| v.trim().parse::<usize>().ok())
+ .map(|w| w.clamp(1, 512));
+ let verify_compressed =
+ std::env::var_os("VICTORY_DSTORAGE_CACHE_VERIFY").is_none_or(|v| v != "0");
+ let slab = OnceLock::new();
+ if initial_hdd {
+ let _ = slab.set(HddSlabCache::from_env());
+ }
+ tracing::info!(
+ hdd_mode = initial_hdd,
+ hdd_override = ?hdd_override,
+ ram_cache_mb = ram_mb,
+ disk_cache_mb = if disk.is_some() { disk_mb } else { 0 },
+ hybrid_ssd_cache = initial_hdd && disk.is_some(),
+ io_concurrency = io_conc,
+ verify_compressed,
+ "dstorage: streaming cache & I/O concurrency configured"
+ );
+ Self {
+ ram: RamCache::new((ram_mb as usize) << 20, MAX_RAM_BLOCK_BYTES),
+ disk,
+ slab,
+ io_limiter: IoLimiter::new(io_conc),
+ io_conc_override: explicit_io_conc.is_some(),
+ hdd_override,
+ hdd_active: AtomicBool::new(initial_hdd),
+ elevator_override,
+ verify_compressed,
+ ram_hits: AtomicU64::new(0),
+ disk_hits: AtomicU64::new(0),
+ misses: AtomicU64::new(0),
+ inserts: AtomicU64::new(0),
+ }
+ }
+
+ /// Inspects an opened archive's backing drive (resolving Xbox `G:\` virtual
+ /// paths via `GetFinalPathNameByHandleW`). When `VICTORY_DSTORAGE_HDD` is
+ /// `auto` and a mechanical HDD is detected, upgrades the running engine to
+ /// **Modo HD Turbo** dynamically.
+ pub(super) fn note_archive_file(&self, file: &File, display_path: &str) {
+ if self.hdd_override.is_some() || self.hdd_active.load(Ordering::Relaxed) {
+ return;
+ }
+ if is_rotational_file(file) == Some(true)
+ && !self.hdd_active.swap(true, Ordering::AcqRel)
+ {
+ if !self.io_conc_override {
+ self.io_limiter.set_limit(1);
+ }
+ let _ = self.slab.get_or_init(HddSlabCache::from_env);
+ tracing::info!(
+ path = display_path,
+ io_concurrency = self.io_limiter.limit(),
+ hybrid_ssd_cache = self.disk.is_some(),
+ "dstorage: mechanical HDD detected for archive — activated Modo HD Turbo (2 MiB sequential slab readahead, C-SCAN window=128, SEQUENTIAL_SCAN)"
+ );
+ }
+ }
+
+ #[inline]
+ pub(super) fn hdd_active(&self) -> bool {
+ self.hdd_active.load(Ordering::Acquire)
+ }
+
+ /// Returns `(window, max_skips)` for the C-SCAN offset elevator.
+ /// Mechanical HDDs get a wide `(128, 32)` window to sweep full streaming
+ /// bursts in strict ascending LBA order; SSDs keep `(16, 4)`.
+ #[inline]
+ pub(super) fn elevator_params(&self) -> (usize, u32) {
+ if let Some(w) = self.elevator_override {
+ return (w, (w / 4).clamp(1, 64) as u32);
+ }
+ if self.hdd_active() {
+ (128, 32)
+ } else {
+ (16, 4)
+ }
+ }
+
+ /// Serves a cold archive read through the 2 MiB aligned sequential slab
+ /// readahead cache when **Modo HD Turbo** is active.
+ pub(super) fn read_through_slab<F>(
+ &self,
+ file_id: u64,
+ offset: u64,
+ out: &mut [u8],
+ fetch_slab: F,
+ ) -> std::io::Result<bool>
+ where
+ F: FnMut(u64, &mut [u8]) -> std::io::Result<usize>,
+ {
+ if !self.hdd_active() {
+ return Ok(false);
+ }
+ let slab = self.slab.get_or_init(HddSlabCache::from_env);
+ slab.read_through(file_id, offset, out, fetch_slab)
+ }
+
+ pub(super) fn try_read(&self, key: BlockKey, out: &mut [u8], self_checked: bool) -> bool {
+ if self.ram.get_into(key, out) {
+ self.ram_hits.fetch_add(1, Ordering::Relaxed);
+ return true;
+ }
+ let verify = !self_checked || self.verify_compressed;
+ if let Some(disk) = &self.disk
+ && disk.get_into_checked(key, out, verify)
+ {
+ self.disk_hits.fetch_add(1, Ordering::Relaxed);
+ self.put_ram_checked(key, out);
+ return true;
+ }
+ self.misses.fetch_add(1, Ordering::Relaxed);
+ false
+ }
+
+ pub(super) fn record_miss(&self, key: BlockKey, data: &[u8]) {
+ self.put_ram_checked(key, data);
+ if let Some(disk) = &self.disk {
+ disk.enqueue(key, data);
+ }
+ }
+
+ fn put_ram_checked(&self, key: BlockKey, data: &[u8]) {
+ let n = self.inserts.fetch_add(1, Ordering::Relaxed);
+ if n.is_multiple_of(256)
+ && let Some(avail) = available_physical_ram()
+ && avail < (2 << 30)
+ {
+ self.ram.trim_to(0);
+ if let Some(slab) = self.slab.get() {
+ slab.trim_to(0);
+ }
+ return;
+ }
+ self.ram.put(key, data);
+ }
+
+ pub(super) fn acquire_io(&self) -> IoPermit<'_> {
+ self.io_limiter.acquire()
+ }
+
+ pub(super) fn stats(&self) -> (u64, u64, u64, u64) {
+ let written_mb = self
+ .disk
+ .as_ref()
+ .map_or(0, |d| d.written_bytes.load(Ordering::Relaxed) >> 20);
+ (
+ self.ram_hits.load(Ordering::Relaxed),
+ self.disk_hits.load(Ordering::Relaxed),
+ self.misses.load(Ordering::Relaxed),
+ written_mb,
+ )
+ }
+
+ pub(super) fn slab_stats(&self) -> (u64, u64, u64, u64) {
+ self.slab.get().map_or((0, 0, 0, 0), HddSlabCache::stats)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn file_identity_normalizes_path_and_invalidates_on_metadata_change() {
+ let a = file_identity(r"G:\Data\Levels.RPF", 1024, 555);
+ let b = file_identity("g:/data/levels.rpf", 1024, 555);
+ let diff_size = file_identity(r"G:\Data\Levels.RPF", 2048, 555);
+ let diff_mtime = file_identity(r"G:\Data\Levels.RPF", 1024, 556);
+ assert_ne!(a, 0);
+ assert_eq!(a, b);
+ assert_ne!(a, diff_size);
+ assert_ne!(a, diff_mtime);
+ }
+
+ #[test]
+ fn ram_cache_enforces_budget_lru_eviction_and_trim() {
+ let cache = RamCache::new(100, 60);
+ let k1 = BlockKey { file_id: 1, offset: 0, size: 40 };
+ let k2 = BlockKey { file_id: 1, offset: 40, size: 40 };
+ let k3 = BlockKey { file_id: 1, offset: 80, size: 40 };
+ let too_big = BlockKey { file_id: 1, offset: 120, size: 80 };
+
+ cache.put(k1, &[1u8; 40]);
+ cache.put(k2, &[2u8; 40]);
+ cache.put(too_big, &[9u8; 80]); // exceeds max_block_bytes
+ assert_eq!(cache.len_bytes(), 80);
+
+ // Touch k1 so k2 becomes least-recently-used.
+ let mut out = [0u8; 40];
+ assert!(cache.get_into(k1, &mut out));
+ assert_eq!(out, [1u8; 40]);
+
+ // Inserting k3 (40 B) must evict k2 (not k1) to stay <= 100 B.
+ cache.put(k3, &[3u8; 40]);
+ assert!(cache.len_bytes() <= 100);
+ assert!(cache.get_into(k1, &mut out));
+ assert!(!cache.get_into(k2, &mut out));
+ assert!(cache.get_into(k3, &mut out));
+ assert_eq!(out, [3u8; 40]);
+
+ // Pressure trim down to 0 clears everything.
+ cache.trim_to(0);
+ assert_eq!(cache.len_bytes(), 0);
+ assert!(!cache.get_into(k1, &mut out));
+ }
+
+ #[test]
+ fn ram_cache_sharded_enforces_total_budget_and_concurrent_reads() {
+ let cache = Arc::new(RamCache::new(16 * 1024, 512));
+ assert_eq!(cache.shards.len(), RAM_SHARDS);
+ for i in 0..128u64 {
+ let key = BlockKey { file_id: 7, offset: i * 512, size: 256 };
+ cache.put(key, &[(i as u8); 256]);
+ }
+ assert!(cache.len_bytes() <= 16 * 1024);
+ std::thread::scope(|s| {
+ for t in 0..4u64 {
+ let c = cache.clone();
+ s.spawn(move || {
+ let mut buf = [0u8; 256];
+ for i in 0..128u64 {
+ let key = BlockKey { file_id: 7, offset: ((i + t * 13) % 128) * 512, size: 256 };
+ if c.get_into(key, &mut buf) {
+ assert_eq!(buf, [((i + t * 13) % 128) as u8; 256]);
+ }
+ }
+ });
+ }
+ });
+ cache.trim_to(0);
+ assert_eq!(cache.len_bytes(), 0);
+ }
+
+ #[test]
+ fn disk_cache_persists_across_reopen_wraps_ring_and_rejects_corruption() {
+ let dir = tempfile::tempdir().unwrap();
+ // 2 segments of 2048 bytes each (4096 B total cap).
+ let k1 = BlockKey { file_id: 42, offset: 0x1000, size: 600 };
+ let k2 = BlockKey { file_id: 42, offset: 0x2000, size: 600 };
+ let k3 = BlockKey { file_id: 42, offset: 0x3000, size: 600 };
+ let k4 = BlockKey { file_id: 42, offset: 0x4000, size: 600 };
+ let k5 = BlockKey { file_id: 42, offset: 0x5000, size: 600 };
+ let k6 = BlockKey { file_id: 42, offset: 0x6000, size: 600 };
+ let k7 = BlockKey { file_id: 42, offset: 0x7000, size: 600 };
+
+ {
+ let cache = DiskCache::open(dir.path(), 4096, 2048).unwrap();
+ cache.put_sync(k1, &[0x11; 600]);
+ cache.put_sync(k2, &[0x22; 600]);
+ cache.put_sync(k3, &[0x33; 600]);
+ cache.flush_index().unwrap();
+ let mut out = vec![0u8; 600];
+ assert!(cache.get_into(k1, &mut out));
+ assert_eq!(out, vec![0x11; 600]);
+ assert!(cache.get_into(k3, &mut out));
+ assert_eq!(out, vec![0x33; 600]);
+ }
+
+ // Reopen persisted cache: k1..k3 must be immediately available.
+ {
+ let cache = DiskCache::open(dir.path(), 4096, 2048).unwrap();
+ assert_eq!(cache.entry_count(), 3);
+ let mut out = vec![0u8; 600];
+ assert!(cache.get_into(k2, &mut out));
+ assert_eq!(out, vec![0x22; 600]);
+
+ // Write enough new blocks to wrap segment 0 and evict k1..k3.
+ cache.put_sync(k4, &[0x44; 600]);
+ cache.put_sync(k5, &[0x55; 600]);
+ cache.put_sync(k6, &[0x66; 600]);
+ cache.put_sync(k7, &[0x77; 600]);
+ cache.flush_index().unwrap();
+ assert!(!cache.get_into(k1, &mut out), "oldest segment must be evicted on ring wrap");
+ assert!(cache.get_into(k7, &mut out));
+ assert_eq!(out, vec![0x77; 600]);
+ }
+
+ // Corrupt a payload byte on disk -> checksum check must treat as miss (never return corrupt bytes).
+ let seg0 = dir.path().join("seg-000.bin");
+ let seg1 = dir.path().join("seg-001.bin");
+ for seg in [&seg0, &seg1] {
+ if let Ok(mut bytes) = std::fs::read(seg) {
+ if bytes.len() > 128 {
+ bytes[100] ^= 0xFF;
+ std::fs::write(seg, bytes).unwrap();
+ }
+ }
+ }
+ let cache = DiskCache::open(dir.path(), 4096, 2048).unwrap();
+ let mut out = vec![0u8; 600];
+ let mut any_corrupt_returned = false;
+ for (k, pat) in [(k4, 0x44u8), (k5, 0x55), (k6, 0x66), (k7, 0x77)] {
+ if cache.get_into(k, &mut out) && out != vec![pat; 600] {
+ any_corrupt_returned = true;
+ }
+ }
+ assert!(!any_corrupt_returned, "corrupted disk bytes must never be served");
+ }
+
+ #[test]
+ fn elevator_picks_nearest_forward_offset_within_batch_and_bounds_starvation() {
+ // Queue entries: (seq, file_id, offset)
+ let reads = VecDeque::from([
+ (10, 1, 900_000),
+ (11, 1, 200_000),
+ (12, 1, 120_000), // nearest forward from last_end=100_000!
+ (13, 1, 105_000), // AFTER status barrier at seq=13 -> must NOT jump past!
+ ]);
+ let mut skips = 0;
+ let idx = pick_elevator_index(&reads, Some(13), 1, 100_000, 16, 4, &mut skips, |&x| x);
+ assert_eq!(idx, 2, "must pick seq 12 (offset 120_000) without crossing status seq 13");
+ assert_eq!(skips, 1);
+
+ // Once skips hits max_skips, must serve head (idx 0) so oldest read never starves.
+ skips = 4;
+ let idx_head = pick_elevator_index(&reads, Some(13), 1, 100_000, 16, 4, &mut skips, |&x| x);
+ assert_eq!(idx_head, 0);
+ assert_eq!(skips, 0);
+ }
+
+ #[test]
+ fn io_limiter_caps_concurrent_holders() {
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ let limiter = Arc::new(IoLimiter::new(2));
+ let active = Arc::new(AtomicUsize::new(0));
+ let peak = Arc::new(AtomicUsize::new(0));
+ std::thread::scope(|s| {
+ for _ in 0..8 {
+ let (l, a, p) = (limiter.clone(), active.clone(), peak.clone());
+ s.spawn(move || {
+ let _permit = l.acquire();
+ let cur = a.fetch_add(1, Ordering::SeqCst) + 1;
+ p.fetch_max(cur, Ordering::SeqCst);
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ a.fetch_sub(1, Ordering::SeqCst);
+ });
+ }
+ });
+ assert!(peak.load(Ordering::SeqCst) <= 2);
+ assert_eq!(active.load(Ordering::SeqCst), 0);
+ }
+
+ #[test]
+ fn disk_cache_overlapped_parallel_reads_match_payloads() {
+ let dir = tempfile::tempdir().unwrap();
+ let cache = Arc::new(DiskCache::open(dir.path(), 1 << 20, 256 << 10).unwrap());
+ let mut blocks = Vec::new();
+ for i in 0u64..32 {
+ let len = 4096 + ((i as usize % 7) * 513);
+ let key = BlockKey { file_id: 99, offset: i * 0x4000, size: len as u32 };
+ let payload: Vec<u8> = (0..len).map(|j| ((i as usize * 31 + j * 17) & 0xff) as u8).collect();
+ cache.put_sync(key, &payload);
+ blocks.push((key, payload));
+ }
+ let blocks = Arc::new(blocks);
+
+ // Hammer the same overlapped segment handle from 8 reader threads while
+ // a concurrent writer appends new blocks to the active segment.
+ std::thread::scope(|s| {
+ for t in 0..8usize {
+ let (c, b) = (cache.clone(), blocks.clone());
+ s.spawn(move || {
+ let mut buf = Vec::new();
+ for iter in 0..64 {
+ let idx = (t * 7 + iter * 5) % b.len();
+ let (key, expected) = &b[idx];
+ buf.resize(expected.len(), 0);
+ assert!(c.get_into(*key, &mut buf), "parallel overlapped read missed block {idx}");
+ assert_eq!(&buf, expected, "parallel overlapped read corrupted block {idx}");
+ }
+ });
+ }
+ let c_write = cache.clone();
+ s.spawn(move || {
+ for i in 32u64..48 {
+ let key = BlockKey { file_id: 99, offset: i * 0x4000, size: 4096 };
+ let payload = vec![(i as u8).wrapping_mul(13); 4096];
+ c_write.put_sync(key, &payload);
+ }
+ });
+ });
+
+ // Also confirm reopened overlapped readers work after flushing the index.
+ cache.flush_index().unwrap();
+ let reopened = DiskCache::open(dir.path(), 1 << 20, 256 << 10).unwrap();
+ let mut buf = Vec::new();
+ for (key, expected) in blocks.iter() {
+ buf.resize(expected.len(), 0);
+ assert!(reopened.get_into(*key, &mut buf));
+ assert_eq!(&buf, expected);
+ }
+ }
+
+ #[test]
+ fn rotational_drive_detection_parses_paths_and_queries_host_drives() {
+ assert_eq!(extract_drive_letter(r"C:\Games\GTA6"), Some(b'C'));
+ assert_eq!(extract_drive_letter("d:/gta6/pack/world.rpf"), Some(b'D'));
+ assert_eq!(extract_drive_letter(r"\\?\F:\gta6\game.exe"), Some(b'F'));
+ assert_eq!(extract_drive_letter(r"\\.\e:\data"), Some(b'E'));
+ assert_eq!(extract_drive_letter(r"\\server\share\file.rpf"), None);
+ assert_eq!(extract_drive_letter("relative/path.rpf"), None);
+
+ // Live zero-admin query against the host temp drive (must succeed cleanly on Windows).
+ let tmp = std::env::temp_dir();
+ let res = is_rotational_drive(&tmp);
+ assert!(res.is_some(), "IOCTL_STORAGE_QUERY_PROPERTY should classify temp drive {tmp:?}");
+
+ // Live GetFinalPathNameByHandleW check on an open temporary file.
+ let file = tempfile::tempfile().unwrap();
+ assert_eq!(is_rotational_file(&file), res);
+ }
+
+ #[test]
+ fn hdd_slab_cache_coalesces_scattered_reads_boundary_eof_and_eviction() {
+ const SLAB: usize = 64 * 1024; // 64 KiB slabs for fast unit testing
+ // Synthetic 150 KiB archive (2 full slabs + 22 KiB tail).
+ let archive: Vec<u8> = (0..(2 * SLAB + 22 * 1024))
+ .map(|i| ((i.wrapping_mul(251) ^ (i >> 7)) & 0xff) as u8)
+ .collect();
+ let disk_reads = AtomicUsize::new(0);
+ let cache = HddSlabCache::new(2 * SLAB, SLAB);
+
+ let fetch = |base: u64, buf: &mut [u8]| -> std::io::Result<usize> {
+ disk_reads.fetch_add(1, Ordering::SeqCst);
+ let start = base as usize;
+ if start >= archive.len() {
+ return Ok(0);
+ }
+ let avail = (archive.len() - start).min(buf.len());
+ buf[..avail].copy_from_slice(&archive[start..start + avail]);
+ Ok(avail)
+ };
+
+ // 32 scattered 1 KiB reads inside slab 0 -> ONLY 1 physical disk read!
+ let mut out = vec![0u8; 1024];
+ for i in 0..32usize {
+ let off = ((i * 1997) % (SLAB - 1024)) as u64;
+ assert!(cache.read_through(77, off, &mut out, fetch).unwrap());
+ assert_eq!(&out[..], &archive[off as usize..off as usize + 1024]);
+ }
+ assert_eq!(disk_reads.load(Ordering::SeqCst), 1, "32 scattered reads in 1 slab must issue exactly 1 disk read");
+
+ // Cross-slab boundary read spanning slab 0 -> slab 1: only 1 MORE disk read (slab 1).
+ let mut cross = vec![0u8; 8192];
+ let cross_off = (SLAB - 3000) as u64;
+ assert!(cache.read_through(77, cross_off, &mut cross, fetch).unwrap());
+ assert_eq!(&cross[..], &archive[cross_off as usize..cross_off as usize + 8192]);
+ assert_eq!(disk_reads.load(Ordering::SeqCst), 2);
+
+ // Tail slab 2 (partial 22 KiB) succeeds inside EOF and evicts oldest slab to keep <= budget.
+ let mut tail = vec![0u8; 4096];
+ let tail_off = (2 * SLAB + 18 * 1024) as u64;
+ assert!(cache.read_through(77, tail_off, &mut tail, fetch).unwrap());
+ assert_eq!(&tail[..], &archive[tail_off as usize..tail_off as usize + 4096]);
+ assert!(cache.len_bytes() <= 2 * SLAB);
+
+ // Reading past EOF must fail with UnexpectedEof.
+ let mut past_eof = vec![0u8; 4096];
+ let err = cache
+ .read_through(77, (archive.len() - 100) as u64, &mut past_eof, fetch)
+ .unwrap_err();
+ assert_eq!(err.kind(), std::io::ErrorKind::UnexpectedEof);
+
+ // Giant read (> 2 * SLAB) bypasses slab cache (`Ok(false)`).
+ let mut giant = vec![0u8; 2 * SLAB + 1];
+ assert!(!cache.read_through(77, 0, &mut giant, fetch).unwrap());
+
+ // Pressure trim clears all cached slabs.
+ cache.trim_to(0);
+ assert_eq!(cache.len_bytes(), 0);
+ }
+
+ #[test]
+ fn hdd_slab_cache_singleflight_deduplicates_concurrent_misses() {
+ const SLAB: usize = 64 * 1024;
+ let archive: Arc<Vec<u8>> = Arc::new((0..SLAB).map(|i| (i * 37 % 251) as u8).collect());
+ let cache = Arc::new(HddSlabCache::new(256 * 1024, SLAB));
+ let physical_reads = Arc::new(AtomicUsize::new(0));
+ let barrier = Arc::new(std::sync::Barrier::new(8));
+
+ std::thread::scope(|s| {
+ for t in 0..8usize {
+ let (a, c, p, b) = (archive.clone(), cache.clone(), physical_reads.clone(), barrier.clone());
+ s.spawn(move || {
+ b.wait();
+ let off = (t * 4096 + 123) as u64;
+ let mut out = vec![0u8; 2048];
+ let ok = c
+ .read_through(55, off, &mut out, |base, dst| {
+ p.fetch_add(1, Ordering::SeqCst);
+ // Simulate a 15 ms mechanical HDD seek + sequential transfer.
+ std::thread::sleep(Duration::from_millis(15));
+ let n = dst.len().min(a.len() - base as usize);
+ dst[..n].copy_from_slice(&a[base as usize..base as usize + n]);
+ Ok(n)
+ })
+ .unwrap();
+ assert!(ok);
+ assert_eq!(&out[..], &a[off as usize..off as usize + 2048]);
+ });
+ }
+ });
+
+ assert_eq!(
+ physical_reads.load(Ordering::SeqCst),
+ 1,
+ "8 concurrent threads hitting the same cold slab must perform ONLY 1 physical HDD read"
+ );
+ let (hits, coalesced, misses, _) = cache.stats();
+ assert_eq!(misses, 1);
+ assert_eq!(hits + coalesced, 7);
+ }
+
+ #[test]
+ fn hdd_slab_cache_seek_model_proves_over_10x_reduction_on_150mbs_hdd() {
+ // Model a 7200 RPM 150 MB/s HDD: 9.0 ms average seek + len / (150 MB/s).
+ // Workload: 64 scattered 32 KiB `.rpf` reads across a 4 MiB map region (2 slabs).
+ const SLAB: usize = 2 << 20;
+ const READ_LEN: usize = 32 << 10;
+ let offsets: Vec<u64> = (0..64u64)
+ .map(|i| ((i * 59_113) % ((2 * SLAB - READ_LEN) as u64)) & !4095)
+ .collect();
+
+ // Baseline (no slab cache): 64 separate small reads = 64 seeks.
+ let baseline_ms: f64 = offsets
+ .iter()
+ .map(|_| 9.0 + (READ_LEN as f64) / (150.0 * 1024.0 * 1024.0) * 1000.0)
+ .sum();
+
+ // With HddSlabCache: count actual physical reads & bytes read.
+ let cache = HddSlabCache::new(16 << 20, SLAB);
+ let mut phys_seeks = 0usize;
+ let mut phys_bytes = 0usize;
+ let mut out = vec![0u8; READ_LEN];
+ for &off in &offsets {
+ assert!(
+ cache
+ .read_through(101, off, &mut out, |_base, dst| {
+ phys_seeks += 1;
+ phys_bytes += dst.len();
+ dst.fill(0xAB);
+ Ok(dst.len())
+ })
+ .unwrap()
+ );
+ }
+ let turbo_ms =
+ phys_seeks as f64 * 9.0 + (phys_bytes as f64) / (150.0 * 1024.0 * 1024.0) * 1000.0;
+ assert_eq!(phys_seeks, 2, "64 clustered reads across 4 MiB must collapse into 2 slab seeks");
+ assert!(
+ baseline_ms / turbo_ms > 10.0,
+ "expected >10x HDD speedup (baseline={baseline_ms:.1} ms vs turbo={turbo_ms:.1} ms)"
+ );
+ }
+
+ #[test]
+ fn io_limiter_dynamic_set_limit_caps_to_one_for_hdd() {
+ let limiter = IoLimiter::new(4);
+ assert_eq!(limiter.limit(), 4);
+ limiter.set_limit(1);
+ assert_eq!(limiter.limit(), 1);
+ let _p = limiter.acquire();
+ assert_eq!(*limiter.state.lock().unwrap(), 1);
+ }
+}
diff --git a/crates/victory-loader/src/engine.rs b/crates/victory-loader/src/engine.rs
new file mode 100644
index 0000000..cecfe25
--- /dev/null
+++ b/crates/victory-loader/src/engine.rs
@@ -0,0 +1,885 @@
+//! Verified RAGE 9 engine-level graphics quality controls for
+//! `game_scarlett_master.exe` (build `1.0.2.1`, Xbox Series X|S).
+//!
+//! Ported conceptually from `HSgod/ps5-fpsunlocker-gta6` (`low_shadows` and
+//! `low_volumetric`), with every RVA and expected byte sequence independently
+//! disassembled and verified against `game_scarlett_master.exe` (`1.0.2.1`):
+//!
+//! - **`VICTORY_LOW_SHADOWS`** (`0`/unset = stock, `1`/`1280`/`low` = 1280 px
+//! shadow atlas tier [PS5 `low_shadows=1` match], `2`/`1024`/`ultra` = 1024 px
+//! engine default fallback, `1536`/`med` = tier 0, `2048`/`high` = tier 2):
+//! Patches the central `GetShadowMapResolution(out, tier, half_flag, ...)`
+//! helper at `+0x1ce8bb0` (which indexes the `u32[4]` tier table at
+//! `+0x63deff8`: `[1536, 1280, 2048, 4096]`). All four engine callers
+//! (`+0xcc38e6` primary shadow atlas, `+0xcc39e2` secondary half-res atlas,
+//! `+0x5a40f85`, and `CSettingsManager::ApplySettings -> +0x5ad0aae` which
+//! computes `1024.0f / shadow_res` into `+0x84ddbc0`) call `+0x1ce8bb0`, so
+//! patching it once keeps both render-target sizes and shader texel scales
+//! synchronized.
+//!
+//! - **`VICTORY_LOW_VOLUMETRIC`** (`0`/unset = stock, `1` = 128 px / 7 mips
+//! [PS5 `low_volumetric=1` match]):
+//! Patches the volumetric / reflection map setter at `+0x1c9bea0` (called
+//! from `CSettingsManager::ApplySettings` at `+0x2243605 -> +0x599c810 ->
+//! +0x1c9bea0`). Clearing its `setg al` (`0f 9f c0` -> `90 90 90`) leaves
+//! `eax = 0`, fixing the map resolution (`+0x8551628`) to `128 << 0 = 128`
+//! and mip count (`+0x855162c`) to `7 + 0 = 7` (instead of `256` / `8`).
+//!
+//! Each setting is OFF by default, compared byte-for-byte before writing, and
+//! publishes its outcome in `VICTORY_ENGINE_STATUS_<NAME>` (`Done` / `Differs`
+//! / `Failed`) so the F1 menu can report honest status.
+
+use crate::patch::{Change, Patched, Site};
+
+/// Shadow map resolution override requested via `VICTORY_LOW_SHADOWS`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ShadowPreset {
+ /// Tier 1 (`1280` px, `1280x5120` 4-cascade atlas): exact PS5 `low_shadows=1`.
+ Low1280,
+ /// Engine fallback (`1024` px, `1024x4096` 4-cascade atlas): smallest native size.
+ UltraLow1024,
+ /// Tier 0 (`1536` px).
+ Med1536,
+ /// Tier 2 (`2048` px).
+ High2048,
+}
+
+impl ShadowPreset {
+ pub fn parse(spec: &str) -> Option<Self> {
+ match spec.trim().to_ascii_lowercase().as_str() {
+ "" | "0" | "off" | "stock" => None,
+ "1" | "low" | "1280" => Some(Self::Low1280),
+ "2" | "ultra" | "ultralow" | "1024" => Some(Self::UltraLow1024),
+ "med" | "medium" | "1536" => Some(Self::Med1536),
+ "high" | "2048" => Some(Self::High2048),
+ _ => None,
+ }
+ }
+
+ pub fn label(self) -> &'static str {
+ match self {
+ Self::Low1280 => "1280px (tier 1)",
+ Self::UltraLow1024 => "1024px (ultra-low)",
+ Self::Med1536 => "1536px (tier 0)",
+ Self::High2048 => "2048px (tier 2)",
+ }
+ }
+}
+
+/// Reads `VICTORY_LOW_SHADOWS`. `None` if unset, `0`, or unrecognized (logged).
+pub fn asked_low_shadows() -> Option<ShadowPreset> {
+ let spec = std::env::var("VICTORY_LOW_SHADOWS").ok()?;
+ let trimmed = spec.trim();
+ if trimmed.is_empty() || trimmed == "0" || trimmed.eq_ignore_ascii_case("off") || trimmed.eq_ignore_ascii_case("stock") {
+ return None;
+ }
+ let preset = ShadowPreset::parse(trimmed);
+ if preset.is_none() {
+ eprintln!("VIctory: VICTORY_LOW_SHADOWS={spec}: expected 0 (stock), 1/1280 (low), 2/1024 (ultra-low), 1536, or 2048");
+ }
+ preset
+}
+
+/// Reads `VICTORY_LOW_VOLUMETRIC` (`1` = force 128 px / 7 mips).
+pub fn asked_low_volumetric() -> bool {
+ std::env::var("VICTORY_LOW_VOLUMETRIC")
+ .ok()
+ .is_some_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "on" | "low" | "128"))
+}
+
+/// Parses `VICTORY_LOD_SCALE` (`0.05..=1.0`, stock Series S = `0.50`, Series X = `0.75`).
+pub fn parse_lod_scale(spec: &str) -> Option<f32> {
+ let s = spec.trim();
+ if s.is_empty() || s.eq_ignore_ascii_case("stock") || s.eq_ignore_ascii_case("off") || s == "0" {
+ return None;
+ }
+ match s.to_ascii_lowercase().as_str() {
+ "low" => Some(0.25),
+ "med" | "medium" => Some(0.35),
+ "high" => Some(0.50),
+ _ => s.parse::<f32>().ok().filter(|v| v.is_finite() && (0.05..=1.0).contains(v)),
+ }
+}
+
+/// Reads `VICTORY_LOD_SCALE` (`0.05..=1.0`, `low`/`med`/`high`, or `0`/`off`/`stock`).
+pub fn asked_lod_scale() -> Option<f32> {
+ let spec = std::env::var("VICTORY_LOD_SCALE").ok()?;
+ let trimmed = spec.trim();
+ if trimmed.is_empty() || trimmed == "0" || trimmed.eq_ignore_ascii_case("off") || trimmed.eq_ignore_ascii_case("stock") {
+ return None;
+ }
+ let val = parse_lod_scale(trimmed);
+ if val.is_none() {
+ eprintln!("VIctory: VICTORY_LOD_SCALE={spec}: expected 0/stock, low (0.25), med (0.35), or float 0.05..=1.0");
+ }
+ val
+}
+
+/// Parses `VICTORY_SMALL_CULL` (`0.25..=16.0`, stock = `1.0`; higher culls tiny distant objects).
+pub fn parse_small_cull(spec: &str) -> Option<f32> {
+ let s = spec.trim();
+ if s.is_empty() || s.eq_ignore_ascii_case("stock") || s.eq_ignore_ascii_case("off") || s == "0" {
+ return None;
+ }
+ match s.to_ascii_lowercase().as_str() {
+ "med" | "medium" => Some(2.0),
+ "high" | "perf" => Some(3.0),
+ "max" | "ultra" => Some(4.5),
+ _ => s.parse::<f32>().ok().filter(|v| v.is_finite() && (0.25..=16.0).contains(v)),
+ }
+}
+
+/// Reads `VICTORY_SMALL_CULL` (`0.25..=16.0`, `med`/`high`/`max`, or `0`/`off`/`stock`).
+pub fn asked_small_cull() -> Option<f32> {
+ let spec = std::env::var("VICTORY_SMALL_CULL").ok()?;
+ let trimmed = spec.trim();
+ if trimmed.is_empty() || trimmed == "0" || trimmed.eq_ignore_ascii_case("off") || trimmed.eq_ignore_ascii_case("stock") {
+ return None;
+ }
+ let val = parse_small_cull(trimmed);
+ if val.is_none() {
+ eprintln!("VIctory: VICTORY_SMALL_CULL={spec}: expected 0/stock, med (2.0), high (3.0), max (4.5), or float 0.25..=16.0");
+ }
+ val
+}
+
+/// Parses `VICTORY_VEHICLE_LOD_BIAS` (`-2.0..=4.0`, stock = `0.0`).
+pub fn parse_vehicle_lod_bias(spec: &str) -> Option<f32> {
+ let s = spec.trim();
+ if s.is_empty() || s.eq_ignore_ascii_case("stock") || s.eq_ignore_ascii_case("off") || s == "0" {
+ return None;
+ }
+ s.parse::<f32>().ok().filter(|v| v.is_finite() && (-2.0..=4.0).contains(v))
+}
+
+/// Reads `VICTORY_VEHICLE_LOD_BIAS` (`-2.0..=4.0` or `0`/`off`/`stock`).
+pub fn asked_vehicle_lod_bias() -> Option<f32> {
+ let spec = std::env::var("VICTORY_VEHICLE_LOD_BIAS").ok()?;
+ let trimmed = spec.trim();
+ if trimmed.is_empty() || trimmed == "0" || trimmed.eq_ignore_ascii_case("off") || trimmed.eq_ignore_ascii_case("stock") {
+ return None;
+ }
+ let val = parse_vehicle_lod_bias(trimmed);
+ if val.is_none() {
+ eprintln!("VIctory: VICTORY_VEHICLE_LOD_BIAS={spec}: expected 0/stock or float -2.0..=4.0");
+ }
+ val
+}
+
+/// Parses a RAGE 9 quality tier (`enum.0xaae5818c`: `0=Low, 1=Medium, 2=High, 3=Ultra`).
+pub fn parse_quality_tier(spec: &str) -> Option<u32> {
+ match spec.trim().to_ascii_lowercase().as_str() {
+ "0" | "low" => Some(0),
+ "1" | "med" | "medium" => Some(1),
+ "2" | "high" => Some(2),
+ "3" | "ultra" => Some(3),
+ _ => None,
+ }
+}
+
+/// Reads `VICTORY_VOLUMETRIC_QUALITY` (`0`/`low`, `1`/`med`, `2`/`high`, `3`/`ultra`; unset/`stock`/`off` = untouched).
+pub fn asked_volumetric_quality() -> Option<u32> {
+ let spec = std::env::var("VICTORY_VOLUMETRIC_QUALITY").ok()?;
+ let s = spec.trim();
+ if s.is_empty() || s.eq_ignore_ascii_case("stock") || s.eq_ignore_ascii_case("off") {
+ return None;
+ }
+ parse_quality_tier(s)
+}
+
+/// Reads `VICTORY_TREE_QUALITY` (`low`/`0`, `med`/`1`, `high`/`2`, `ultra`/`3`; unset/`stock`/`off` = untouched).
+pub fn asked_tree_quality() -> Option<u32> {
+ let spec = std::env::var("VICTORY_TREE_QUALITY").ok()?;
+ let s = spec.trim();
+ if s.is_empty() || s.eq_ignore_ascii_case("stock") || s.eq_ignore_ascii_case("off") {
+ return None;
+ }
+ parse_quality_tier(s)
+}
+
+/// Reads `VICTORY_TREE_TESS` (`0`/`off` = force `treeTessellationEnabled = false`).
+pub fn asked_disable_tree_tess() -> bool {
+ std::env::var("VICTORY_TREE_TESS")
+ .ok()
+ .is_some_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "0" | "off" | "false"))
+}
+
+/// Reads `VICTORY_GRASS_SHADOWS` (`0`/`off`/`low` = force `shadowGrassShadows = Low (0)`).
+pub fn asked_disable_grass_shadows() -> bool {
+ std::env::var("VICTORY_GRASS_SHADOWS")
+ .ok()
+ .is_some_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "0" | "off" | "low" | "false"))
+}
+
+/// Reads `VICTORY_SHADOW_EXTRAS` (`0`/`off` = disable `shadowAlphaTintedShadows` & `shadowParticleShadows`).
+pub fn asked_disable_shadow_extras() -> bool {
+ std::env::var("VICTORY_SHADOW_EXTRAS")
+ .ok()
+ .is_some_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "0" | "off" | "false"))
+}
+
+/// Reads `VICTORY_TESS_LOW` (`1`/`on`/`low` = force `tessellation = Low (0)` & `deepsurfaceQuality = Low (0)`).
+pub fn asked_tess_low() -> bool {
+ std::env::var("VICTORY_TESS_LOW")
+ .ok()
+ .is_some_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "on" | "low" | "true"))
+}
+
+/// Verified image RVA of the `u32[4]` shadow map resolution table
+/// `[1536, 1280, 2048, 4096]` in `game_scarlett_master.exe` `1.0.2.1`.
+pub const SHADOW_TABLE_RVA: usize = 0x63deff8;
+
+/// Verified image RVAs written by [`VOLUMETRIC_RES`]:
+/// dirty flag (`+0x8554a74`), tier flag (`+0x8551640`), resolution (`+0x8551628`),
+/// and mip count (`+0x855162c`).
+pub const VOLUMETRIC_DIRTY_RVA: usize = 0x8554a74;
+pub const VOLUMETRIC_TIER_RVA: usize = 0x8551640;
+pub const VOLUMETRIC_RES_RVA: usize = 0x8551628;
+pub const VOLUMETRIC_MIPS_RVA: usize = 0x855162c;
+
+/// Verified image RVAs written by `CSettingsManager::ApplySettings` (`+0x22434a0`)
+/// in `game_scarlett_master.exe` `1.0.2.1`:
+/// - `LOD_SCALE_GLOBAL_RVA` (`+0xa15e200`): raw `<lodScale>` float (followed by `call +0x5edebc0`
+/// which computes `clamp(lodScale, 0, 1) * 950.0 + 50.0` into `+0x6b520b0`).
+/// - `SMALL_CULL_GLOBAL_RVA` (`+0x684984c`): `<smallCullThreshold>` float.
+/// - `VEHICLE_LOD_BIAS_GLOBAL_RVA` (`+0x8fe0850`): `<vehicleLodBias>` float (written by `+0x5eef340`).
+pub const LOD_SCALE_GLOBAL_RVA: usize = 0xa15e200;
+pub const SMALL_CULL_GLOBAL_RVA: usize = 0x684984c;
+pub const VEHICLE_LOD_BIAS_GLOBAL_RVA: usize = 0x8fe0850;
+pub const VEHICLE_LOD_BIAS_SETTER_RVA: usize = 0x5eef340;
+
+/// `+0x1ce8bb0`..`+0x1ce8bd3` (`game_scarlett_master.exe` `1.0.2.1`):
+/// `GetShadowMapResolution(out, tier, half_flag, ...)` prologue and tier-table lookup.
+pub const SHADOW_RES: Site = Site {
+ at: 0x1ce8bb0,
+ what: "shadow map resolution tier lookup",
+ bytes: &[
+ 0x56, 0x57, 0x53, 0x48, 0x83, 0xec, 0x20, // push rsi; push rdi; push rbx; sub rsp, 20h
+ 0xbe, 0x00, 0x04, 0x00, 0x00, // mov esi, 400h (1024 default)
+ 0x83, 0xfa, 0x03, // cmp edx, 3 [+12]
+ 0x77, 0x0d, // ja +0xd (to +0x1ce8bce) [+15]
+ 0x89, 0xd0, // mov eax, edx [+17]
+ 0x4c, 0x8d, 0x15, 0x2e, 0x64, 0x6f, 0x04, // lea r10, [+0x63deff8] [+19]
+ 0x41, 0x8b, 0x34, 0x82, // mov esi, [r10+rax*4] [+26]
+ 0x48, 0x8b, 0x7c, 0x24, 0x60, // mov rdi, [rsp+60h] [+30]
+ ],
+};
+
+/// `+0x1c9bea0`..`+0x1c9bece` (`game_scarlett_master.exe` `1.0.2.1`):
+/// Volumetric / reflection map resolution & mip setter called from
+/// `CSettingsManager::ApplySettings` (`+0x2243605 -> +0x599c810 -> +0x1c9bea0`).
+pub const VOLUMETRIC_RES: Site = Site {
+ at: 0x1c9bea0,
+ what: "volumetric/reflection map resolution setter",
+ bytes: &[
+ 0x31, 0xc0, // xor eax, eax
+ 0x85, 0xc9, // test ecx, ecx
+ 0xb9, 0x80, 0x00, 0x00, 0x00, // mov ecx, 80h (128)
+ 0xc6, 0x05, 0xc4, 0x8b, 0x8b, 0x06, 0x01, // mov byte [+0x8554a74], 1
+ 0x0f, 0x9f, 0xc0, // setg al [+16]
+ 0xc4, 0xe2, 0x79, 0xf7, 0xc9, // shlx ecx, ecx, eax
+ 0x89, 0x05, 0x82, 0x57, 0x8b, 0x06, // mov [+0x8551640], eax
+ 0x83, 0xc0, 0x07, // add eax, 7
+ 0x89, 0x0d, 0x61, 0x57, 0x8b, 0x06, // mov [+0x8551628], ecx
+ 0x89, 0x05, 0x5f, 0x57, 0x8b, 0x06, // mov [+0x855162c], eax
+ 0xc3, // ret
+ ],
+};
+
+/// Replacement bytes for [`SHADOW_RES`] for `preset`.
+///
+/// Only bytes `12..19` (`cmp edx, 3; ja +0xd; mov eax, edx`) are changed:
+/// - Table tiers replace them with `mov edx, <tier>; mov eax, edx`, keeping
+/// `edx` valid for the downstream cascade/mip check (`cmp edx, 2`) at `+0x1ce8bf2`.
+/// - `UltraLow1024` replaces them with `mov edx, 1; jmp +0xb` (landing on
+/// `mov rdi, [rsp+60h]` at byte 30 = `+0x1ce8bce`), keeping `esi = 1024` and
+/// `edx = 1`.
+pub fn shadow_res_code(preset: ShadowPreset) -> Vec<u8> {
+ let mut code = SHADOW_RES.bytes.to_vec();
+ match preset {
+ ShadowPreset::Med1536 => {
+ code[12..19].copy_from_slice(&[0xba, 0x00, 0x00, 0x00, 0x00, 0x89, 0xd0]);
+ }
+ ShadowPreset::Low1280 => {
+ code[12..19].copy_from_slice(&[0xba, 0x01, 0x00, 0x00, 0x00, 0x89, 0xd0]);
+ }
+ ShadowPreset::High2048 => {
+ code[12..19].copy_from_slice(&[0xba, 0x02, 0x00, 0x00, 0x00, 0x89, 0xd0]);
+ }
+ ShadowPreset::UltraLow1024 => {
+ // mov edx, 1 ; jmp +0x0b (19 + 11 = 30 -> +0x1ce8bce)
+ code[12..19].copy_from_slice(&[0xba, 0x01, 0x00, 0x00, 0x00, 0xeb, 0x0b]);
+ }
+ }
+ code
+}
+
+/// `+0x224360a`..`+0x224361a` (`game_scarlett_master.exe` `1.0.2.1`):
+/// `CSettingsManager::ApplySettings` loading `<lodScale>` (`[rsi+0xd4]`),
+/// writing it to `[+0xa15e200]`, and passing `xmm0` to `+0x5edebc0`
+/// (`clamp(lodScale, 0, 1) * 950.0 + 50.0 -> [+0x6b520b0]`).
+pub const LOD_SCALE: Site = Site {
+ at: 0x224360a,
+ what: "world LOD scale override",
+ bytes: &[
+ 0xc5, 0xfa, 0x10, 0x86, 0xd4, 0x00, 0x00, 0x00, // vmovss xmm0, [rsi+0xd4]
+ 0xc5, 0xfa, 0x11, 0x05, 0xe6, 0xab, 0xf1, 0x07, // vmovss [+0xa15e200], xmm0
+ ],
+};
+
+/// `+0x2243651`..`+0x2243661` (`game_scarlett_master.exe` `1.0.2.1`):
+/// `CSettingsManager::ApplySettings` copying `<smallCullThreshold>` (`[rsi+0x10c]`)
+/// into `[+0x684984c]`.
+pub const SMALL_CULL: Site = Site {
+ at: 0x2243651,
+ what: "small-object cull threshold override",
+ bytes: &[
+ 0xc5, 0xfa, 0x10, 0x86, 0x0c, 0x01, 0x00, 0x00, // vmovss xmm0, [rsi+0x10c]
+ 0xc5, 0xfa, 0x11, 0x05, 0xeb, 0x61, 0x60, 0x04, // vmovss [+0x684984c], xmm0
+ ],
+};
+
+/// `+0x2243720`..`+0x224372d` (`game_scarlett_master.exe` `1.0.2.1`):
+/// `CSettingsManager::ApplySettings` passing `<vehicleLodBias>` (`[rsi+0x184]`)
+/// to `+0x5eef340` (`vmovss [+0x8fe0850], xmm0; ret`).
+pub const VEHICLE_LOD_BIAS: Site = Site {
+ at: 0x2243720,
+ what: "vehicle LOD bias override",
+ bytes: &[
+ 0xc5, 0xfa, 0x10, 0x86, 0x84, 0x01, 0x00, 0x00, // vmovss xmm0, [rsi+0x184]
+ 0xe8, 0x13, 0xbc, 0xca, 0x03, // call +0x5eef340
+ ],
+};
+
+/// `+0x22436c7`..`+0x22436d5` (`game_scarlett_master.exe` `1.0.2.1`):
+/// `CSettingsManager::ApplySettings` loading `volumetricsRaymarchQuality` (`[rsi+0x194]`)
+/// before `vzeroupper; call +0x5ed7ba0` (writes `[+0x849ad38]`).
+pub const VOL_RAYMARCH_CALL: Site = Site {
+ at: 0x22436c7,
+ what: "volumetrics raymarch quality override",
+ bytes: &[
+ 0x8b, 0x8e, 0x94, 0x01, 0x00, 0x00, // mov ecx, [rsi+0x194]
+ 0xc5, 0xf8, 0x77, // vzeroupper
+ 0xe8, 0xcb, 0x44, 0xc9, 0x03, // call +0x5ed7ba0
+ ],
+};
+
+/// `+0x22436d5`..`+0x22436e0` (`game_scarlett_master.exe` `1.0.2.1`):
+/// `CSettingsManager::ApplySettings` loading `volumetricsLightingQuality` (`[rsi+0x190]`)
+/// before `call +0x5ed7bb0` (writes `[+0x849ad3c]`).
+pub const VOL_LIGHT_CALL: Site = Site {
+ at: 0x22436d5,
+ what: "volumetrics lighting quality override",
+ bytes: &[
+ 0x8b, 0x8e, 0x90, 0x01, 0x00, 0x00, // mov ecx, [rsi+0x190]
+ 0xe8, 0xd0, 0x44, 0xc9, 0x03, // call +0x5ed7bb0
+ ],
+};
+
+/// `+0x22436e9`..`+0x22436f4` (`game_scarlett_master.exe` `1.0.2.1`):
+/// `CSettingsManager::ApplySettings` loading `treeTessellationEnabled` (`[rsi+0x17c]`)
+/// before `call +0x5ebb980` (writes `byte [+0x876fea0]`).
+pub const TREE_TESS_CALL: Site = Site {
+ at: 0x22436e9,
+ what: "tree tessellation override",
+ bytes: &[
+ 0x8a, 0x8e, 0x7c, 0x01, 0x00, 0x00, // mov cl, [rsi+0x17c]
+ 0xe8, 0x8c, 0x82, 0xc7, 0x03, // call +0x5ebb980
+ ],
+};
+
+/// `+0x22436f4`..`+0x22436ff` (`game_scarlett_master.exe` `1.0.2.1`):
+/// `CSettingsManager::ApplySettings` loading `shadowGrassShadows` (`[rsi+0x154]`)
+/// before `call +0x58cb810`.
+pub const SHADOW_GRASS_CALL: Site = Site {
+ at: 0x22436f4,
+ what: "grass shadows quality override",
+ bytes: &[
+ 0x8b, 0x8e, 0x54, 0x01, 0x00, 0x00, // mov ecx, [rsi+0x154]
+ 0xe8, 0x11, 0x81, 0x68, 0x03, // call +0x58cb810
+ ],
+};
+
+/// `+0x22436ff`..`+0x224370a` (`game_scarlett_master.exe` `1.0.2.1`):
+/// `CSettingsManager::ApplySettings` loading `treeQuality` (`[rsi+0x178]`)
+/// for the primary tree LOD setter `call +0x5eb7870`.
+pub const TREE_QUAL_1_CALL: Site = Site {
+ at: 0x22436ff,
+ what: "tree quality override (primary)",
+ bytes: &[
+ 0x8b, 0x8e, 0x78, 0x01, 0x00, 0x00, // mov ecx, [rsi+0x178]
+ 0xe8, 0x66, 0x41, 0xc7, 0x03, // call +0x5eb7870
+ ],
+};
+
+/// `+0x2243715`..`+0x2243720` (`game_scarlett_master.exe` `1.0.2.1`):
+/// `CSettingsManager::ApplySettings` loading `treeQuality` (`[rsi+0x178]`)
+/// for the secondary tree LOD setter `call +0x5ebb990`.
+pub const TREE_QUAL_2_CALL: Site = Site {
+ at: 0x2243715,
+ what: "tree quality override (secondary)",
+ bytes: &[
+ 0x8b, 0x8e, 0x78, 0x01, 0x00, 0x00, // mov ecx, [rsi+0x178]
+ 0xe8, 0x70, 0x82, 0xc7, 0x03, // call +0x5ebb990
+ ],
+};
+
+/// `+0x5ad0a73`..`+0x5ad0a93` (`game_scarlett_master.exe` `1.0.2.1`):
+/// Inside shadow settings apply (`+0x5ad09f0`), loading `shadowAlphaTintedShadows`
+/// (`[rsi+0x150]`) and `shadowParticleShadows` (`[rsi+0x159]`).
+pub const SHADOW_ALPHA_PARTICLE: Site = Site {
+ at: 0x5ad0a73,
+ what: "alpha-tinted & particle shadows override",
+ bytes: &[
+ 0x8a, 0x8e, 0x50, 0x01, 0x00, 0x00, // mov cl, [rsi+0x150]
+ 0xe8, 0xf2, 0x4e, 0x53, 0xfa, // call +0x5970
+ 0x88, 0x05, 0xa1, 0xc3, 0xa0, 0x02, // mov byte [+0x84dce25], al
+ 0x45, 0x31, 0xc9, // xor r9d, r9d
+ 0x8a, 0x86, 0x59, 0x01, 0x00, 0x00, // mov al, [rsi+0x159]
+ 0x88, 0x05, 0xa1, 0xc3, 0xa0, 0x02, // mov byte [+0x84dce34], al
+ ],
+};
+
+/// `+0x2243738`..`+0x2243749` (`game_scarlett_master.exe` `1.0.2.1`):
+/// `CSettingsManager::ApplySettings` loading `tessellation` (`[rsi+0x80]`) and
+/// `deepsurfaceQuality` (`[rsi+0xb8]`) before `call +0x2607a00`.
+pub const TESS_DEEPSURF_CALL: Site = Site {
+ at: 0x2243738,
+ what: "tessellation & deepsurface quality override",
+ bytes: &[
+ 0x8b, 0x8e, 0x80, 0x00, 0x00, 0x00, // mov ecx, [rsi+0x80]
+ 0x8b, 0x96, 0xb8, 0x00, 0x00, 0x00, // mov edx, [rsi+0xb8]
+ 0xe8, 0xb7, 0x42, 0x3c, 0x00, // call +0x2607a00
+ ],
+};
+
+/// Replacement bytes for [`VOLUMETRIC_RES`]: NOPs out `setg al` (`+16..+19`)
+/// so `eax` remains `0`, fixing resolution to `128` and mip count to `7`.
+pub fn low_volumetric_code() -> Vec<u8> {
+ let mut code = VOLUMETRIC_RES.bytes.to_vec();
+ code[16..19].copy_from_slice(&[0x90, 0x90, 0x90]);
+ code
+}
+
+/// Replacement bytes for [`LOD_SCALE`] (`16` bytes, self-contained):
+/// `mov eax, imm32; mov [+0xa15e200], eax; vmovd xmm0, eax; nop`.
+/// Updates both `[+0xa15e200]` and `xmm0` for the following `call +0x5edebc0`.
+pub fn lod_scale_code(scale: f32) -> Vec<u8> {
+ let disp = (LOD_SCALE_GLOBAL_RVA as i64 - (LOD_SCALE.at + 5 + 6) as i64) as i32;
+ let mut code = Vec::with_capacity(16);
+ code.push(0xb8); // mov eax, imm32
+ code.extend_from_slice(&scale.to_bits().to_le_bytes());
+ code.extend_from_slice(&[0x89, 0x05]); // mov dword ptr [rip+disp], eax
+ code.extend_from_slice(&disp.to_le_bytes());
+ code.extend_from_slice(&[0xc5, 0xf9, 0x6e, 0xc0]); // vmovd xmm0, eax
+ code.push(0x90); // nop
+ code
+}
+
+/// Replacement bytes for [`SMALL_CULL`] (`16` bytes, self-contained):
+/// `mov dword ptr [+0x684984c], imm32; 6x nop`.
+pub fn small_cull_code(threshold: f32) -> Vec<u8> {
+ let disp = (SMALL_CULL_GLOBAL_RVA as i64 - (SMALL_CULL.at + 10) as i64) as i32;
+ let mut code = Vec::with_capacity(16);
+ code.extend_from_slice(&[0xc7, 0x05]); // mov dword ptr [rip+disp], imm32
+ code.extend_from_slice(&disp.to_le_bytes());
+ code.extend_from_slice(&threshold.to_bits().to_le_bytes());
+ code.extend_from_slice(&[0x90; 6]);
+ code
+}
+
+/// Replacement bytes for [`VEHICLE_LOD_BIAS`] (`13` bytes, self-contained):
+/// `mov dword ptr [+0x8fe0850], imm32; 3x nop`.
+pub fn vehicle_lod_bias_code(bias: f32) -> Vec<u8> {
+ let disp = (VEHICLE_LOD_BIAS_GLOBAL_RVA as i64 - (VEHICLE_LOD_BIAS.at + 10) as i64) as i32;
+ let mut code = Vec::with_capacity(13);
+ code.extend_from_slice(&[0xc7, 0x05]); // mov dword ptr [rip+disp], imm32
+ code.extend_from_slice(&disp.to_le_bytes());
+ code.extend_from_slice(&bias.to_bits().to_le_bytes());
+ code.extend_from_slice(&[0x90; 3]);
+ code
+}
+
+/// Replaces a 6-byte `mov ecx, [rsi+off]` prefix in a `Site` with
+/// `mov ecx, tier; nop` (`b9 <u32> 90`), preserving the trailing call.
+pub fn replace_ecx_imm(site: &Site, tier: u32) -> Vec<u8> {
+ let mut code = site.bytes.to_vec();
+ code[0] = 0xb9; // mov ecx, imm32
+ code[1..5].copy_from_slice(&tier.to_le_bytes());
+ code[5] = 0x90; // nop
+ code
+}
+
+/// Replaces the 6-byte `mov cl, [rsi+0x17c]` prefix of [`TREE_TESS_CALL`] with
+/// `mov cl, 0; 4x nop`.
+pub fn disable_tree_tess_code() -> Vec<u8> {
+ let mut code = TREE_TESS_CALL.bytes.to_vec();
+ code[0..6].copy_from_slice(&[0xb1, 0x00, 0x90, 0x90, 0x90, 0x90]);
+ code
+}
+
+/// Forces `shadowAlphaTintedShadows = 0` (`mov cl, 0`) and
+/// `shadowParticleShadows = 0` (`mov al, 0`) inside [`SHADOW_ALPHA_PARTICLE`].
+pub fn disable_shadow_extras_code() -> Vec<u8> {
+ let mut code = SHADOW_ALPHA_PARTICLE.bytes.to_vec();
+ code[0..6].copy_from_slice(&[0xb1, 0x00, 0x90, 0x90, 0x90, 0x90]);
+ code[20..26].copy_from_slice(&[0xb0, 0x00, 0x90, 0x90, 0x90, 0x90]);
+ code
+}
+
+/// Forces `tessellation = 0` (`mov ecx, 0`) and `deepsurfaceQuality = 0`
+/// (`mov edx, 0`) in [`TESS_DEEPSURF_CALL`].
+pub fn tess_low_code() -> Vec<u8> {
+ let mut code = TESS_DEEPSURF_CALL.bytes.to_vec();
+ code[0..6].copy_from_slice(&[0xb9, 0x00, 0x00, 0x00, 0x00, 0x90]);
+ code[6..12].copy_from_slice(&[0xba, 0x00, 0x00, 0x00, 0x00, 0x90]);
+ code
+}
+
+#[cfg(windows)]
+fn record_status(env_name: &str, result: Patched) {
+ let status = match result {
+ Patched::Done => "Done",
+ Patched::Differs | Patched::Withheld => "Differs",
+ Patched::Failed(_) => "Failed",
+ };
+ // SAFETY: called single-threaded at startup before title execution.
+ unsafe {
+ std::env::set_var(env_name, status);
+ }
+}
+
+/// Applies all asked RAGE 9 engine-level settings patches transactionally,
+/// logging each result and publishing `VICTORY_ENGINE_STATUS_*` for the F1 UI.
+///
+/// # Safety
+/// The image of `size` bytes at `base` stays mapped and no thread runs its
+/// code yet.
+#[cfg(windows)]
+pub unsafe fn apply_asked(base: usize, size: usize) {
+ if let Some(preset) = asked_low_shadows() {
+ let changes = [Change {
+ site: &SHADOW_RES,
+ code: shadow_res_code(preset),
+ }];
+ // SAFETY: the caller's promise.
+ let done = unsafe { crate::patch::apply_set(base, size, &changes) };
+ record_status("VICTORY_ENGINE_STATUS_LOW_SHADOWS", done);
+ let offset = format!("{:#x}", SHADOW_RES.at);
+ match done {
+ Patched::Done => tracing::info!(site = %offset, preset = preset.label(), "engine: low shadows patched"),
+ Patched::Differs | Patched::Withheld => tracing::warn!(site = %offset, "engine: low shadows not patched (bytes differ; another build?)"),
+ Patched::Failed(why) => tracing::warn!(site = %offset, why, "engine: low shadows not patched"),
+ }
+ println!("engine {} ({}) at title+{offset}: {done:?}", SHADOW_RES.what, preset.label());
+ }
+
+ if asked_low_volumetric() {
+ let changes = [Change {
+ site: &VOLUMETRIC_RES,
+ code: low_volumetric_code(),
+ }];
+ // SAFETY: the caller's promise.
+ let done = unsafe { crate::patch::apply_set(base, size, &changes) };
+ record_status("VICTORY_ENGINE_STATUS_LOW_VOLUMETRIC", done);
+ let offset = format!("{:#x}", VOLUMETRIC_RES.at);
+ match done {
+ Patched::Done => tracing::info!(site = %offset, "engine: low volumetric patched (128px / 7 mips)"),
+ Patched::Differs | Patched::Withheld => tracing::warn!(site = %offset, "engine: low volumetric not patched (bytes differ; another build?)"),
+ Patched::Failed(why) => tracing::warn!(site = %offset, why, "engine: low volumetric not patched"),
+ }
+ println!("engine {} (128px / 7 mips) at title+{offset}: {done:?}", VOLUMETRIC_RES.what);
+ }
+
+ if let Some(scale) = asked_lod_scale() {
+ let changes = [Change {
+ site: &LOD_SCALE,
+ code: lod_scale_code(scale),
+ }];
+ // SAFETY: the caller's promise.
+ let done = unsafe { crate::patch::apply_set(base, size, &changes) };
+ record_status("VICTORY_ENGINE_STATUS_LOD_SCALE", done);
+ let offset = format!("{:#x}", LOD_SCALE.at);
+ let dist_m = scale.clamp(0.0, 1.0) * 950.0 + 50.0;
+ match done {
+ Patched::Done => tracing::info!(site = %offset, scale, dist_m, "engine: world LOD scale patched"),
+ Patched::Differs | Patched::Withheld => tracing::warn!(site = %offset, "engine: LOD scale not patched (bytes differ; another build?)"),
+ Patched::Failed(why) => tracing::warn!(site = %offset, why, "engine: LOD scale not patched"),
+ }
+ println!("engine {} ({scale:.2} -> {dist_m:.0}m) at title+{offset}: {done:?}", LOD_SCALE.what);
+ }
+
+ if let Some(threshold) = asked_small_cull() {
+ let changes = [Change {
+ site: &SMALL_CULL,
+ code: small_cull_code(threshold),
+ }];
+ // SAFETY: the caller's promise.
+ let done = unsafe { crate::patch::apply_set(base, size, &changes) };
+ record_status("VICTORY_ENGINE_STATUS_SMALL_CULL", done);
+ let offset = format!("{:#x}", SMALL_CULL.at);
+ match done {
+ Patched::Done => tracing::info!(site = %offset, threshold, "engine: small-object cull threshold patched"),
+ Patched::Differs | Patched::Withheld => tracing::warn!(site = %offset, "engine: small-object cull not patched (bytes differ; another build?)"),
+ Patched::Failed(why) => tracing::warn!(site = %offset, why, "engine: small-object cull not patched"),
+ }
+ println!("engine {} ({threshold:.2}) at title+{offset}: {done:?}", SMALL_CULL.what);
+ }
+
+ if let Some(bias) = asked_vehicle_lod_bias() {
+ let changes = [Change {
+ site: &VEHICLE_LOD_BIAS,
+ code: vehicle_lod_bias_code(bias),
+ }];
+ // SAFETY: the caller's promise.
+ let done = unsafe { crate::patch::apply_set(base, size, &changes) };
+ record_status("VICTORY_ENGINE_STATUS_VEHICLE_LOD_BIAS", done);
+ let offset = format!("{:#x}", VEHICLE_LOD_BIAS.at);
+ match done {
+ Patched::Done => tracing::info!(site = %offset, bias, "engine: vehicle LOD bias patched"),
+ Patched::Differs | Patched::Withheld => tracing::warn!(site = %offset, "engine: vehicle LOD bias not patched (bytes differ; another build?)"),
+ Patched::Failed(why) => tracing::warn!(site = %offset, why, "engine: vehicle LOD bias not patched"),
+ }
+ println!("engine {} ({bias:.2}) at title+{offset}: {done:?}", VEHICLE_LOD_BIAS.what);
+ }
+
+ if let Some(tier) = asked_volumetric_quality() {
+ let changes = [
+ Change {
+ site: &VOL_RAYMARCH_CALL,
+ code: replace_ecx_imm(&VOL_RAYMARCH_CALL, tier),
+ },
+ Change {
+ site: &VOL_LIGHT_CALL,
+ code: replace_ecx_imm(&VOL_LIGHT_CALL, tier),
+ },
+ ];
+ // SAFETY: the caller's promise.
+ let done = unsafe { crate::patch::apply_set(base, size, &changes) };
+ record_status("VICTORY_ENGINE_STATUS_VOLUMETRIC_QUALITY", done);
+ println!("engine volumetrics raymarch+lighting tier ({tier}) at title+{:#x}: {done:?}", VOL_RAYMARCH_CALL.at);
+ }
+
+ if asked_disable_tree_tess() {
+ let changes = [Change {
+ site: &TREE_TESS_CALL,
+ code: disable_tree_tess_code(),
+ }];
+ // SAFETY: the caller's promise.
+ let done = unsafe { crate::patch::apply_set(base, size, &changes) };
+ record_status("VICTORY_ENGINE_STATUS_TREE_TESS", done);
+ println!("engine {} (off) at title+{:#x}: {done:?}", TREE_TESS_CALL.what, TREE_TESS_CALL.at);
+ }
+
+ if let Some(tier) = asked_tree_quality() {
+ let changes = [
+ Change {
+ site: &TREE_QUAL_1_CALL,
+ code: replace_ecx_imm(&TREE_QUAL_1_CALL, tier),
+ },
+ Change {
+ site: &TREE_QUAL_2_CALL,
+ code: replace_ecx_imm(&TREE_QUAL_2_CALL, tier),
+ },
+ ];
+ // SAFETY: the caller's promise.
+ let done = unsafe { crate::patch::apply_set(base, size, &changes) };
+ record_status("VICTORY_ENGINE_STATUS_TREE_QUALITY", done);
+ println!("engine tree quality tier ({tier}) at title+{:#x}: {done:?}", TREE_QUAL_1_CALL.at);
+ }
+
+ if asked_disable_grass_shadows() {
+ let changes = [Change {
+ site: &SHADOW_GRASS_CALL,
+ code: replace_ecx_imm(&SHADOW_GRASS_CALL, 0),
+ }];
+ // SAFETY: the caller's promise.
+ let done = unsafe { crate::patch::apply_set(base, size, &changes) };
+ record_status("VICTORY_ENGINE_STATUS_GRASS_SHADOWS", done);
+ println!("engine {} (low/off) at title+{:#x}: {done:?}", SHADOW_GRASS_CALL.what, SHADOW_GRASS_CALL.at);
+ }
+
+ if asked_disable_shadow_extras() {
+ let changes = [Change {
+ site: &SHADOW_ALPHA_PARTICLE,
+ code: disable_shadow_extras_code(),
+ }];
+ // SAFETY: the caller's promise.
+ let done = unsafe { crate::patch::apply_set(base, size, &changes) };
+ record_status("VICTORY_ENGINE_STATUS_SHADOW_EXTRAS", done);
+ println!("engine {} (off) at title+{:#x}: {done:?}", SHADOW_ALPHA_PARTICLE.what, SHADOW_ALPHA_PARTICLE.at);
+ }
+
+ if asked_tess_low() {
+ let changes = [Change {
+ site: &TESS_DEEPSURF_CALL,
+ code: tess_low_code(),
+ }];
+ // SAFETY: the caller's promise.
+ let done = unsafe { crate::patch::apply_set(base, size, &changes) };
+ record_status("VICTORY_ENGINE_STATUS_TESS_LOW", done);
+ println!("engine {} (low) at title+{:#x}: {done:?}", TESS_DEEPSURF_CALL.what, TESS_DEEPSURF_CALL.at);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn rip_target(site: &Site, disp_end: usize) -> usize {
+ let disp = i32::from_le_bytes(site.bytes[disp_end - 4..disp_end].try_into().unwrap());
+ ((site.at + disp_end) as i64 + i64::from(disp)) as usize
+ }
+
+ #[test]
+ fn parse_shadow_presets() {
+ assert_eq!(ShadowPreset::parse("0"), None);
+ assert_eq!(ShadowPreset::parse("off"), None);
+ assert_eq!(ShadowPreset::parse("1"), Some(ShadowPreset::Low1280));
+ assert_eq!(ShadowPreset::parse("1280"), Some(ShadowPreset::Low1280));
+ assert_eq!(ShadowPreset::parse("2"), Some(ShadowPreset::UltraLow1024));
+ assert_eq!(ShadowPreset::parse("1024"), Some(ShadowPreset::UltraLow1024));
+ assert_eq!(ShadowPreset::parse("1536"), Some(ShadowPreset::Med1536));
+ assert_eq!(ShadowPreset::parse("2048"), Some(ShadowPreset::High2048));
+ assert_eq!(ShadowPreset::parse("bogus"), None);
+ }
+
+ #[test]
+ fn shadow_site_geometry_and_replacements() {
+ assert_eq!(SHADOW_RES.bytes.len(), 35);
+ // `ja +0x0d` at 15..17 lands at byte 30 (`mov rdi, [rsp+60h]`).
+ assert_eq!(SHADOW_RES.bytes[15], 0x77);
+ assert_eq!(17 + usize::from(SHADOW_RES.bytes[16]), 30);
+ // `lea r10, [rip+disp]` at 19..26 points to SHADOW_TABLE_RVA.
+ assert_eq!(&SHADOW_RES.bytes[19..22], &[0x4c, 0x8d, 0x15]);
+ assert_eq!(rip_target(&SHADOW_RES, 26), SHADOW_TABLE_RVA);
+ assert_eq!(&SHADOW_RES.bytes[30..35], &[0x48, 0x8b, 0x7c, 0x24, 0x60]);
+
+ let low = shadow_res_code(ShadowPreset::Low1280);
+ assert_eq!(low.len(), SHADOW_RES.bytes.len());
+ assert_eq!(&low[..12], &SHADOW_RES.bytes[..12]);
+ assert_eq!(&low[12..19], &[0xba, 0x01, 0x00, 0x00, 0x00, 0x89, 0xd0]);
+ assert_eq!(&low[19..], &SHADOW_RES.bytes[19..]);
+
+ let ultra = shadow_res_code(ShadowPreset::UltraLow1024);
+ assert_eq!(ultra.len(), SHADOW_RES.bytes.len());
+ assert_eq!(ultra[17], 0xeb);
+ assert_eq!(19 + usize::from(ultra[18]), 30, "short jmp lands on mov rdi, [rsp+60h]");
+ assert_eq!(&ultra[19..], &SHADOW_RES.bytes[19..]);
+ }
+
+ #[test]
+ fn volumetric_site_geometry_and_replacement() {
+ assert_eq!(VOLUMETRIC_RES.bytes.len(), 46);
+ // `mov byte [rip+disp], 1` ends at byte 16, disp is 11..15, next rip is 16.
+ let dirty_disp = i32::from_le_bytes(VOLUMETRIC_RES.bytes[11..15].try_into().unwrap());
+ assert_eq!((VOLUMETRIC_RES.at + 16) as i64 + i64::from(dirty_disp), VOLUMETRIC_DIRTY_RVA as i64);
+ assert_eq!(&VOLUMETRIC_RES.bytes[16..19], &[0x0f, 0x9f, 0xc0]);
+ assert_eq!(rip_target(&VOLUMETRIC_RES, 30), VOLUMETRIC_TIER_RVA);
+ assert_eq!(rip_target(&VOLUMETRIC_RES, 39), VOLUMETRIC_RES_RVA);
+ assert_eq!(rip_target(&VOLUMETRIC_RES, 45), VOLUMETRIC_MIPS_RVA);
+ assert_eq!(VOLUMETRIC_RES.bytes[45], 0xc3);
+
+ let patched = low_volumetric_code();
+ assert_eq!(patched.len(), VOLUMETRIC_RES.bytes.len());
+ assert_eq!(&patched[..16], &VOLUMETRIC_RES.bytes[..16]);
+ assert_eq!(&patched[16..19], &[0x90, 0x90, 0x90]);
+ assert_eq!(&patched[19..], &VOLUMETRIC_RES.bytes[19..]);
+ }
+
+ #[test]
+ fn stage14_lod_small_cull_and_vehicle_lod_sites() {
+ assert_eq!(parse_lod_scale("0"), None);
+ assert_eq!(parse_lod_scale("low"), Some(0.25));
+ assert_eq!(parse_lod_scale("0.35"), Some(0.35));
+ assert_eq!(parse_small_cull("stock"), None);
+ assert_eq!(parse_small_cull("high"), Some(3.0));
+ assert_eq!(parse_small_cull("2.5"), Some(2.5));
+ assert_eq!(parse_vehicle_lod_bias("0"), None);
+ assert_eq!(parse_vehicle_lod_bias("0.5"), Some(0.5));
+
+ assert_eq!(LOD_SCALE.bytes.len(), 16);
+ assert_eq!(rip_target(&LOD_SCALE, 16), LOD_SCALE_GLOBAL_RVA);
+ let lod = lod_scale_code(0.35);
+ assert_eq!(lod.len(), 16);
+ assert_eq!(lod[0], 0xb8);
+ assert_eq!(f32::from_bits(u32::from_le_bytes(lod[1..5].try_into().unwrap())), 0.35);
+ let lod_disp = i32::from_le_bytes(lod[7..11].try_into().unwrap());
+ assert_eq!((LOD_SCALE.at + 11) as i64 + i64::from(lod_disp), LOD_SCALE_GLOBAL_RVA as i64);
+
+ assert_eq!(SMALL_CULL.bytes.len(), 16);
+ assert_eq!(rip_target(&SMALL_CULL, 16), SMALL_CULL_GLOBAL_RVA);
+ let sc = small_cull_code(2.5);
+ assert_eq!(sc.len(), 16);
+ let sc_disp = i32::from_le_bytes(sc[2..6].try_into().unwrap());
+ assert_eq!((SMALL_CULL.at + 10) as i64 + i64::from(sc_disp), SMALL_CULL_GLOBAL_RVA as i64);
+ assert_eq!(f32::from_bits(u32::from_le_bytes(sc[6..10].try_into().unwrap())), 2.5);
+
+ assert_eq!(VEHICLE_LOD_BIAS.bytes.len(), 13);
+ assert_eq!(rip_target(&VEHICLE_LOD_BIAS, 13), VEHICLE_LOD_BIAS_SETTER_RVA);
+ let vb = vehicle_lod_bias_code(0.5);
+ assert_eq!(vb.len(), 13);
+ let vb_disp = i32::from_le_bytes(vb[2..6].try_into().unwrap());
+ assert_eq!((VEHICLE_LOD_BIAS.at + 10) as i64 + i64::from(vb_disp), VEHICLE_LOD_BIAS_GLOBAL_RVA as i64);
+ assert_eq!(f32::from_bits(u32::from_le_bytes(vb[6..10].try_into().unwrap())), 0.5);
+ }
+
+ /// Optional golden check against a real title PE when `VICTORY_TITLE_EXE`
+ /// is set in the environment: confirms both sites match byte-for-byte.
+ #[test]
+ fn golden_title_exe_bytes_if_present() {
+ let Ok(path) = std::env::var("VICTORY_TITLE_EXE") else {
+ return;
+ };
+ let pe = std::fs::read(&path).expect("read VICTORY_TITLE_EXE");
+ let pe_off = u32::from_le_bytes(pe[0x3c..0x40].try_into().unwrap()) as usize;
+ let num_sec = u16::from_le_bytes(pe[pe_off + 6..pe_off + 8].try_into().unwrap()) as usize;
+ let opt_size = u16::from_le_bytes(pe[pe_off + 20..pe_off + 22].try_into().unwrap()) as usize;
+ let sec_base = pe_off + 24 + opt_size;
+ let rva_to_off = |rva: usize| -> usize {
+ for i in 0..num_sec {
+ let s = sec_base + i * 40;
+ let vs = u32::from_le_bytes(pe[s + 8..s + 12].try_into().unwrap()) as usize;
+ let va = u32::from_le_bytes(pe[s + 12..s + 16].try_into().unwrap()) as usize;
+ let raw = u32::from_le_bytes(pe[s + 20..s + 24].try_into().unwrap()) as usize;
+ if rva >= va && rva < va + vs {
+ return raw + (rva - va);
+ }
+ }
+ panic!("RVA {rva:#x} not found in PE sections");
+ };
+
+ for site in [
+ &SHADOW_RES,
+ &VOLUMETRIC_RES,
+ &LOD_SCALE,
+ &SMALL_CULL,
+ &VEHICLE_LOD_BIAS,
+ &VOL_RAYMARCH_CALL,
+ &VOL_LIGHT_CALL,
+ &TREE_TESS_CALL,
+ &SHADOW_GRASS_CALL,
+ &TREE_QUAL_1_CALL,
+ &TREE_QUAL_2_CALL,
+ &SHADOW_ALPHA_PARTICLE,
+ &TESS_DEEPSURF_CALL,
+ ] {
+ let off = rva_to_off(site.at);
+ assert_eq!(
+ &pe[off..off + site.bytes.len()],
+ site.bytes,
+ "site {} at {:#x} mismatched real PE",
+ site.what,
+ site.at
+ );
+ }
+ let tbl_off = rva_to_off(SHADOW_TABLE_RVA);
+ let tiers: [u32; 4] = [
+ u32::from_le_bytes(pe[tbl_off..tbl_off + 4].try_into().unwrap()),
+ u32::from_le_bytes(pe[tbl_off + 4..tbl_off + 8].try_into().unwrap()),
+ u32::from_le_bytes(pe[tbl_off + 8..tbl_off + 12].try_into().unwrap()),
+ u32::from_le_bytes(pe[tbl_off + 12..tbl_off + 16].try_into().unwrap()),
+ ];
+ assert_eq!(tiers, [1536, 1280, 2048, 4096]);
+ }
+}
diff --git a/crates/victory-loader/src/lib.rs b/crates/victory-loader/src/lib.rs
index 1f301af..42ce2c5 100644
--- a/crates/victory-loader/src/lib.rs
+++ b/crates/victory-loader/src/lib.rs
@@ -31,7 +31,9 @@ mod crash;
pub mod descriptor_sites;
#[cfg(windows)]
pub mod heap_sites;
+pub mod engine;
pub mod frame_rate;
+pub mod patch;
pub mod prepare;
#[cfg(any(windows, test))]
pub(crate) mod publish;
diff --git a/crates/victory-loader/src/patch.rs b/crates/victory-loader/src/patch.rs
new file mode 100644
index 0000000..f147e03
--- /dev/null
+++ b/crates/victory-loader/src/patch.rs
@@ -0,0 +1,155 @@
+//! Shared byte-verified, transactional code-patching core for title images.
+//!
+//! Every patch site records its exact image RVA and the full expected bytes
+//! from the verified build. `apply_set` checks every site in a dependent
+//! group *before* writing any of them so a partial build mismatch never
+//! leaves a half-patched image (for example patching output size without
+//! also patching the back-buffer pool check).
+
+pub use crate::frame_rate::Patched;
+
+/// One place in the title's image to compare and optionally patch: its image
+/// offset (RVA), a human label, and the full bytes expected there before
+/// patching. Any replacement must be at most `bytes.len()` long.
+pub struct Site {
+ pub at: usize,
+ pub what: &'static str,
+ pub bytes: &'static [u8],
+}
+
+/// One concrete replacement bound to a verified [`Site`].
+pub struct Change {
+ pub site: &'static Site,
+ pub code: Vec<u8>,
+}
+
+/// Compares `site`'s bytes in the image of `size` bytes at `base`.
+///
+/// # Safety
+/// The image of `size` bytes at `base` is mapped and readable.
+pub unsafe fn matches(base: usize, size: usize, site: &Site) -> Patched {
+ if site.at.checked_add(site.bytes.len()).is_none_or(|end| end > size) {
+ return Patched::Failed("outside the image");
+ }
+ // SAFETY: inside the mapped image (checked above).
+ let there = unsafe { std::slice::from_raw_parts((base + site.at) as *const u8, site.bytes.len()) };
+ if there == site.bytes { Patched::Done } else { Patched::Differs }
+}
+
+/// Writes `code` over `site` if its bytes are the expected ones.
+///
+/// # Safety
+/// The image stays mapped and no thread runs its code yet.
+#[cfg(windows)]
+pub unsafe fn write(base: usize, size: usize, site: &Site, code: &[u8]) -> Patched {
+ if code.len() > site.bytes.len() {
+ return Patched::Failed("replacement longer than the bytes compared");
+ }
+ // SAFETY: the caller's promise.
+ let found = unsafe { matches(base, size, site) };
+ if found != Patched::Done {
+ return found;
+ }
+ // SAFETY: verified bounds and no executing title threads yet.
+ unsafe { write_checked(base, site, code) }
+}
+
+/// Writes `code` over an already-verified `site`.
+///
+/// # Safety
+/// `site` has already passed [`matches`] and `code.len() <= site.bytes.len()`,
+/// and no thread is executing title code yet.
+#[cfg(windows)]
+unsafe fn write_checked(base: usize, site: &Site, code: &[u8]) -> Patched {
+ use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache;
+ use windows_sys::Win32::System::Memory::{PAGE_EXECUTE_READWRITE, VirtualProtect};
+ use windows_sys::Win32::System::Threading::GetCurrentProcess;
+
+ let at = base + site.at;
+ let mut old = 0;
+ // SAFETY: inside the mapped image (verified); made writable only for the
+ // copy and restored immediately, followed by icache flush.
+ unsafe {
+ if VirtualProtect(at as *const _, code.len(), PAGE_EXECUTE_READWRITE, &mut old) == 0 {
+ return Patched::Failed("Windows would not make it writable");
+ }
+ std::ptr::copy_nonoverlapping(code.as_ptr(), at as *mut u8, code.len());
+ VirtualProtect(at as *const _, code.len(), old, &mut old);
+ FlushInstructionCache(GetCurrentProcess(), at as *const _, code.len());
+ }
+ Patched::Done
+}
+
+/// Applies a group of dependent [`Change`]s transactionally: every site's
+/// length and original bytes are verified before *any* site is written.
+///
+/// Returns `Patched::Done` only if every site matched and wrote cleanly;
+/// otherwise returns the first failure (`Differs` or `Failed`) and leaves
+/// earlier sites untouched if the check phase failed.
+///
+/// # Safety
+/// The image of `size` bytes at `base` stays mapped and no thread runs its
+/// code yet.
+#[cfg(windows)]
+pub unsafe fn apply_set(base: usize, size: usize, changes: &[Change]) -> Patched {
+ for change in changes {
+ if change.code.len() > change.site.bytes.len() {
+ return Patched::Failed("replacement longer than the bytes compared");
+ }
+ // SAFETY: the caller's promise.
+ let found = unsafe { matches(base, size, change.site) };
+ if found != Patched::Done {
+ return found;
+ }
+ }
+ for change in changes {
+ // SAFETY: every site in `changes` passed `matches` above.
+ let done = unsafe { write_checked(base, change.site, &change.code) };
+ if done != Patched::Done {
+ return done;
+ }
+ }
+ Patched::Done
+}
+
+#[cfg(all(test, windows))]
+mod tests {
+ use super::*;
+ use windows_sys::Win32::System::Memory::{
+ MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READ, VirtualAlloc, VirtualFree, VirtualProtect,
+ };
+
+ #[test]
+ fn apply_set_is_all_or_nothing_on_mismatch() {
+ static S1: Site = Site { at: 0x100, what: "first", bytes: &[0x90, 0x90, 0x90, 0x90] };
+ static S2: Site = Site { at: 0x200, what: "second", bytes: &[0x48, 0x89, 0xc0, 0xc3] };
+ // SAFETY: fresh private allocation freed at end of test.
+ unsafe {
+ let mem = VirtualAlloc(std::ptr::null(), 0x1000, MEM_COMMIT | MEM_RESERVE, 0x40) as *mut u8;
+ assert!(!mem.is_null());
+ std::ptr::copy_nonoverlapping(S1.bytes.as_ptr(), mem.add(S1.at), S1.bytes.len());
+ // S2 intentionally has one differing byte.
+ std::ptr::copy_nonoverlapping([0x48u8, 0x89, 0xc1, 0xc3].as_ptr(), mem.add(S2.at), 4);
+ let mut old = 0;
+ VirtualProtect(mem.cast(), 0x1000, PAGE_EXECUTE_READ, &mut old);
+
+ let changes = [
+ Change { site: &S1, code: vec![0xcc, 0xcc, 0xcc, 0xcc] },
+ Change { site: &S2, code: vec![0x90, 0x90, 0x90, 0xc3] },
+ ];
+ assert_eq!(apply_set(mem as usize, 0x1000, &changes), Patched::Differs);
+ // S1 must NOT have been written because S2 differed!
+ assert_eq!(std::slice::from_raw_parts(mem.add(S1.at), 4), S1.bytes);
+
+ // Now fix S2 and retry: both must write atomically.
+ VirtualProtect(mem.cast(), 0x1000, 0x40, &mut old);
+ std::ptr::copy_nonoverlapping(S2.bytes.as_ptr(), mem.add(S2.at), S2.bytes.len());
+ VirtualProtect(mem.cast(), 0x1000, PAGE_EXECUTE_READ, &mut old);
+ assert_eq!(apply_set(mem as usize, 0x1000, &changes), Patched::Done);
+ assert_eq!(std::slice::from_raw_parts(mem.add(S1.at), 4), &[0xcc, 0xcc, 0xcc, 0xcc]);
+ assert_eq!(std::slice::from_raw_parts(mem.add(S2.at), 4), &[0x90, 0x90, 0x90, 0xc3]);
+
+ VirtualFree(mem.cast(), 0, MEM_RELEASE);
+ }
+ }
+}
diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs
index 4b61449..73485a7 100644
--- a/crates/victory-shader/src/emit/bitcode.rs
+++ b/crates/victory-shader/src/emit/bitcode.rs
@@ -5,7 +5,9 @@
//! it is written: functions, then constants (all at module level), then the
//! instructions of `main` in block order.
-use std::collections::{BTreeMap, HashMap};
+use std::collections::BTreeMap;
+
+use crate::structure::FxMap;
pub mod census;
pub mod opt;
@@ -148,6 +150,11 @@ pub(crate) mod pred {
#[derive(Debug, Clone)]
enum Op {
Bin(Bin, V, V),
+ /// Float division with LLVM `arcp` (`ALLOW_RECIPROCAL`, fast-math bit 4),
+ /// letting the host driver lower `1.0 / x` to its single-instruction
+ /// hardware reciprocal (e.g. `MUFU.RCP` on NVIDIA) matching RDNA2
+ /// `v_rcp_f32`/`v_rcp_f16` (1 ULP).
+ FDivArcp(V, V),
Cast(Cast, V),
Cmp(u8, V, V),
Select(V, V, V),
@@ -214,23 +221,42 @@ enum MdDef {
Node(Vec<Option<Md>>),
}
+struct SmallI32([Option<V>; 65]);
+
+impl Default for SmallI32 {
+ fn default() -> Self {
+ Self([None; 65])
+ }
+}
+
#[derive(Default)]
pub(crate) struct Module {
types: Vec<TypeDef>,
- type_ids: HashMap<TypeDef, u32>,
+ type_ids: FxMap<TypeDef, u32>,
consts: Vec<(Ty, Const)>,
- const_ids: HashMap<(Ty, Const), u32>,
+ const_ids: FxMap<(Ty, Const), u32>,
globals: Vec<Global>,
funcs: Vec<Func>,
- func_ids: HashMap<String, u32>,
+ func_ids: FxMap<String, u32>,
+ /// Fast lookup of `dx.op.<name>` by bare `<name>` without `format!`.
+ dx_op_ids: FxMap<String, V>,
insts: Vec<Inst>,
blocks: Vec<Block>,
mds: Vec<MdDef>,
named: Vec<(String, Vec<Md>)>,
/// See [`Tag`]: by instruction.
- tags: HashMap<u32, Tag>,
+ tags: FxMap<u32, Tag>,
/// A block that was closed by a meet: later instructions aimed at it belong in the continuation.
- redirect: HashMap<usize, usize>,
+ redirect: FxMap<usize, usize>,
+ // Cached common scalar types and small constants to bypass hash lookups.
+ ty_void: Option<Ty>,
+ ty_i1: Option<Ty>,
+ ty_i8: Option<Ty>,
+ ty_i32: Option<Ty>,
+ ty_f32: Option<Ty>,
+ ty_f64: Option<Ty>,
+ const_bool: [Option<V>; 2],
+ const_i32: SmallI32,
}
impl Module {
@@ -281,16 +307,57 @@ impl Module {
}
pub fn void(&mut self) -> Ty {
- self.ty(TypeDef::Void)
+ if let Some(t) = self.ty_void {
+ return t;
+ }
+ let t = self.ty(TypeDef::Void);
+ self.ty_void = Some(t);
+ t
}
pub fn int(&mut self, bits: u32) -> Ty {
- self.ty(TypeDef::Int(bits))
+ match bits {
+ 1 => {
+ if let Some(t) = self.ty_i1 {
+ return t;
+ }
+ let t = self.ty(TypeDef::Int(1));
+ self.ty_i1 = Some(t);
+ t
+ }
+ 8 => {
+ if let Some(t) = self.ty_i8 {
+ return t;
+ }
+ let t = self.ty(TypeDef::Int(8));
+ self.ty_i8 = Some(t);
+ t
+ }
+ 32 => {
+ if let Some(t) = self.ty_i32 {
+ return t;
+ }
+ let t = self.ty(TypeDef::Int(32));
+ self.ty_i32 = Some(t);
+ t
+ }
+ _ => self.ty(TypeDef::Int(bits)),
+ }
}
pub fn float(&mut self) -> Ty {
- self.ty(TypeDef::Float)
+ if let Some(t) = self.ty_f32 {
+ return t;
+ }
+ let t = self.ty(TypeDef::Float);
+ self.ty_f32 = Some(t);
+ t
}
pub fn double(&mut self) -> Ty {
- self.ty(TypeDef::Double)
+ if let Some(t) = self.ty_f64 {
+ return t;
+ }
+ let t = self.ty(TypeDef::Double);
+ self.ty_f64 = Some(t);
+ t
}
pub fn ptr(&mut self, to: Ty) -> Ty {
self.ty(TypeDef::Ptr(to, 0))
@@ -326,16 +393,29 @@ impl Module {
self.constant(ty, Const::Int(v))
}
pub fn i32(&mut self, v: u32) -> V {
+ if let Some(slot) = self.const_i32.0.get(v as usize).and_then(|&c| c) {
+ return slot;
+ }
let t = self.int(32);
- self.int_const(t, i64::from(v as i32))
+ let c = self.int_const(t, i64::from(v as i32));
+ if (v as usize) < self.const_i32.0.len() {
+ self.const_i32.0[v as usize] = Some(c);
+ }
+ c
}
pub fn i8(&mut self, v: u8) -> V {
let t = self.int(8);
self.int_const(t, i64::from(v as i8))
}
pub fn bool(&mut self, v: bool) -> V {
+ let idx = usize::from(v);
+ if let Some(c) = self.const_bool[idx] {
+ return c;
+ }
let t = self.int(1);
- self.int_const(t, -i64::from(v))
+ let c = self.int_const(t, -i64::from(v));
+ self.const_bool[idx] = Some(c);
+ c
}
pub fn f32(&mut self, bits: u32) -> V {
let t = self.float();
@@ -433,6 +513,23 @@ impl Module {
}
}
+ /// A `dx.op.<name>` declaration, looked up by bare `name` without allocating
+ /// a `String` or parameter `Vec` on cache hit.
+ pub fn dx_op(&mut self, name: &str, ret: Ty, attr: Attr, opcode_ty: Ty, args: &[V]) -> V {
+ if let Some(&f) = self.dx_op_ids.get(name) {
+ return f;
+ }
+ let mut params = Vec::with_capacity(1 + args.len());
+ params.push(opcode_ty);
+ params.extend(args.iter().map(|&a| self.type_of(a)));
+ let fty = self.func_ty(ret, params);
+ self.ptr(fty);
+ let full = format!("dx.op.{name}");
+ let f = self.function(&full, fty, Some(attr), false);
+ self.dx_op_ids.insert(name.into(), f);
+ f
+ }
+
/// A function declaration (or `main` with `body`), found by name.
pub fn function(&mut self, name: &str, ty: Ty, attr: Option<Attr>, body: bool) -> V {
if let Some(&i) = self.func_ids.get(name) {
@@ -536,6 +633,11 @@ impl Module {
let ty = self.type_of(a);
self.push(block, ty, Op::Bin(op, a, b))
}
+ /// Float division with LLVM `arcp` (`ALLOW_RECIPROCAL`) fast-math flag.
+ pub fn fdiv_arcp(&mut self, block: usize, a: V, b: V) -> V {
+ let ty = self.type_of(a);
+ self.push(block, ty, Op::FDivArcp(a, b))
+ }
pub fn cast(&mut self, block: usize, op: Cast, v: V, to: Ty) -> V {
self.push(block, to, Op::Cast(op, v))
}
@@ -1129,6 +1231,8 @@ impl Module {
};
match &inst.op {
Op::Bin(op, a, b) => w.record(2, &[rel(*a), rel(*b), *op as u64]),
+ // LLVM 3.7 FastMathMap: bit 4 (0x10) = AllowReciprocal (`arcp`).
+ Op::FDivArcp(a, b) => w.record(2, &[rel(*a), rel(*b), Bin::SDiv as u64, 1 << 4]),
Op::Cast(op, v) => w.record(3, &[rel(*v), u64::from(inst.ty.0), *op as u64]),
Op::Cmp(p, a, b) => w.record(28, &[rel(*a), rel(*b), u64::from(*p)]),
Op::Select(c, t, f) => w.record(29, &[rel(*t), rel(*f), rel(*c)]),
@@ -1200,7 +1304,11 @@ const TYPE_BLOCK: u64 = 17;
/// Calls `f` with every value `op` reads, in operand order.
fn for_each_operand(op: &Op, mut f: impl FnMut(V)) {
match op {
- Op::Bin(_, a, b) | Op::Cmp(_, a, b) | Op::Store(a, b) | Op::AtomicRmw(_, a, b) => {
+ Op::Bin(_, a, b)
+ | Op::FDivArcp(a, b)
+ | Op::Cmp(_, a, b)
+ | Op::Store(a, b)
+ | Op::AtomicRmw(_, a, b) => {
f(*a);
f(*b);
}
diff --git a/crates/victory-shader/src/emit/bitcode/census.rs b/crates/victory-shader/src/emit/bitcode/census.rs
index f336c5d..c52aa63 100644
--- a/crates/victory-shader/src/emit/bitcode/census.rs
+++ b/crates/victory-shader/src/emit/bitcode/census.rs
@@ -208,7 +208,7 @@ impl Module {
{
c.counts[0] += 1;
let at = match &self.insts[i as usize].op {
- Op::Bin(..) | Op::Cmp(..) => k("arith"),
+ Op::Bin(..) | Op::FDivArcp(..) | Op::Cmp(..) => k("arith"),
Op::Cast(Cast::Bitcast, _) => k("bitcast"),
Op::Cast(..) => k("cast"),
Op::Select(..) => k("select"),
diff --git a/crates/victory-shader/src/emit/bitcode/opt.rs b/crates/victory-shader/src/emit/bitcode/opt.rs
index 048bb30..f928938 100644
--- a/crates/victory-shader/src/emit/bitcode/opt.rs
+++ b/crates/victory-shader/src/emit/bitcode/opt.rs
@@ -43,7 +43,7 @@
//! Which passes run is `emit::shader_opt()` (`VICTORY_SHADER_OPT`), part of
//! the translation and so of the shader cache's key.
-use std::collections::HashMap;
+use crate::structure::FxMap as HashMap;
use super::{
Attr, Bin, Cast, Const, Func, MdDef, Module, Op, Term, Ty, TypeDef, V, for_each_operand, pred,
@@ -393,7 +393,11 @@ fn resolve(repl: &[Option<V>], mut v: V) -> V {
/// Replaces every value `op` reads by `f` of it.
fn map_operands(op: &mut Op, mut f: impl FnMut(V) -> V) {
match op {
- Op::Bin(_, a, b) | Op::Cmp(_, a, b) | Op::Store(a, b) | Op::AtomicRmw(_, a, b) => {
+ Op::Bin(_, a, b)
+ | Op::FDivArcp(a, b)
+ | Op::Cmp(_, a, b)
+ | Op::Store(a, b)
+ | Op::AtomicRmw(_, a, b) => {
*a = f(*a);
*b = f(*b);
}
@@ -1556,7 +1560,7 @@ impl Module {
/// path (or [`PtrPath::Dynamic`] for any dynamic, out-of-bounds, negative,
/// aggregate, or non-canonical pointer).
fn trace_ptr(&self, mut v: V, escaped: &[bool]) -> (PtrRoot, PtrPath) {
- let mut hops: Vec<(Ty, Ty, Vec<V>)> = Vec::new();
+ let mut hops: Vec<(Ty, Ty, &[V])> = Vec::new();
for _ in 0..=self.insts.len() {
match v {
V::Global(g) => {
@@ -1580,17 +1584,13 @@ impl Module {
if gep_ty != cur_ty || idx.is_empty() {
return (root, PtrPath::Dynamic);
}
- let mut consts = Vec::with_capacity(idx.len());
- for ix in idx {
- let Some((bits, k)) = self.int_k(ix) else {
- return (root, PtrPath::Dynamic);
- };
- if bits == 0 {
- return (root, PtrPath::Dynamic);
- }
- consts.push(signed(bits, k));
+ let Some((bits0, k0)) = self.int_k(idx[0]) else {
+ return (root, PtrPath::Dynamic);
+ };
+ if bits0 == 0 {
+ return (root, PtrPath::Dynamic);
}
- let s0 = consts[0];
+ let s0 = signed(bits0, k0);
if s0 != 0 {
let (Some(len), Some(last)) = (parent_array_len, path.last_mut())
else {
@@ -1602,7 +1602,14 @@ impl Module {
}
*last = next as u64;
}
- for &s in &consts[1..] {
+ for &ix in &idx[1..] {
+ let Some((bits, k)) = self.int_k(ix) else {
+ return (root, PtrPath::Dynamic);
+ };
+ if bits == 0 {
+ return (root, PtrPath::Dynamic);
+ }
+ let s = signed(bits, k);
if s < 0 {
return (root, PtrPath::Dynamic);
}
@@ -1637,7 +1644,7 @@ impl Module {
let Op::Gep(gep_ty, base, idx) = &inst.op else {
return (PtrRoot::Unknown, PtrPath::Dynamic);
};
- hops.push((*gep_ty, inst.ty, idx.clone()));
+ hops.push((*gep_ty, inst.ty, idx.as_slice()));
v = *base;
}
_ => return (PtrRoot::Unknown, PtrPath::Dynamic),
@@ -1707,10 +1714,158 @@ impl Module {
)
}
+ /// Whether any reached block in `order` executes a call that may write
+ /// title resource memory (UAV stores, atomics, or opaque `WriteKind::All`
+ /// calls). Excludes `dx.op.discard`, wave/quad intrinsics, and writes to
+ /// host-only telemetry UAVs (`SLOT_SAMPLED`, `SLOT_FAULTS`) which never
+ /// alias title SRVs.
+ fn has_resource_writes(&self, effects: &[Effect], order: &[usize]) -> bool {
+ for &b in order {
+ for &i in &self.blocks[b].body {
+ if let Op::Call(f, ref args) = self.insts[i as usize].op
+ && effects[f as usize] == Effect::Writes
+ {
+ match write_kind(&self.funcs[f as usize]) {
+ WriteKind::Barrier | WriteKind::OutputOnly => {}
+ WriteKind::ResourceMemory => {
+ if !args.get(1).is_some_and(|&h| self.is_host_telemetry_uav(h)) {
+ return true;
+ }
+ }
+ WriteKind::All => {
+ let name = self.funcs[f as usize]
+ .name
+ .strip_prefix("dx.op.")
+ .unwrap_or(&self.funcs[f as usize].name);
+ if name != "discard" && !name.starts_with("wave") && !name.starts_with("quad") {
+ return true;
+ }
+ }
+ }
+ }
+ }
+ }
+ false
+ }
+
+ /// If `handle` is an annotated handle to a single root binding in
+ /// `ROOT_CBV_SPACE`, returns `(resource_class, slot)`.
+ fn root_binding_slot(&self, handle: V) -> Option<(i64, u8)> {
+ let V::Inst(ann_id) = handle else {
+ return None;
+ };
+ let Op::Call(ann_f, ref ann_args) = self.insts[ann_id as usize].op else {
+ return None;
+ };
+ if self.funcs[ann_f as usize].name != "dx.op.annotateHandle" || ann_args.len() < 2 {
+ return None;
+ }
+ let V::Inst(bind_id) = ann_args[1] else {
+ return None;
+ };
+ let Op::Call(bind_f, ref bind_args) = self.insts[bind_id as usize].op else {
+ return None;
+ };
+ if self.funcs[bind_f as usize].name != "dx.op.createHandleFromBinding" || bind_args.len() < 2 {
+ return None;
+ }
+ let V::Const(agg_c) = bind_args[1] else {
+ return None;
+ };
+ let Const::Aggregate(ref fields) = self.consts[agg_c as usize].1 else {
+ return None;
+ };
+ if fields.len() != 4 {
+ return None;
+ }
+ let field_i64 = |idx: usize| match self.consts[fields[idx] as usize].1 {
+ Const::Int(x) => Some(x),
+ _ => None,
+ };
+ let (lo, hi, space, class) = (field_i64(0)?, field_i64(1)?, field_i64(2)?, field_i64(3)?);
+ (space == i64::from(super::super::shader::ROOT_CBV_SPACE) && lo == hi).then_some((class, lo as u8))
+ }
+
+ /// Whether `handle` is an annotated handle to one of the host's immutable
+ /// root SRV metadata tables (`SLOT_STRIDES`, `SLOT_TABLE_STRIDES`,
+ /// `SLOT_VIEW_ADDRESSES` in `ROOT_CBV_SPACE`), which no shader can write.
+ fn is_immutable_host_srv(&self, handle: V) -> bool {
+ matches!(
+ self.root_binding_slot(handle),
+ Some((
+ 0,
+ super::super::shader::SLOT_STRIDES
+ | super::super::shader::SLOT_TABLE_STRIDES
+ | super::super::shader::SLOT_VIEW_ADDRESSES
+ ))
+ )
+ }
+
+ /// Whether `handle` is a host-only write-only telemetry UAV (`SLOT_SAMPLED`
+ /// or `SLOT_FAULTS` in `ROOT_CBV_SPACE`), which never aliases title SRVs.
+ fn is_host_telemetry_uav(&self, handle: V) -> bool {
+ matches!(
+ self.root_binding_slot(handle),
+ Some((1, super::super::shader::SLOT_SAMPLED | super::super::shader::SLOT_FAULTS))
+ )
+ }
+
+ /// Whether `handle` is annotated as a non-UAV resource (`props0 & 0x1000 == 0`).
+ fn is_readonly_srv_handle(&self, handle: V) -> bool {
+ let V::Inst(ann_id) = handle else {
+ return false;
+ };
+ let Op::Call(ann_f, ref ann_args) = self.insts[ann_id as usize].op else {
+ return false;
+ };
+ if self.funcs[ann_f as usize].name != "dx.op.annotateHandle" || ann_args.len() < 3 {
+ return false;
+ }
+ let V::Const(props_c) = ann_args[2] else {
+ return false;
+ };
+ let Const::Aggregate(ref fields) = self.consts[props_c as usize].1 else {
+ return false;
+ };
+ let Some(&p0_id) = fields.first() else {
+ return false;
+ };
+ matches!(self.consts[p0_id as usize].1, Const::Int(p0) if (p0 as u32) & 0x1000 == 0)
+ }
+
+ /// Whether a `ReadOnly` resource load call is pure for GVN/LICM:
+ /// - `rawBufferLoad` from an immutable host metadata table (`SLOT_STRIDES`,
+ /// `SLOT_TABLE_STRIDES`, `SLOT_VIEW_ADDRESSES`) is always pure;
+ /// - any non-UAV SRV `rawBufferLoad`, `bufferLoad`, or `textureLoad` is pure
+ /// when the module contains no resource writes at all.
+ fn is_pure_srv_load(&self, f: u32, args: &[V], no_resource_writes: bool) -> bool {
+ if args.len() < 2 {
+ return false;
+ }
+ let name = self.funcs[f as usize].name.as_str();
+ let name = name.strip_prefix("dx.op.").unwrap_or(name);
+ let handle = args[1];
+ if name.starts_with("rawBufferLoad") {
+ return self.is_immutable_host_srv(handle)
+ || (no_resource_writes && self.is_readonly_srv_handle(handle));
+ }
+ if no_resource_writes
+ && (name.starts_with("bufferLoad") || name.starts_with("textureLoad"))
+ {
+ return self.is_readonly_srv_handle(handle);
+ }
+ false
+ }
+
/// What kind of instruction `i` is for merging.
fn class(&self, effects: &[Effect], i: u32) -> Effect {
+ self.class_with(effects, i, false)
+ }
+
+ fn class_with(&self, effects: &[Effect], i: u32, no_resource_writes: bool) -> Effect {
match &self.insts[i as usize].op {
Op::Bin(..)
+ | Op::FDivArcp(..)
| Op::Cast(..)
| Op::Cmp(..)
| Op::Select(..)
@@ -1737,7 +1892,14 @@ impl Module {
}
Op::Store(..) | Op::AtomicRmw(..) | Op::CmpXchg(..) => Effect::Writes,
Op::Phi(_) => Effect::Lanes,
- Op::Call(f, _) => effects[*f as usize],
+ Op::Call(f, args) => {
+ let eff = effects[*f as usize];
+ if eff == Effect::Reads && self.is_pure_srv_load(*f, args, no_resource_writes) {
+ Effect::Pure
+ } else {
+ eff
+ }
+ }
}
}
@@ -1757,6 +1919,7 @@ impl Module {
};
Key::Bin(*op as u8, a, b)
}
+ Op::FDivArcp(a, b) => Key::Bin(0x80 | Bin::SDiv as u8, *a, *b),
Op::Cast(op, v) => Key::Cast(*op as u8, inst.ty, *v),
Op::Cmp(p, a, b) => {
let (cp, ca, cb) = canonical_cmp(*p, *a, *b);
@@ -1779,6 +1942,7 @@ impl Module {
}
let effects = self.effects();
let tree = self.dominator_tree();
+ let no_resource_writes = !self.has_resource_writes(&effects, &tree.order);
let escaped = self.escaped_globals(&tree.order);
let mut repl: Vec<Option<V>> = vec![None; self.insts.len()];
let mut changed = false;
@@ -1820,19 +1984,19 @@ impl Module {
}
// The values every path to the block being walked has computed
// (those of the blocks above it in the tree, and its own so far).
- let mut known: HashMap<Key, V> = HashMap::new();
+ let mut known: HashMap<Key, V> = HashMap::default();
// Per-block resource memory reads (`dx.op.*` with `Effect::Reads`).
- let mut read_mem: HashMap<Key, V> = HashMap::new();
+ let mut read_mem: HashMap<Key, V> = HashMap::default();
// Per-block wave/quad lane ops (`Effect::Lanes`).
- let mut read_lanes: HashMap<Key, V> = HashMap::new();
+ let mut read_lanes: HashMap<Key, V> = HashMap::default();
// Per-block shared memory (LDS, space 3) tracked values.
- let mut shared_const: HashMap<(u32, Vec<u64>), V> = HashMap::new();
- let mut shared_dyn: HashMap<(u32, V, Ty), V> = HashMap::new();
+ let mut shared_const: HashMap<(u32, Vec<u64>), V> = HashMap::default();
+ let mut shared_dyn: HashMap<(u32, V, Ty), V> = HashMap::default();
// Per-block escaped/unknown pointer loads.
- let mut unknown_loads: HashMap<V, V> = HashMap::new();
+ let mut unknown_loads: HashMap<V, V> = HashMap::default();
// Per-block un-observed local/shared stores eligible for overwritten DSE.
- let mut pending_const_stores: HashMap<(u32, Vec<u64>), usize> = HashMap::new();
- let mut pending_dyn_stores: HashMap<(u32, V, Ty), usize> = HashMap::new();
+ let mut pending_const_stores: HashMap<(u32, Vec<u64>), usize> = HashMap::default();
+ let mut pending_dyn_stores: HashMap<(u32, V, Ty), usize> = HashMap::default();
// Exit state of non-escaping thread-private globals for single-pred children.
let mut exit_private: Vec<Option<PrivateVals>> = vec![None; self.blocks.len()];
let mut facts = Facts::default();
@@ -1893,7 +2057,7 @@ impl Module {
let mut dropped_kept = false;
// Two joins of the same values from the same blocks are one.
if passes & REUSE != 0 && self.blocks[b].phis.len() > 1 {
- let mut joins: HashMap<Vec<(usize, V)>, V> = HashMap::new();
+ let mut joins: HashMap<Vec<(usize, V)>, V> = HashMap::default();
for &p in &self.blocks[b].phis {
if repl[p as usize].is_some() {
continue;
@@ -1996,7 +2160,7 @@ impl Module {
changed = true;
continue;
}
- let class = self.class(&effects, i);
+ let class = self.class_with(&effects, i, no_resource_writes);
if passes & REUSE != 0
&& class == Effect::Pure
&& let Some(key) = self.key(i)
@@ -2009,11 +2173,11 @@ impl Module {
known.insert(key.clone(), V::Inst(i));
added.push(key);
}
- match self.insts[i as usize].op.clone() {
+ match &self.insts[i as usize].op {
Op::Load(_) if class == Effect::Pure => {
barriers.on_load(PtrRoot::ConstGlobal(0));
}
- Op::Load(ptr) => {
+ &Op::Load(ptr) => {
if passes & (LOADS | BARRIERS) != 0 {
let val_ty = self.insts[i as usize].ty;
let (root, raw_path) = self.trace_ptr(ptr, &escaped);
@@ -2101,7 +2265,7 @@ impl Module {
barriers.reset();
}
}
- Op::Store(ptr, val) => {
+ &Op::Store(ptr, val) => {
if passes & LOADS != 0 {
let val_ty = self.type_of(val);
let (root, raw_path) = self.trace_ptr(ptr, &escaped);
@@ -2203,7 +2367,7 @@ impl Module {
}
barriers.reset();
}
- Op::AtomicRmw(_, ptr, _) | Op::CmpXchg(ptr, _, _) => {
+ &Op::AtomicRmw(_, ptr, _) | &Op::CmpXchg(ptr, _, _) => {
if passes & LOADS != 0 {
let (root, _) = self.trace_ptr(ptr, &escaped);
match root {
@@ -2226,7 +2390,9 @@ impl Module {
}
barriers.reset();
}
- Op::Call(f, args) => match class {
+ Op::Call(f, args) => {
+ let f = *f;
+ match class {
Effect::Reads => {
if passes & LOADS != 0
&& let Some(key) = self.key(i)
@@ -2398,7 +2564,8 @@ impl Module {
barriers.reset();
}
}
- },
+ }
+ }
Op::Phi(_) => barriers.reset(),
_ => {}
}
@@ -2490,7 +2657,7 @@ impl Module {
/// hoist to the loop preheader (`guaranteed`: `i` executes on every entry
/// to the loop with the exact same active lanes as the preheader, before
/// any `dx.op.discard` or unknown side-effecting call).
- fn can_hoist(&self, effects: &[Effect], i: u32, guaranteed: bool) -> bool {
+ fn can_hoist(&self, effects: &[Effect], i: u32, guaranteed: bool, no_resource_writes: bool) -> bool {
match &self.insts[i as usize].op {
Op::Bin(Bin::UDiv | Bin::URem, _, rhs) => {
self.int_k(*rhs).is_some_and(|(_, k)| k != 0)
@@ -2498,6 +2665,12 @@ impl Module {
Op::Bin(Bin::SDiv, _, rhs) => self
.int_k(*rhs)
.is_some_and(|(bits, k)| k != 0 && signed(bits, k) != -1),
+ // Keep `fdiv arcp` in its original block: NVIDIA's D3D12 DXIL
+ // compiler rejects large compute shaders with `E_OUTOFMEMORY`
+ // (`0x8007000E`) when `LICM` hoists `fdiv arcp` out of a guarded
+ // `x != 0` branch into a loop preheader. This matches
+ // `Op::Bin(Bin::SDiv, ..)` above, which never hoisted float `fdiv`.
+ Op::FDivArcp(..) => false,
Op::Bin(..)
| Op::Cast(..)
| Op::Cmp(..)
@@ -2510,7 +2683,7 @@ impl Module {
|| self.is_in_bounds_const_global_ptr(*p, self.insts[i as usize].ty))
}
Op::Call(f, _) => {
- if effects[*f as usize] != Effect::Pure {
+ if self.class_with(effects, i, no_resource_writes) != Effect::Pure {
return false;
}
if guaranteed {
@@ -2613,8 +2786,9 @@ impl Module {
}
let effects = self.effects();
let mut tree = self.dominator_tree();
+ let no_resource_writes = !self.has_resource_writes(&effects, &tree.order);
// Group all backedges `(latch -> header)` by header.
- let mut latches_by_header: HashMap<usize, Vec<usize>> = HashMap::new();
+ let mut latches_by_header: HashMap<usize, Vec<usize>> = HashMap::default();
for &b in &tree.order {
for &s in successors(self.blocks[b].term).iter() {
if dominates(&tree.idom, s, b) {
@@ -2738,7 +2912,7 @@ impl Module {
guaranteed = false;
}
let dom_target = preheader.unwrap_or(entry_pred);
- if self.can_hoist(&effects, i, guaranteed)
+ if self.can_hoist(&effects, i, guaranteed, no_resource_writes)
&& self.operands_invariant(
i,
&loops[idx].in_loop,
@@ -8426,4 +8600,154 @@ mod tests {
);
k.m.write();
}
+
+ #[test]
+ fn slot_strides_and_readonly_srv_loads_cse_across_blocks() {
+ use super::super::super::shader::{SLOT_STRIDES, Shader};
+ let count_raw_loads = |m: &Module| -> usize {
+ m.blocks
+ .iter()
+ .flat_map(|b| &b.body)
+ .filter(|&&i| {
+ matches!(m.insts[i as usize].op, Op::Call(f, _) if m.funcs[f as usize].name == "dx.op.rawBufferLoad.f32")
+ })
+ .count()
+ };
+
+ // 1. With a UAV store in between, SLOT_STRIDES rawBufferLoad STILL CSEs across blocks,
+ // while an ordinary heap SRV rawBufferLoad stays separate (aliasing conservative).
+ let mut s = Shader::new(false);
+ let entry = s.entry;
+ let then = s.m.new_block();
+ let k0 = s.m.i32(0);
+ let k4 = s.m.i32(4);
+ let iu = s.m.undef(s.t.i32);
+ let m1 = s.m.i8(1);
+ let f0 = s.m.f32(0);
+ let strides_h = s.root_srv_handle(SLOT_STRIDES);
+ let heap_srv = s.heap_handle(entry, k0, false, false, (11, 0));
+ let uav_h = s.heap_handle(entry, k4, false, false, (11 | 0x1000, 0));
+
+ let st1 = s.op(entry, "rawBufferLoad.f32", Attr::ReadOnly, s.t.res_ret, 139, &[strides_h, k0, iu, m1, k4]);
+ let sr1 = s.op(entry, "rawBufferLoad.f32", Attr::ReadOnly, s.t.res_ret, 139, &[heap_srv, k0, iu, m1, k4]);
+ let v1 = s.m.extract(entry, st1, 0);
+ let v2 = s.m.extract(entry, sr1, 0);
+ s.op(entry, "rawBufferStore.f32", Attr::NoUnwind, s.t.void, 140, &[uav_h, k0, iu, v1, v2, f0, f0, m1, k4]);
+ s.m.terminate(entry, Term::Br(then));
+
+ let st2 = s.op(then, "rawBufferLoad.f32", Attr::ReadOnly, s.t.res_ret, 139, &[strides_h, k0, iu, m1, k4]);
+ let sr2 = s.op(then, "rawBufferLoad.f32", Attr::ReadOnly, s.t.res_ret, 139, &[heap_srv, k0, iu, m1, k4]);
+ let w1 = s.m.extract(then, st2, 0);
+ let w2 = s.m.extract(then, sr2, 0);
+ s.op(then, "rawBufferStore.f32", Attr::NoUnwind, s.t.void, 140, &[uav_h, k4, iu, w1, w2, f0, f0, m1, k4]);
+ s.m.terminate(then, Term::Ret);
+
+ assert_eq!(count_raw_loads(&s.m), 4);
+ s.m.optimise(DEAD | REUSE | LOADS);
+ // st2 collapsed into st1; sr1 and sr2 stayed separate because of rawBufferStore.
+ assert_eq!(count_raw_loads(&s.m), 3);
+
+ // 2. Without any resource writes (read-only shader), heap SRV rawBufferLoad CSEs across blocks.
+ let mut ro = Shader::new(false);
+ let e = ro.entry;
+ let b2 = ro.m.new_block();
+ let k0 = ro.m.i32(0);
+ let k4 = ro.m.i32(4);
+ let iu = ro.m.undef(ro.t.i32);
+ let m1 = ro.m.i8(1);
+ let srv = ro.heap_handle(e, k0, false, false, (11, 0));
+ let l1 = ro.op(e, "rawBufferLoad.f32", Attr::ReadOnly, ro.t.res_ret, 139, &[srv, k0, iu, m1, k4]);
+ let x1 = ro.m.extract(e, l1, 0);
+ ro.m.terminate(e, Term::Br(b2));
+ let l2 = ro.op(b2, "rawBufferLoad.f32", Attr::ReadOnly, ro.t.res_ret, 139, &[srv, k0, iu, m1, k4]);
+ let x2 = ro.m.extract(b2, l2, 0);
+ let sum = ro.m.bin(b2, Bin::Add, x1, x2);
+ ro.op(b2, "storeOutput.f32", Attr::NoUnwind, ro.t.void, 5, &[k0, k0, m1, sum]);
+ ro.m.terminate(b2, Term::Ret);
+
+ assert_eq!(count_raw_loads(&ro.m), 2);
+ ro.m.optimise(DEAD | REUSE | LOADS);
+ assert_eq!(count_raw_loads(&ro.m), 1);
+
+ // 3. With SLOT_SAMPLED telemetry atomic + waveIsFirstLane, heap SRV still CSEs.
+ let mut sm = Shader::new(false);
+ let e = sm.entry;
+ let b2 = sm.m.new_block();
+ let k0 = sm.m.i32(0);
+ let k2 = sm.m.i32(2);
+ let k4 = sm.m.i32(4);
+ let iu = sm.m.undef(sm.t.i32);
+ let m1 = sm.m.i8(1);
+ let srv = sm.heap_handle(e, k0, false, false, (11, 0));
+ let marks = sm.root_uav_handle(super::super::super::shader::SLOT_SAMPLED);
+ let _first = sm.op(e, "waveIsFirstLane", Attr::NoUnwind, sm.t.i1, 110, &[]);
+ let l1 = sm.op(e, "rawBufferLoad.f32", Attr::ReadOnly, sm.t.res_ret, 139, &[srv, k0, iu, m1, k4]);
+ let x1 = sm.m.extract(e, l1, 0);
+ sm.op(e, "atomicBinOp.i32", Attr::NoUnwind, sm.t.i32, 78, &[marks, k2, k0, iu, iu, k4]);
+ sm.m.terminate(e, Term::Br(b2));
+ let l2 = sm.op(b2, "rawBufferLoad.f32", Attr::ReadOnly, sm.t.res_ret, 139, &[srv, k0, iu, m1, k4]);
+ let x2 = sm.m.extract(b2, l2, 0);
+ let sum = sm.m.bin(b2, Bin::Add, x1, x2);
+ sm.op(b2, "storeOutput.f32", Attr::NoUnwind, sm.t.void, 5, &[k0, k0, m1, sum]);
+ sm.m.terminate(b2, Term::Ret);
+
+ assert_eq!(count_raw_loads(&sm.m), 2);
+ sm.m.optimise(DEAD | REUSE | LOADS);
+ assert_eq!(count_raw_loads(&sm.m), 1);
+ }
+
+ #[test]
+ fn licm_does_not_hoist_fdiv_arcp_out_of_loop() {
+ use super::super::super::shader::Shader;
+ let mut s = Shader::new(false);
+ let entry = s.entry;
+ let header = s.m.new_block();
+ let div_bb = s.m.new_block();
+ let latch = s.m.new_block();
+ let exit = s.m.new_block();
+
+ let k0 = s.m.i32(0);
+ let k1 = s.m.i32(1);
+ let k4 = s.m.i32(4);
+ let f0 = s.m.f32(0);
+ let f1 = s.m.f32(1.0f32.to_bits());
+ let iu = s.m.undef(s.t.i32);
+ let m1 = s.m.i8(1);
+ let srv = s.heap_handle(entry, k0, false, false, (11, 0));
+ let uav = s.heap_handle(entry, k4, false, false, (11 | 0x1000, 0));
+ let loaded = s.op(entry, "rawBufferLoad.f32", Attr::ReadOnly, s.t.res_ret, 139, &[srv, k0, iu, m1, k4]);
+ let denom = s.m.extract(entry, loaded, 0);
+ s.m.terminate(entry, Term::Br(header));
+
+ let iv = s.m.phi(header, s.t.i32);
+ let is_zero = s.m.cmp(header, pred::OEQ, f0, denom);
+ s.m.terminate(header, Term::CondBr(is_zero, latch, div_bb));
+
+ let rcp = s.m.fdiv_arcp(div_bb, f1, denom);
+ s.m.terminate(div_bb, Term::Br(latch));
+
+ let val = s.m.phi(latch, s.t.f32);
+ s.m.set_phi(val, vec![(f0, header), (rcp, div_bb)]);
+ s.op(latch, "rawBufferStore.f32", Attr::NoUnwind, s.t.void, 140, &[uav, iv, iu, val, f0, f0, f0, m1, k4]);
+ let next = s.m.bin(latch, Bin::Add, iv, k1);
+ let more = s.m.cmp(latch, pred::IULT, next, k4);
+ s.m.terminate(latch, Term::CondBr(more, header, exit));
+ s.m.set_phi(iv, vec![(k0, entry), (next, latch)]);
+
+ s.m.terminate(exit, Term::Ret);
+
+ s.m.optimise(DEAD | FOLD | REUSE | FACTS | LOADS | LICM | BARRIERS);
+
+ // `FDivArcp` must remain inside `div_bb` (never hoisted to `entry`).
+ let in_entry = s.m.blocks[entry]
+ .body
+ .iter()
+ .any(|&i| matches!(s.m.insts[i as usize].op, Op::FDivArcp(..)));
+ let in_div = s.m.blocks[div_bb]
+ .body
+ .iter()
+ .any(|&i| matches!(s.m.insts[i as usize].op, Op::FDivArcp(..)));
+ assert!(!in_entry, "LICM must not hoist FDivArcp into loop preheader");
+ assert!(in_div, "FDivArcp must stay in its guarded loop block");
+ }
}
diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs
index 146024f..06f2921 100644
--- a/crates/victory-shader/src/emit/lower.rs
+++ b/crates/victory-shader/src/emit/lower.rs
@@ -4412,35 +4412,44 @@ impl<'a> Lower<'a> {
/// top bit when `signed`; widths from 32 on take every bit. A signed
/// field that runs past bit 31 extends from bit 31, as the hardware
/// does: the shift is arithmetic then.
- fn bfe(&mut self, a: V, off: V, width: V, signed: bool) -> V {
+ ///
+ /// Lowers directly to DXIL `Ibfe` (51) / `Ubfe` (52). For signed `Ibfe`,
+ /// clamping `width` to `32 - (off & 31)` matches RDNA2 sign-extension from
+ /// bit 31 when `off + width > 32` (whereas raw DXIL `Ibfe` reads bit
+ /// `width - 1` of the shifted value).
+ fn bfe(&mut self, a: V, off: V, width: V, signed: bool, narrow_width: bool) -> V {
let c = self.cur;
- let (k31, k32, zero, one, ones) = (
- self.s.m.i32(31),
- self.s.m.i32(32),
- self.s.m.i32(0),
- self.s.m.i32(1),
- self.s.m.i32(u32::MAX),
- );
- let off = self.s.m.bin(c, Bin::And, off, k31);
+ let op = if signed { 51 } else { 52 };
+ let bfe_op = |l: &mut Self, w: V, o: V, v: V| {
+ l.s.op(c, "tertiary.i32", Attr::ReadNone, l.s.t.i32, op, &[w, o, v])
+ };
+ let k31 = self.s.m.i32(31);
+ let k32 = self.s.m.i32(32);
+ if narrow_width {
+ if !signed {
+ return bfe_op(self, width, off, a);
+ }
+ let o = self.s.m.bin(c, Bin::And, off, k31);
+ let w = self.s.m.bin(c, Bin::And, width, k31);
+ let room = self.s.m.bin(c, Bin::Sub, k32, o);
+ let fits = self.s.m.cmp(c, pred::IULE, w, room);
+ let w_eff = self.s.m.select(c, fits, w, room);
+ return bfe_op(self, w_eff, o, a);
+ }
let shift = if signed { Bin::AShr } else { Bin::LShr };
- let shifted = self.s.m.bin(c, shift, a, off);
+ let o = self.s.m.bin(c, Bin::And, off, k31);
+ let shifted = self.s.m.bin(c, shift, a, o);
let full = self.s.m.cmp(c, pred::IUGE, width, k32);
- let w = self.s.m.bin(c, Bin::And, width, k31);
- let mask = self.s.m.bin(c, Bin::Shl, one, w);
- let mask = self.s.m.bin(c, Bin::Sub, mask, one);
- let mask = self.s.m.select(c, full, ones, mask);
- let r = self.s.m.bin(c, Bin::And, shifted, mask);
- if !signed {
- return r;
- }
- // Sign-extend a field narrower than 32 bits (none for width 0).
- let left = self.s.m.bin(c, Bin::Sub, k32, w);
- let left = self.s.m.bin(c, Bin::And, left, k31);
- let t = self.s.m.bin(c, Bin::Shl, r, left);
- let t = self.s.m.bin(c, Bin::AShr, t, left);
- let is0 = self.s.m.cmp(c, pred::EQ, w, zero);
- let keep = self.s.m.bin(c, Bin::Or, full, is0);
- self.s.m.select(c, keep, r, t)
+ let extracted = if signed {
+ let room = self.s.m.bin(c, Bin::Sub, k32, o);
+ let w = self.s.m.bin(c, Bin::And, width, k31);
+ let fits = self.s.m.cmp(c, pred::IULE, w, room);
+ let w_eff = self.s.m.select(c, fits, w, room);
+ bfe_op(self, w_eff, o, a)
+ } else {
+ bfe_op(self, width, o, a)
+ };
+ self.s.m.select(c, full, shifted, extracted)
}
/// Holds a pixel float colour output to `[-65024, 65024]` (`VICTORY_HDR_CLAMP`).
@@ -4504,12 +4513,16 @@ impl<'a> Lower<'a> {
/// different constant than 2π (a last-place difference).
fn trig_turns(&mut self, x: V, cosine: bool) -> V {
let c = self.cur;
- let zero = self.s.m.f32(0);
let whole = self.unary(26, x);
let part = self.s.m.bin(c, Bin::Sub, x, whole);
+ let k = self.s.m.f32(TWO_PI.to_bits());
+ if host_rdna() & super::rdna::TRIG_PLAIN != 0 {
+ let angle = self.s.m.bin(c, Bin::Mul, part, k);
+ return self.unary(if cosine { 12 } else { 13 }, angle);
+ }
+ let zero = self.s.m.f32(0);
let is_zero = self.s.m.cmp(c, pred::OEQ, x, zero);
let part = self.s.m.select(c, is_zero, x, part);
- let k = self.s.m.f32(TWO_PI.to_bits());
let angle = self.s.m.bin(c, Bin::Mul, part, k);
let r = self.unary(if cosine { 12 } else { 13 }, angle);
let at = if cosine { 0.25f32 } else { 0.5 };
@@ -4536,6 +4549,9 @@ impl<'a> Lower<'a> {
/// `0 × anything = 0`, as in D3D9.
fn legacy_mul(&mut self, a: V, b: V) -> V {
let c = self.cur;
+ if host_rdna() & super::rdna::LEGACY_PLAIN != 0 {
+ return self.s.m.bin(c, Bin::Mul, a, b);
+ }
if host_rdna() & super::rdna::LEGACY != 0 {
let m = self.s.m.bin(c, Bin::Mul, a, b);
let zero = self.s.m.f32(0);
@@ -4899,13 +4915,20 @@ impl<'a> Lower<'a> {
let half = self.s.m.bin(c, Bin::LShr, cl, five);
let half = self.s.m.bin(c, Bin::Shl, half, one);
let own = self.s.m.bin(c, Bin::Add, at, half);
+ let first = self.s.op(c, "waveIsFirstLane", Attr::NoUnwind, self.s.t.i1, 110, &[]);
+ self.s.flags |= flags::WAVE_OPS;
+ let (write_bb, join_bb) = (self.s.m.new_block(), self.s.m.new_block());
+ self.s.m.terminate(c, Term::CondBr(first, write_bb, join_bb));
let lds = self.s.lds();
for (w, &x) in mine.iter().enumerate() {
let k = self.s.m.i32(w as u32);
- let dword = self.s.m.bin(c, Bin::Add, own, k);
- let ptr = self.s.m.element(c, lds, dword);
- self.s.m.store(c, ptr, x);
+ let dword = self.s.m.bin(write_bb, Bin::Add, own, k);
+ let ptr = self.s.m.element(write_bb, lds, dword);
+ self.s.m.store(write_bb, ptr, x);
}
+ self.s.m.terminate(write_bb, Term::Br(join_bb));
+ self.cur = join_bb;
+ self.s.m.continues(c, join_bb);
let absent = self.meet();
let c = self.cur;
let two = self.s.m.i32(2);
@@ -5053,7 +5076,8 @@ impl<'a> Lower<'a> {
let generation = self.s.m.bin(join, Bin::Add, shared, one);
let (wait, done) = (self.s.m.new_block(), self.s.m.new_block());
self.s.m.terminate(join, Term::Br(wait));
- let polls = self.s.m.phi(wait, i32t);
+ let track_tally = self.meet_uav.is_some();
+ let polls = track_tally.then(|| self.s.m.phi(wait, i32t));
let (lyes, lno, ljoin) = (self.s.m.new_block(), self.s.m.new_block(), self.s.m.new_block());
self.s.m.terminate(wait, Term::CondBr(first, lyes, lno));
let theirs = self.s.m.element(lyes, lds, other);
@@ -5064,17 +5088,21 @@ impl<'a> Lower<'a> {
self.s.m.set_phi(seen_lane, vec![(seen_yes, lyes), (zero, lno)]);
let seen = self.s.op(ljoin, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[seen_lane]);
let ready = self.s.m.cmp(ljoin, pred::IUGE, seen, generation);
- let polled = self.s.m.bin(ljoin, Bin::Add, polls, one);
+ let polled = polls.map(|p| self.s.m.bin(ljoin, Bin::Add, p, one));
self.s.m.terminate(ljoin, Term::CondBr(ready, done, wait));
- let start = self.s.m.i32(0);
- self.s.m.set_phi(polls, vec![(start, join), (polled, ljoin)]);
- self.cur = done;
- let who = self.tally_lane(done);
- let guarded = self.begin_guarded(Some(who));
- let here = self.cur;
- self.lds_tally(here, 0, one);
- self.lds_tally(here, 1, polled);
- self.end_guarded(guarded, &[]);
+ if let (Some(polls), Some(polled)) = (polls, polled) {
+ let start = self.s.m.i32(0);
+ self.s.m.set_phi(polls, vec![(start, join), (polled, ljoin)]);
+ self.cur = done;
+ let who = self.tally_lane(done);
+ let guarded = self.begin_guarded(Some(who));
+ let here = self.cur;
+ self.lds_tally(here, 0, one);
+ self.lds_tally(here, 1, polled);
+ self.end_guarded(guarded, &[]);
+ } else {
+ self.cur = done;
+ }
let after = self.cur;
// The rest of this instruction was aimed at the block the meet closed.
self.s.m.continues(block, after);
@@ -5128,28 +5156,39 @@ impl<'a> Lower<'a> {
self.end_guarded(guarded, &[]);
}
- /// Zeroes the meet table. Every thread runs it, then one group barrier, before any meet.
+ /// Zeroes the meet table. Each thread strides by the group size, then one group barrier, before any meet.
fn zero_meet_slots(&mut self) {
if self.meet_cap == 0 {
return;
}
let n = self.meet_cap * 2 * self.meet_waves.max(1) + 3;
+ let group = self.s.threads.map_or(1, |t| t.iter().product::<u32>()).max(1);
let entry = self.s.entry;
+ let i32t = self.s.t.i32;
+ let start = if group > 1 {
+ self.s.op(entry, "flattenedThreadIdInGroup.i32", Attr::ReadNone, i32t, 96, &[])
+ } else {
+ self.s.m.i32(0)
+ };
+ let last = self.s.m.i32(n);
let (head, done) = (self.s.m.new_block(), self.s.m.new_block());
- self.s.m.terminate(entry, Term::Br(head));
- let i = self.s.m.phi(head, self.s.t.i32);
+ if group > 1 {
+ let enter = self.s.m.cmp(entry, pred::IULT, start, last);
+ self.s.m.terminate(entry, Term::CondBr(enter, head, done));
+ } else {
+ self.s.m.terminate(entry, Term::Br(head));
+ }
+ let i = self.s.m.phi(head, i32t);
let base = self.s.m.i32(self.meet_base);
let idx = self.s.m.bin(head, Bin::Add, base, i);
let lds = self.s.lds();
let ptr = self.s.m.element(head, lds, idx);
let zero = self.s.m.i32(0);
self.s.m.store(head, ptr, zero);
- let one = self.s.m.i32(1);
- let next = self.s.m.bin(head, Bin::Add, i, one);
- let last = self.s.m.i32(n);
+ let stride = self.s.m.i32(group);
+ let next = self.s.m.bin(head, Bin::Add, i, stride);
let more = self.s.m.cmp(head, pred::IULT, next, last);
self.s.m.terminate(head, Term::CondBr(more, head, done));
- let start = self.s.m.i32(0);
self.s.m.set_phi(i, vec![(start, entry), (next, head)]);
self.group_sync(done);
self.s.entry = done;
@@ -5200,8 +5239,22 @@ impl<'a> Lower<'a> {
let five = self.s.m.i32(5);
let half = self.s.m.bin(at, Bin::LShr, cl, five);
let index = self.s.m.bin(at, Bin::Add, pair, half);
- let ptr = self.s.m.element(at, lds, index);
- self.s.m.store(at, ptr, mine);
+ let at = if at == self.cur {
+ let first = self.s.op(at, "waveIsFirstLane", Attr::NoUnwind, self.s.t.i1, 110, &[]);
+ self.s.flags |= flags::WAVE_OPS;
+ let (write_bb, join_bb) = (self.s.m.new_block(), self.s.m.new_block());
+ self.s.m.terminate(at, Term::CondBr(first, write_bb, join_bb));
+ let ptr = self.s.m.element(write_bb, lds, index);
+ self.s.m.store(write_bb, ptr, mine);
+ self.s.m.terminate(write_bb, Term::Br(join_bb));
+ self.cur = join_bb;
+ self.s.m.continues(at, join_bb);
+ join_bb
+ } else {
+ let ptr = self.s.m.element(at, lds, index);
+ self.s.m.store(at, ptr, mine);
+ at
+ };
let at = self.order_waves(at, self.reached_by_group());
let one = self.s.m.i32(1);
let k1 = self.s.m.bin(at, Bin::Add, pair, one);
@@ -5214,6 +5267,74 @@ impl<'a> Lower<'a> {
Ok((lo, hi))
}
+ /// Exchanges two uniform values `(a, b)` between a console wave's two halves
+ /// in a single pair of barriers when private exchange LDS fits 4 words/wave,
+ /// falling back to two [`Self::exchange_halves`] calls otherwise.
+ fn exchange_halves_two(&mut self, a: V, b: V) -> Result<((V, V), (V, V)), Why> {
+ let c = self.cur;
+ let Some((slot, small, _)) = self.exchange.as_ref().map(|(s, sm, _)| (*s, *sm, ())) else {
+ let z = self.s.m.i32(0);
+ return Ok(((a, z), (b, z)));
+ };
+ if small || self.local || self.pairs.is_some() {
+ let ra = self.exchange_halves(c, a)?;
+ let c = self.cur;
+ let rb = self.exchange_halves(c, b)?;
+ return Ok((ra, rb));
+ }
+ let threads = self.s.threads.expect("compute exchange").iter().product::<u32>();
+ let words = 4 * threads.div_ceil(64);
+ if self.s.lds_dwords + self.private_exchange_dwords + words > HOST_LDS_DWORDS {
+ let ra = self.exchange_halves(c, a)?;
+ let c = self.cur;
+ let rb = self.exchange_halves(c, b)?;
+ return Ok((ra, rb));
+ }
+ self.sync_block = c;
+ let pair = self.exchange_pair(slot);
+ let ty = self.s.m.array(words, self.s.t.i32);
+ let lds = self.s.m.global(&format!("wave_exchange_{}", self.private_exchange_dwords), ty, 3);
+ self.private_exchange_dwords += words;
+ let base = self.s.m.i32(slot);
+ let one = self.s.m.i32(1);
+ let two = self.s.m.i32(2);
+ let three = self.s.m.i32(3);
+ let five = self.s.m.i32(5);
+ // `pair - base = 2 * wave`, so shifting left by 1 gives `4 * wave`.
+ let quad = self.s.m.bin(c, Bin::Sub, pair, base);
+ let quad = self.s.m.bin(c, Bin::Shl, quad, one);
+ let cl = self.console_lane();
+ let half = self.s.m.bin(c, Bin::LShr, cl, five);
+ let half_off = self.s.m.bin(c, Bin::Shl, half, one);
+ let own0 = self.s.m.bin(c, Bin::Add, quad, half_off);
+ let own1 = self.s.m.bin(c, Bin::Add, own0, one);
+ let first = self.s.op(c, "waveIsFirstLane", Attr::NoUnwind, self.s.t.i1, 110, &[]);
+ self.s.flags |= flags::WAVE_OPS;
+ let (write_bb, join_bb) = (self.s.m.new_block(), self.s.m.new_block());
+ self.s.m.terminate(c, Term::CondBr(first, write_bb, join_bb));
+ let p0 = self.s.m.element(write_bb, lds, own0);
+ let p1 = self.s.m.element(write_bb, lds, own1);
+ self.s.m.store(write_bb, p0, a);
+ self.s.m.store(write_bb, p1, b);
+ self.s.m.terminate(write_bb, Term::Br(join_bb));
+ self.cur = join_bb;
+ self.s.m.continues(c, join_bb);
+ let at = self.order_waves(join_bb, self.reached_by_group());
+ let k1 = self.s.m.bin(at, Bin::Add, quad, one);
+ let k2 = self.s.m.bin(at, Bin::Add, quad, two);
+ let k3 = self.s.m.bin(at, Bin::Add, quad, three);
+ let (r0, r1, r2, r3) = (
+ self.s.m.element(at, lds, quad),
+ self.s.m.element(at, lds, k1),
+ self.s.m.element(at, lds, k2),
+ self.s.m.element(at, lds, k3),
+ );
+ let (lo_a, lo_b) = (self.s.m.load(at, r0), self.s.m.load(at, r1));
+ let (hi_a, hi_b) = (self.s.m.load(at, r2), self.s.m.load(at, r3));
+ let _at = self.order_waves(at, self.reached_by_group());
+ Ok(((lo_a, hi_a), (lo_b, hi_b)))
+ }
+
/// Keep lane reads and reductions at distinct static sites from overwriting one another.
/// A lane broadcast needs one word per console wave, a pair of partial results needs two.
fn exchange_storage(&mut self, at: usize, slot: u32, words_per_wave: u32) -> (V, V) {
@@ -5923,16 +6044,25 @@ impl<'a> Lower<'a> {
};
let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
let r = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[g]);
- let (lo, hi) = (self.s.m.extract(c, r, 0), self.s.m.extract(c, r, 1));
- let (z, k32) = (self.s.m.i32(0), self.s.m.i32(32));
+ let lo = self.s.m.extract(c, r, 0);
+ let z = self.s.m.i32(0);
// FirstbitLo (dx.op 32): the lowest set bit
let flo = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[lo]);
- let fhi = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[hi]);
- let fhi = self.s.m.bin(c, Bin::Add, fhi, k32);
- let in_lo = self.s.m.cmp(c, pred::NE, lo, z);
- let in_hi = self.s.m.cmp(c, pred::NE, hi, z);
- let any = self.s.m.bin(c, Bin::Or, in_lo, in_hi);
- let lane = self.s.m.select(c, in_lo, flo, fhi);
+ let (any, lane) = if self.s.wave_size == Some(32) {
+ // Wave32 ballots have zero upper lanes: skip hi extraction and selection.
+ let any = self.s.m.cmp(c, pred::NE, lo, z);
+ (any, flo)
+ } else {
+ let hi = self.s.m.extract(c, r, 1);
+ let k32 = self.s.m.i32(32);
+ let fhi = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[hi]);
+ let fhi = self.s.m.bin(c, Bin::Add, fhi, k32);
+ let in_lo = self.s.m.cmp(c, pred::NE, lo, z);
+ let in_hi = self.s.m.cmp(c, pred::NE, hi, z);
+ let any = self.s.m.bin(c, Bin::Or, in_lo, in_hi);
+ let lane = self.s.m.select(c, in_lo, flo, fhi);
+ (any, lane)
+ };
// no lane in EXEC: read this lane (one that is here); the read is not used
let me = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
let lane = self.s.m.select(c, any, lane, me);
@@ -5949,8 +6079,14 @@ impl<'a> Lower<'a> {
self.s.m.i32(0),
);
let low = self.s.m.cmp(at, pred::IULT, lane, k32);
- let word = self.s.m.select(at, low, lo, hi);
let sh = self.s.m.bin(at, Bin::And, lane, k31);
+ if self.s.wave_size == Some(32) {
+ let t = self.s.m.bin(at, Bin::LShr, lo, sh);
+ let t = self.s.m.bin(at, Bin::And, t, one);
+ let bit = self.s.m.cmp(at, pred::NE, t, z);
+ return self.s.m.bin(at, Bin::And, low, bit);
+ }
+ let word = self.s.m.select(at, low, lo, hi);
let t = self.s.m.bin(at, Bin::LShr, word, sh);
let t = self.s.m.bin(at, Bin::And, t, one);
self.s.m.cmp(at, pred::NE, t, z)
@@ -7447,7 +7583,7 @@ impl<'a> Lower<'a> {
let (k16, k127) = (self.s.m.i32(16), self.s.m.i32(0x7F));
let w = self.s.m.bin(c, Bin::LShr, b, k16);
let w = self.s.m.bin(c, Bin::And, w, k127);
- (self.bfe(a, b, w, name == "s_bfe_i32"), None)
+ (self.bfe(a, b, w, name == "s_bfe_i32", false), None)
}
"s_and_b32" | "s_or_b32" | "s_xor_b32" | "s_andn2_b32" | "s_orn2_b32"
| "s_nand_b32" | "s_nor_b32" | "s_xnor_b32" => {
@@ -7790,71 +7926,99 @@ impl<'a> Lower<'a> {
// The host's table of strides by heap slot tells a buffer view
// (not 0) from anything else, which is still read as a constant
// buffer; only the load that fits the slot runs.
+ // With `VICTORY_PORT_CBV=1` (`constants_raw`) and `raw_views != 0`,
+ // both buffer SRVs and CBVs in the view heap have a raw twin at
+ // `index | raw_views`, so a picked `ResourceHeap` scalar load reads
+ // unconditionally through the raw twin without touching `SLOT_STRIDES`
+ // or branching on buffer vs constant buffer.
+ let as_raw = super::shader::constants_raw() && super::shader::raw_views() != 0;
+ if kind.is_none() && as_raw && self.is_picked_heap(&src) {
+ let h = self.handle(site, src, false, (11, 0))?;
+ if Self::wide_loads() {
+ for (k, x) in self.raw_dwords(h, addr, count).into_iter().enumerate() {
+ self.write(inst, Reg::S(code + k as u8), x, None);
+ }
+ } else {
+ for k in 0..count {
+ let b = self.cur;
+ let off = self.s.m.i32(4 * k);
+ let a = self.s.m.bin(b, Bin::Add, addr, off);
+ let mask = self.s.m.i8(1);
+ let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
+ let r = self.s.op(
+ b,
+ "rawBufferLoad.f32",
+ Attr::ReadOnly,
+ self.s.t.res_ret,
+ 139,
+ &[h, a, u, mask, al],
+ );
+ let x = self.s.m.extract(b, r, 0);
+ let x = self.as_int(x);
+ self.write(inst, Reg::S(code + k as u8), x, None);
+ }
+ }
+ return Ok(());
+ }
let picked = match kind {
None => self.slot_stride(src)?,
Some(_) => None,
};
if let Some(stride) = picked {
+ // Single if/else diamond (`stride != 0` raw buffer vs `stride == 0`
+ // constant buffer) instead of two sequential guarded blocks.
let zero = self.s.m.i32(0);
let is_buffer = self.s.m.cmp(self.cur, pred::NE, stride, zero);
- let at = self.begin_guarded(Some(is_buffer));
- let h = self.handle(site, src, false, (11, 0))?;
- let mut raw = Vec::new();
- let wide = Self::wide_loads();
- if wide {
- let dwords = self.raw_dwords(h, addr, count);
- raw.extend(dwords.into_iter().map(|x| (x, zero)));
+ let raw_bb = self.s.m.new_block();
+ let cbuf_bb = self.s.m.new_block();
+ let join_bb = self.s.m.new_block();
+ self.s.m.terminate(self.cur, Term::CondBr(is_buffer, raw_bb, cbuf_bb));
+
+ self.cur = raw_bb;
+ let h_raw = self.handle(site, src, false, (11, 0))?;
+ let mut raw = Vec::with_capacity(count as usize);
+ if Self::wide_loads() {
+ raw.extend(self.raw_dwords(h_raw, addr, count));
+ } else {
+ for k in 0..count {
+ let b = self.cur;
+ let off = self.s.m.i32(4 * k);
+ let a = self.s.m.bin(b, Bin::Add, addr, off);
+ let mask = self.s.m.i8(1);
+ let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
+ let r = self.s.op(
+ b,
+ "rawBufferLoad.f32",
+ Attr::ReadOnly,
+ self.s.t.res_ret,
+ 139,
+ &[h_raw, a, u, mask, al],
+ );
+ let x = self.s.m.extract(b, r, 0);
+ raw.push(self.as_int(x));
+ }
}
- for k in 0..if wide { 0 } else { count } {
+ let raw_end = self.cur;
+ self.s.m.terminate(raw_end, Term::Br(join_bb));
+
+ self.cur = cbuf_bb;
+ let h_cb = self.handle(site, src, false, (13, 0x1_0000))?;
+ let mut cbuf = Vec::with_capacity(count as usize);
+ for k in 0..count {
let b = self.cur;
let off = self.s.m.i32(4 * k);
let a = self.s.m.bin(b, Bin::Add, addr, off);
- let mask = self.s.m.i8(1);
- let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
- let r = self.s.op(
- b,
- "rawBufferLoad.f32",
- Attr::ReadOnly,
- self.s.t.res_ret,
- 139,
- &[h, a, u, mask, al],
- );
- let x = self.s.m.extract(b, r, 0);
- let x = self.as_int(x);
- raw.push((x, zero));
- }
- let raw = self.end_guarded(at, &raw);
- let other = self.s.m.cmp(self.cur, pred::EQ, stride, zero);
- let at = self.begin_guarded(Some(other));
- // (Renderer port 5: the twin of a constant buffer's slot is a
- // raw view of its bytes, read as one.)
- let as_raw = super::shader::constants_raw() && super::shader::raw_views() != 0;
- let h = if as_raw {
- self.handle(site, src, false, (11, 0))?
- } else {
- self.handle(site, src, false, (13, 0x1_0000))?
- };
- let mut both = Vec::new();
- let dwords = if as_raw {
- self.raw_dwords(h, addr, raw.len() as u32)
- } else {
- Vec::new()
- };
- for (k, &r) in raw.iter().enumerate() {
- let b = self.cur;
- let x = match dwords.get(k) {
- Some(&x) => x,
- None => {
- let off = self.s.m.i32(4 * k as u32);
- let a = self.s.m.bin(b, Bin::Add, addr, off);
- self.cbuffer_dword(h, a)
- }
- };
- both.push((x, r));
+ cbuf.push(self.cbuffer_dword(h_cb, a));
}
- let both = self.end_guarded(at, &both);
- for (k, x) in both.into_iter().enumerate() {
- self.write(inst, Reg::S(code + k as u8), x, None);
+ let cbuf_end = self.cur;
+ self.s.m.terminate(cbuf_end, Term::Br(join_bb));
+
+ self.cur = join_bb;
+ let i32t = self.s.t.i32;
+ for (k, (r_val, c_val)) in raw.into_iter().zip(cbuf).enumerate() {
+ let phi = self.s.m.phi(join_bb, i32t);
+ self.s.m.set_phi(phi, vec![(r_val, raw_end), (c_val, cbuf_end)]);
+ self.write(inst, Reg::S(code + k as u8), phi, None);
}
return Ok(());
}
@@ -9018,6 +9182,18 @@ impl<'a> Lower<'a> {
Ok(phi)
}
+ /// Whether `src` is a descriptor picked directly from the view heap
+ /// (`RootType::ResourceHeap`), matching [`Self::slot_word`]'s `SLOT_STRIDES` branch.
+ fn is_picked_heap(&self, src: &Source) -> bool {
+ let Source::Loaded { load, .. } = src else {
+ return false;
+ };
+ self.scalar
+ .get(load)
+ .and_then(|a| self.x.native.layout.get(a.param))
+ .is_some_and(|p| p.root == RootType::ResourceHeap)
+ }
+
/// The bytes per element of the buffer view `src` names, if the program
/// picks it from the view heap at an index it computes (root type
/// `ResourceHeap`): read from the host's table by heap slot in the
@@ -9168,7 +9344,8 @@ impl<'a> Lower<'a> {
.scalar
.get(&load)
.ok_or("an untracked descriptor load")?;
- match self.x.native.layout.get(a.param).map(|p| p.root) {
+ let root = self.x.native.layout.get(a.param).map(|p| p.root);
+ match root {
Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {}
_ => return Err("a descriptor outside the heaps"),
}
@@ -9198,7 +9375,11 @@ impl<'a> Lower<'a> {
.i32((offset as i32 as u32).wrapping_add(4 * u32::from(first)));
at = self.s.m.bin(c, Bin::Add, at, k);
let shift = self.s.m.i32(if sampler { 4 } else { 5 });
- Ok(self.s.m.bin(c, Bin::LShr, at, shift))
+ let index = self.s.m.bin(c, Bin::LShr, at, shift);
+ if root == Some(RootType::ResourceHeap) && !sampler {
+ return Ok(self.title_view(index));
+ }
+ Ok(index)
}
/// The heap index of the descriptor at dword `first` of what the scalar
@@ -9208,7 +9389,8 @@ impl<'a> Lower<'a> {
.scalar
.get(&load)
.ok_or("an untracked descriptor load")?;
- match self.x.native.layout.get(a.param).map(|p| p.root) {
+ let root = self.x.native.layout.get(a.param).map(|p| p.root);
+ match root {
Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {}
_ => return Err("a descriptor outside the heaps"),
}
@@ -9238,7 +9420,30 @@ impl<'a> Lower<'a> {
addr = self.s.m.bin(c, Bin::Add, addr, so);
}
let shift = self.s.m.i32(if sampler { 4 } else { 5 });
- Ok(self.s.m.bin(c, Bin::LShr, addr, shift))
+ let index = self.s.m.bin(c, Bin::LShr, addr, shift);
+ if root == Some(RootType::ResourceHeap) && !sampler {
+ return Ok(self.title_view(index));
+ }
+ Ok(index)
+ }
+
+ /// A view index the program picks from the resource heap, kept to the
+ /// title's slots on the host ([`super::shader::USER_TITLE_VIEWS`]): one
+ /// at or past them reads the null slot at the heap's end. Tables are not
+ /// held to it, as the host makes some of them afresh past the title's
+ /// slots. Without a null slot (no host limit) the index is as it was.
+ fn title_view(&mut self, index: V) -> V {
+ let null = super::shader::view_heap_limit();
+ if null == 0 {
+ return index;
+ }
+ let c = self.cur;
+ let title = self.host_word(RootType::Other(super::shader::USER_TITLE_VIEWS), 0, 0);
+ let inside = self.s.m.cmp(c, pred::IULT, index, title);
+ let null = self.s.m.i32(null);
+ let index = self.s.m.select(c, inside, index, null);
+ self.s.m.tag(index, Tag::Clamp);
+ index
}
fn valu(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
@@ -9966,10 +10171,11 @@ impl<'a> Lower<'a> {
float(self, r)
}
"v_rcp_f32" | "v_rcp_iflag_f32" => {
- // shortcut: the hardware reciprocal is approximate (1 ULP); this divides.
+ // Emit `fdiv arcp 1.0, a` so the host driver lowers to its
+ // single-instruction hardware reciprocal (1 ULP), matching RDNA2.
let a = f(self, 0)?;
let one = self.s.m.f32(1.0f32.to_bits());
- let r = self.s.m.bin(c, Bin::SDiv, one, a);
+ let r = self.s.m.fdiv_arcp(c, one, a);
float(self, r)
}
"v_rsq_f32" | "v_sqrt_f32" | "v_log_f32" | "v_exp_f32" | "v_fract_f32"
@@ -10512,9 +10718,7 @@ impl<'a> Lower<'a> {
let both = self.exchange_pairs(&[has, mine]);
(both[0], both[1])
} else {
- let has = self.exchange_halves(c, has)?;
- let c = self.cur;
- (has, self.exchange_halves(c, mine)?)
+ self.exchange_halves_two(has, mine)?
};
let c = self.cur;
let z = self.s.m.i32(0);
@@ -11085,7 +11289,7 @@ impl<'a> Lower<'a> {
"v_rcp_f16" => {
let a = self.half_fsrc(inst, 0)?;
let one = self.s.m.f32(1.0f32.to_bits());
- self.s.m.bin(c, Bin::SDiv, one, a)
+ self.s.m.fdiv_arcp(c, one, a)
}
_ => {
let a = self.half_fsrc(inst, 0)?;
@@ -11537,8 +11741,7 @@ impl<'a> Lower<'a> {
}
"v_bfe_u32" | "v_bfe_i32" => {
let (a, off, w) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
- let w = m31(self, w);
- self.bfe(a, off, w, name == "v_bfe_i32")
+ self.bfe(a, off, w, name == "v_bfe_i32", true)
}
"v_bfi_b32" => {
let (m, a, b) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs
index 3b7e312..a780fb3 100644
--- a/crates/victory-shader/src/emit/mod.rs
+++ b/crates/victory-shader/src/emit/mod.rs
@@ -145,7 +145,7 @@ pub use rect::rect_list_gs;
pub use shader::{
MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, PAIR_MISS_ENTRIES, ROOT_CBV_SPACE, SAMPLED_MARKS, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEET, SLOT_MEMORY, SLOT_PAIR_MISSES, SLOT_SAMPLED, SLOT_STRIDES, SLOT_TLAS_BASE, SLOT_TLAS_MAX,
SLOT_STRIDES_COUNT, SLOT_TABLE_STRIDES, SLOT_VIEW_ADDRESSES, USER_DATA_SPACE, VIEW_INTEGER, VIEW_SIGNED, VIEW_STRIDE_BITS, USER_DISPATCH_THREADS_X, USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS, USER_PIXEL_MASK,
- constants_raw, program_key, raw_views, set_raw_views, set_view_heap_limit, view_heap_limit,
+ USER_TITLE_VIEWS, constants_raw, program_key, raw_views, set_raw_views, set_view_heap_limit, view_heap_limit,
};
/// The loop limit without an override: 2^20.
@@ -512,7 +512,7 @@ pub fn rdna_float() -> u32 {
static BITS: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
*BITS.get_or_init(|| {
let value = std::env::var("VICTORY_RDNA_FLOAT").ok();
- parse_set(value.as_deref(), rdna::ALL, rdna::ALL)
+ parse_set(value.as_deref(), rdna::ALL, rdna::ALL_EXTENDED)
})
}
@@ -530,7 +530,15 @@ pub mod rdna {
pub const MED3: u32 = 4;
/// `v_fract_f32`: the host's Frc as it is.
pub const FRACT: u32 = 8;
+ /// Opt-in (`VICTORY_RDNA_FLOAT` bit 4 = 16): `v_mul_legacy_f32` lowers to
+ /// a plain `fmul` without the 0*NaN/Inf guard (1 op instead of 6).
+ pub const LEGACY_PLAIN: u32 = 16;
+ /// Opt-in (`VICTORY_RDNA_FLOAT` bit 5 = 32): `v_sin_f32` / `v_cos_f32`
+ /// lower to `Sin/Cos((x - Round_ne(x)) * 2*pi)` without the `-0` and exact
+ /// quarter/half-turn `select` guards (3 ops instead of 9).
+ pub const TRIG_PLAIN: u32 = 32;
pub const ALL: u32 = 15;
+ pub const ALL_EXTENDED: u32 = ALL | LEGACY_PLAIN | TRIG_PLAIN;
}
/// A switch's set of bits; `unset` when it is unset or unreadable. Pure, for
@@ -754,7 +762,7 @@ pub fn emit(
&& std::env::var_os("VICTORY_LDS_WRITE_ONLY_OK").is_none()
&& let Ok(shader) = lds::with_known_write_only_retry(|| emit_with_loop_retry(c, native, p, st, io, res))
{
- if std::env::var_os("VICTORY_WAVE_WHY").is_some() {
+ if wave_why() {
eprintln!("WAVE64-RETRY known write-only LDS kernel: wave Some(32)");
}
return Ok(shader);
@@ -795,7 +803,7 @@ fn emit_with_loop_retry(
LOOPS_OFF.with(|off| off.set(false));
match again {
Ok(shader) => {
- if std::env::var_os("VICTORY_WAVE_WHY").is_some() {
+ if wave_why() {
eprintln!("WAVE-LOOPS left out: the program translates without them");
}
Ok(shader)
@@ -862,6 +870,11 @@ fn with_wide_fallback<T>(f: impl FnOnce() -> T) -> T {
/// their gather, the shadow and decal classification, the TAA and reflection resolves, the
/// particles; 2026-11-28). Unlike `VICTORY_WAVE_WIDE=1`, the programs that translate without it
/// are left as they are (that switch lost the card on two of those).
+fn wave_why() -> bool {
+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var_os("VICTORY_WAVE_WHY").is_some())
+}
+
fn wide_fallback_on() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_WAVE_WIDE_FALLBACK").is_none_or(|v| v != "0"))
@@ -892,7 +905,7 @@ fn emit_strict(
// on its own)
let exact_only = matches!(&original, Err(ShaderError::Unsupported { what, .. }) if *what == lower::MASK_ELSEWHERE);
if stuck && native.stage == HwStage::Cs && native.wave64 && lower::host_max_wave() == 32 {
- let why = std::env::var_os("VICTORY_WAVE_WHY").is_some();
+ let why = wave_why();
if why {
// (the digest names the program in `scene_kernel` below)
eprintln!("WAVE64-SHADER digest={:02x?}", c.digest);
@@ -1228,7 +1241,7 @@ fn emit_strict(
&& what == lower::LANE_MASK
&& std::env::var_os("VICTORY_WAVE_WIDE").is_none_or(|v| v != "0") =>
{
- let again = widen(c, native, p, std::env::var_os("VICTORY_WAVE_WHY").is_some(), WidenMode::All, false);
+ let again = widen(c, native, p, wave_why(), WidenMode::All, false);
match again {
Ok(_) => again,
Err(_) => emit_program(c, native, p, st, io, res),
@@ -1852,7 +1865,7 @@ fn emit_program(
let res = resource::track(p, &native.layout, native.stage, Some(&st))?;
emit_program_plain(c, native, p, &st, io, &res)
});
- let why = std::env::var_os("VICTORY_WAVE_WHY").is_some();
+ let why = wave_why();
match again {
Ok((shader, Some(w))) if w <= *wave && !too_wide(Some(w)) => {
if why {
diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs
index b0746d8..e5e9575 100644
--- a/crates/victory-shader/src/emit/shader.rs
+++ b/crates/victory-shader/src/emit/shader.rs
@@ -155,6 +155,17 @@ pub const USER_DISPATCH_THREADS_X: u32 = 0x106;
/// console's `OMSetSampleMaskX` gives 16 sample bits a pixel; a host target of
/// one sample keeps a pixel when its sample 0 bit is set.
pub const USER_PIXEL_MASK: u32 = 0x108;
+/// `RootType::Other` code of a user-data dword the host sets at every bind
+/// of a program that picks views from the resource heap by an index it
+/// computes: how many of the bound view heap's slots are the title's own on
+/// the host (`u32::MAX`: no bound). A picked index at or past it reads the
+/// null slot at the heap's end ([`set_view_heap_limit`]) instead of what the
+/// host keeps past the title's slots. Past them lie the host's dynamic slots,
+/// the tables it makes afresh for draws: on a heap capped at 1,000,000 views
+/// (NVIDIA) the title's 1,245,184 do not fit, and an index of the title's
+/// between the 606,783 that do and the null slot read whatever table another
+/// draw had there, a texture's view read as a buffer's among them.
+pub const USER_TITLE_VIEWS: u32 = 0x109;
/// `ShaderFlags` bits (metadata) and their `SFI0` feature bits.
pub(crate) mod flags {
@@ -259,8 +270,18 @@ pub fn set_view_heap_limit(null_slot: u32) {
VIEW_LIMIT.store(null_slot, std::sync::atomic::Ordering::Relaxed);
}
+#[cfg(test)]
+thread_local! {
+ /// For a test's thread alone: [`view_heap_limit`].
+ pub(crate) static VIEW_LIMIT_HERE: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
+}
+
/// See [`VIEW_LIMIT`]: the null slot shaders translated now clamp view indices to (0: none).
pub fn view_heap_limit() -> u32 {
+ #[cfg(test)]
+ if let Some(null) = VIEW_LIMIT_HERE.get() {
+ return null;
+ }
VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed)
}
@@ -440,15 +461,10 @@ impl Shader {
opcode: u32,
args: &[V],
) -> V {
- let mut params = vec![self.t.i32];
- params.extend(args.iter().map(|&a| self.m.type_of(a)));
- let fty = self.m.func_ty(ret, params);
- self.m.ptr(fty);
- let f = self
- .m
- .function(&format!("dx.op.{name}"), fty, Some(attr), false);
- let mut all = vec![self.m.i32(opcode)];
- all.extend(args);
+ let f = self.m.dx_op(name, ret, attr, self.t.i32, args);
+ let mut all = Vec::with_capacity(1 + args.len());
+ all.push(self.m.i32(opcode));
+ all.extend_from_slice(args);
self.m.call(block, f, all)
}
diff --git a/crates/victory-shader/src/emit/size_tests.rs b/crates/victory-shader/src/emit/size_tests.rs
index e684ade..f397843 100644
--- a/crates/victory-shader/src/emit/size_tests.rs
+++ b/crates/victory-shader/src/emit/size_tests.rs
@@ -422,6 +422,85 @@ fn a_picked_buffer_is_read_at_its_raw_twin() {
}
}
+/// A view picked from the heap by an index at or past the title's slots on
+/// the host (`USER_TITLE_VIEWS`, which the host sets at each bind) reads the
+/// null slot at the heap's end, not what the host keeps past the title's
+/// slots: there lie the tables it makes afresh for other draws (#3222: a
+/// dispatch that picks buffers by indices in records hung the card). Tables
+/// are not held to it. Without a null slot nothing changes.
+#[test]
+fn a_picked_view_past_the_titles_slots_reads_the_null_slot() {
+ use super::host::{Dispatch, Host, Root};
+ use super::shader::{USER_TITLE_VIEWS, VIEW_LIMIT_HERE};
+ let program = |at: u32| {
+ let words = [
+ 0xBE86_0301, // s_mov_b32 s6, s1
+ 0xBE87_0380, // s_mov_b32 s7, 0
+ 0xBE8C_03FF, // s_mov_b32 s12, at
+ at,
+ 0xF408_0203, // s_load_dwordx4 s[8:11], s[6:7], s12
+ 0x1800_0000,
+ 0xE030_0004, // buffer_load_dword v5, off, s[8:11], 0 offset:4
+ 0x8002_0500,
+ 0x7E0A_0505, // v_readfirstlane_b32 s5, v5
+ 0xBE84_0380, // s_mov_b32 s4, 0
+ ];
+ [TABLE, &words, STORE].concat()
+ };
+ let title_word = |shader: &HostShader| {
+ shader.user_data.iter().find(|u| u.root == RootType::Other(USER_TITLE_VIEWS)).map(|u| u.index)
+ };
+ // No host limit: the program as before, without the word.
+ let plain = build(&program(32 * 3), (8, 0)).expect("translates");
+ assert_eq!(title_word(&plain), None);
+ // Slots 0 to 2 the title's (2: the table's UAV), 3 a dynamic one, 5 null.
+ const NULL: u32 = 5;
+ VIEW_LIMIT_HERE.set(Some(NULL));
+ let built = [32, 32 * 3, 32 * 1000].map(|at| build(&program(at), (8, 0)));
+ VIEW_LIMIT_HERE.set(None);
+ let shaders = built.map(|b| b.expect("translates"));
+ for s in &shaders {
+ assert!(title_word(s).is_some(), "a picked view asks for the title's slots");
+ }
+ let (title, dynamic, null, texel) = ([1u32, 2, 3, 4], [5u32, 6, 7, 8], [0u32; 4], [[0.0; 4]; 1]);
+ let raw = |data| View::Buffer { data, stride: Stride::Raw };
+ let views = [
+ View::Texture(1, 1, &texel),
+ raw(&title),
+ View::RawUav(2),
+ raw(&dynamic),
+ View::Texture(1, 1, &texel),
+ raw(&null),
+ ];
+ let _serial = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
+ for (label, warp) in [("hardware", false), ("WARP", true)] {
+ let Ok(host) = Host::new(warp) else {
+ eprintln!("no SM 6.6 {label} device; skipped");
+ continue;
+ };
+ // (the program, the title slots the host says, the dword it reads)
+ for (shader, titles, want) in [
+ (&shaders[0], 3, 2),
+ (&shaders[1], 3, 0),
+ (&shaders[1], 4, 6),
+ (&shaders[1], u32::MAX, 6),
+ (&shaders[2], 3, 0),
+ ] {
+ let (root, pso) = host.compute_pipeline(shader).expect("create compute pipeline");
+ let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
+ ud[title_word(shader).unwrap() as usize] = titles;
+ let dispatch = Dispatch {
+ roots: vec![(0, Root::Constants(ud))],
+ views: &views,
+ samplers: &[],
+ groups: [1, 1, 1],
+ };
+ let got = host.dispatch(&root, &pso, &dispatch).expect("dispatch");
+ assert_eq!(got[0][..2], [0, want], "{label}: title slots {titles}");
+ }
+ }
+}
+
/// A table's buffer read as raw bytes is read at its raw twin too.
#[test]
fn a_tables_raw_buffer_is_read_at_its_raw_twin() {
diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs
index 37ec86e..1512806 100644
--- a/crates/victory-shader/src/emit/valu_tests.rs
+++ b/crates/victory-shader/src/emit/valu_tests.rs
@@ -2994,6 +2994,50 @@ fn v_mov_and_cndmask_b32_modifiers_are_bitwise() {
});
}
+#[test]
+fn rcp_arcp_matches_rdna2_accuracy_and_specials() {
+ // v_rcp_f32 v0, v1 (VOP1 opcode 0x02a).
+ let shader = build_valu_cs(&[vop1(0x02a, 0, vgpr(1))]);
+ let inputs: &[f32] = &[
+ 1.0,
+ -1.0,
+ 2.0,
+ -0.5,
+ 3.0,
+ -7.0,
+ 0.123_456_79,
+ 1e-20,
+ 1e20,
+ 0.0,
+ -0.0,
+ f32::INFINITY,
+ f32::NEG_INFINITY,
+ f32::NAN,
+ ];
+ let cases: Vec<[u32; 4]> = inputs.iter().map(|&x| [x.to_bits(), 0, 0, 0]).collect();
+ run_cases(&shader, &cases, |backend, i, _, got| {
+ let x = inputs[i];
+ let y = f32::from_bits(got);
+ if x.is_nan() {
+ assert!(y.is_nan(), "{backend}: v_rcp_f32(NaN) = {y} ({got:#010x})");
+ } else if x == 0.0 {
+ let want = if x.is_sign_negative() { f32::NEG_INFINITY } else { f32::INFINITY };
+ assert_eq!(got, want.to_bits(), "{backend}: v_rcp_f32({x:?}) = {y:?} ({got:#010x})");
+ } else if x.is_infinite() {
+ let want = if x.is_sign_negative() { -0.0f32 } else { 0.0f32 };
+ assert_eq!(got, want.to_bits(), "{backend}: v_rcp_f32({x:?}) = {y:?} ({got:#010x})");
+ } else {
+ let exact = 1.0f32 / x;
+ let ulp = got.abs_diff(exact.to_bits());
+ assert!(
+ ulp <= 1,
+ "{backend}: v_rcp_f32({x}) = {y} ({got:#010x}), exact {exact} ({:#010x}), ulp={ulp}",
+ exact.to_bits(),
+ );
+ }
+ });
+}
+
mod cost_checks;
/// SOP1 `op sdst, src0`.
diff --git a/crates/victory-shader/src/structure.rs b/crates/victory-shader/src/structure.rs
index aed8d81..df346fe 100644
--- a/crates/victory-shader/src/structure.rs
+++ b/crates/victory-shader/src/structure.rs
@@ -67,11 +67,13 @@ pub struct Bools {
}
/// The tables below have small integer keys; SipHash dominated run time.
-type Map<K, V> = HashMap<K, V, BuildHasherDefault<Fx>>;
+pub(crate) type FxMap<K, V> = HashMap<K, V, BuildHasherDefault<Fx>>;
+pub(crate) type FxSet<T> = HashSet<T, BuildHasherDefault<Fx>>;
+type Map<K, V> = FxMap<K, V>;
/// FxHash's multiply-rotate step.
#[derive(Default)]
-struct Fx(u64);
+pub(crate) struct Fx(u64);
impl Hasher for Fx {
fn finish(&self) -> u64 {
@@ -143,14 +145,16 @@ impl Bools {
}
fn vars(&self, b: Bool) -> Vec<u32> {
- let (mut seen, mut vars, mut stack) = (Vec::new(), Vec::new(), vec![b]);
+ let mut seen = FxSet::default();
+ let mut var_set = FxSet::default();
+ let mut vars = Vec::new();
+ let mut stack = vec![b];
while let Some(b) = stack.pop() {
let (v, lo, hi) = self.nodes[b.0 as usize];
- if v == TERMINAL || seen.contains(&b) {
+ if v == TERMINAL || !seen.insert(b) {
continue;
}
- seen.push(b);
- if !vars.contains(&v) {
+ if var_set.insert(v) {
vars.push(v);
}
stack.extend([lo, hi]);