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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,11 @@ Fork: MagiccConch/VIctory, upstream: Marvisak/VIctory. CI: windows-latest only (
- Key upstream fixes now in the fork: copy-back page marks via shader view writes (cd94d35) — touches `crate::memory` copy-back and `emit::HostShader::view_marks` (new `Parts::view_marks`, `Options::view_marks`, `HostShader::view_marks`; test initializers must set it); descriptor cursor range (c6c244d) + dynamic wraparound scan (c1c3281); swap-chain throttle (f096774); TDR log (42961e8, `crate::tdr::log` — called beside our adapter-by-preference in `victory-gpu/src/host.rs`); device-removed reason (13185f5); no-GPU skip for hardware-only shader checks (42363ab/ccfb029: `hardware_adapter` requires DedicatedVideoMemory > 0).
- Conflict resolutions: `victory-gpu/src/host.rs` ours+tdr::log; `texture.rs` tests both suites; `apu.rs` ours (both fixed the same misaligned-output UB; ours cross-checks interleaved vs deinterleaved); `emit/host.rs` kept BOTH `adapter_name` (ours, pub) and `hardware_adapter` (upstream); `emit/lower.rs` took `view_marks: false`, deduped identical `helper_reads_own` (merge doubled it), added `view_marks` to test `Parts`/`HostShader` initializers.
- NOTE: local mingw test-run blocked (`/EXPORT:D3D12SDKPath` link args — MSVC-only Agility exports); local signal = check+clippy+test --no-run on x86_64-pc-windows-gnu, real tests in CI.

## Capped view heaps: upstream PR #1133 ported (2026-11-25)

- The 5080 run's "title slot past the host heap index~1179606 count=934464" flood + 0xc0000005 could NOT be fixed by 6ac8fbe's fallback ladder alone: on a 1,000,000-slot driver cap every rung keeping the full title range (count+DYNAMIC=1441792, count+MIN_DYNAMIC=1245184) still fails, so the heap lands on the PORTABLE_VIEWS cap path and title slots [934464, 1179648) read null descriptors.
- Upstream PR #1133 (cae16e60, rivaldodev) fixes this: probe `PORTABLE_VIEWS + 1` at device creation (`descriptor::host::view_heap_cap`); when refused, `victory-shader::emit::set_view_heap_limit(1_000_000)` and translated shaders clamp `createHandleFromHeap` indices to cap-1. The heap's last slot stays null (out of title slots, dynamic slots, copy-back pairs via `pairs_end`), so past-cap indices read nothing instead of faulting. The cap joins the shader-cache key (`shader_cache.rs::build()` initializes the host first).
- Ported as fork PR #11 (branch new-cap, commit b8388e9d, CI 45545098162 green, mergeable CLEAN). Merge conflict was only the heap-size chain in descriptor/host.rs: kept BOTH upstream's `.max(views)` rungs first (small title heaps must span the full capped range) AND the fork's 6ac8fbe plain rungs (`count + DYNAMIC`, `count + MIN_DYNAMIC`), then the cap path. Guard arithmetic: when `cap == Some(count + DYNAMIC)` (or `+MIN_DYNAMIC`), the matching `.max(views)` rung always succeeds first, so the plain rungs can never hide a needed guard trim.
- Mingw test-run limitation confirmed — WSL interop intercepts the .exe (`UtilGetPpid` error); local signal stays check+clippy+test --no-run on x86_64-pc-windows-gnu.
- After merging to main: rebuild, re-run pre-build (pipeline library rebuilds — emitted shaders change with the new clamp constant), then run the title. Expect the `host view heaps capped` info line, no slot-past-heap flood, and no null-write crash at world entry. Old cache dirs are keyed out automatically (cap in the key).
90 changes: 79 additions & 11 deletions crates/victory-gpu/src/descriptor/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,23 @@ pub(crate) fn near_heaps(va: u64) -> String {
/// tiers 1 and 2; tier 3 hardware may take more.
const PORTABLE_VIEWS: u32 = 1_000_000;

/// The size of a capped view heap if `device` takes no larger
/// shader-visible view heap (NVIDIA), else `None`. Translated shaders keep
/// their view indices below it (`set_view_heap_limit`), and a capped heap
/// keeps its last slot null for them.
pub(crate) fn view_heap_cap(device: &ID3D12Device) -> Option<u32> {
// SAFETY: plain heap creation, released at once.
let larger = unsafe {
device.CreateDescriptorHeap::<ID3D12DescriptorHeap>(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
NumDescriptors: PORTABLE_VIEWS + 1,
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
NodeMask: 0,
})
};
larger.is_err().then_some(PORTABLE_VIEWS)
}

/// Slots past the title's in a view heap, for tables a draw needs made
/// afresh (constant buffers copied per draw). A list holds the slots it
/// took until it is reset (its submissions have run) or released.
Expand Down Expand Up @@ -137,9 +154,14 @@ impl HostHeap {
.flatten();
// The larger dynamic range only where the host takes it on top of
// every title slot; else the smaller one, and the cap after that.
// Translated shaders clamp their indices below `HEAP_VIEWS` or
// `HEAP_SAMPLERS`: slots up to there exist and stay null.
let (views, samplers) = (victory_shader::emit::HEAP_VIEWS, victory_shader::emit::HEAP_SAMPLERS);
// Translated shaders clamp below the host cap (or `HEAP_VIEWS`),
// samplers below `HEAP_SAMPLERS`: every such slot must exist. The
// cap's last slot stays null, including for dynamic and pair views.
let cap = victory_shader::emit::view_heap_limit();
let views = cap
.unwrap_or(victory_shader::emit::HEAP_VIEWS)
.min(victory_shader::emit::HEAP_VIEWS);
let samplers = victory_shader::emit::HEAP_SAMPLERS;
let (heap, count, extra) = if sampler {
match make(count.max(samplers)) {
Ok(heap) => (heap, count, 0),
Expand All @@ -149,24 +171,38 @@ impl HostHeap {
}
}
} else if let Ok(heap) = make((count + DYNAMIC).max(views)) {
(heap, count, DYNAMIC)
// A host that takes every slot on top of the larger dynamic
// one; a capped one whose cap fits them keeps its last slot
// out of the dynamic range instead.
(heap, count, DYNAMIC - u32::from(cap == Some(count + DYNAMIC)))
} else if let Ok(heap) = make(count + DYNAMIC) {
// A host that allows the title's whole range beside the larger
// dynamic one, though below `HEAP_VIEWS` (NVIDIA): every title
// slot mirrored.
(heap, count, DYNAMIC)
} else if let Ok(heap) = make((count + MIN_DYNAMIC).max(views)) {
// The same for the smaller dynamic range.
(heap, count, MIN_DYNAMIC - u32::from(cap == Some(count + MIN_DYNAMIC)))
} else if let Ok(heap) = make(count + MIN_DYNAMIC) {
(heap, count, MIN_DYNAMIC)
} else {
// shortcut: a host that caps its heaps below the title's range
// (NVIDIA) faults on an index past them, as before the clamp.
match make(count + MIN_DYNAMIC) {
Ok(heap) => (heap, count, MIN_DYNAMIC),
Err(e) if count + MIN_DYNAMIC > PORTABLE_VIEWS => {
Err(_e) if count + MIN_DYNAMIC > PORTABLE_VIEWS => {
// shortcut: descriptors past the host's limit are left
// out; a title that reaches them needs remapping.
tracing::warn!(error = %e, count, "host view heap capped at {PORTABLE_VIEWS}");
(make(PORTABLE_VIEWS).ok()?, PORTABLE_VIEWS - MIN_DYNAMIC, MIN_DYNAMIC)
// out; a title that reaches them needs remapping. A
// shader's index past the heap reads its last slot,
// which no view takes (translated shaders clamp to it).
match make(PORTABLE_VIEWS) {
Ok(heap) => {
tracing::warn!(count, "host view heap capped at {PORTABLE_VIEWS}");
(heap, PORTABLE_VIEWS - MIN_DYNAMIC, MIN_DYNAMIC - 1)
}
Err(e) => {
tracing::warn!(error = %e, count, sampler, "no host descriptor heap");
return None;
}
}
}
Err(e) => {
tracing::warn!(error = %e, count, sampler, "no host descriptor heap");
Expand Down Expand Up @@ -205,6 +241,7 @@ impl HostHeap {
pairs: Mutex::new((count + extra, Vec::new())),
pairs_end: match victory_shader::emit::NULL_BUFFER_VIEW {
null if !sampler && null > count + extra && null < total => null - 1,
_ if !sampler && cap == Some(total) => total - 1,
_ => total,
},
strides,
Expand Down Expand Up @@ -1480,6 +1517,33 @@ mod tests {
assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok());
}

/// A view heap the host caps keeps its last slot out of title and
/// dynamic slots: translated shaders clamp their indices to it.
#[test]
fn a_capped_view_heap_keeps_its_last_slot_null() {
let Some(host) = host() else {
return; // no host GPU
};
let Some(cap) = view_heap_cap(&host.device) else {
return; // the host takes larger heaps
};
let heap = HostHeap::new(false, cap + 1).expect("a capped view heap");
assert_eq!(heap.count + heap.dynamic, cap - 1);
let last = heap.dynamic(heap.dynamic).unwrap() + heap.dynamic - 1;
assert!(last < cap - 1);
assert_eq!(heap.pairs_end, cap - 1);
// Small title heaps must cover the same shader-visible range too.
let small = HostHeap::new(false, 4).expect("a small capped view heap");
// SAFETY: a plain query of a live heap.
assert_eq!(unsafe { small.heap.GetDesc().NumDescriptors }, cap);
assert!(small.count + small.dynamic < cap);
assert_eq!(small.pairs_end, cap - 1);
// A dynamic range ending exactly at the cap also leaves a guard.
let exact = HostHeap::new(false, cap - DYNAMIC).expect("an exact capped view heap");
assert_eq!(exact.count + exact.dynamic, cap - 1);
assert_eq!(exact.pairs_end, cap - 1);
}

/// Dynamic slots stay taken until given back, and runs do not wrap.
#[test]
fn dynamic_slots_are_held_until_released() {
Expand All @@ -1490,7 +1554,11 @@ mod tests {
// `HEAP_VIEWS`, `HEAP_SAMPLERS`).
// SAFETY: plain queries of live heaps.
unsafe {
assert!(heap.heap.GetDesc().NumDescriptors >= victory_shader::emit::HEAP_VIEWS);
assert!(
heap.heap.GetDesc().NumDescriptors
>= victory_shader::emit::view_heap_limit()
.unwrap_or(victory_shader::emit::HEAP_VIEWS)
);
let samplers = HostHeap::new(true, 128).unwrap();
assert!(samplers.heap.GetDesc().NumDescriptors >= victory_shader::emit::HEAP_SAMPLERS);
}
Expand Down
4 changes: 4 additions & 0 deletions crates/victory-gpu/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,10 @@ fn create() -> windows::core::Result<Host> {
crate::tdr::log();
}
let device = device.ok_or_else(windows::core::Error::empty)?;
if let Some(cap) = crate::descriptor::host::view_heap_cap(&device) {
victory_shader::emit::set_view_heap_limit(cap);
tracing::info!(cap, "host view heaps capped: translated shaders keep their view indices below the cap");
}
let messages = debug
.then(|| device.cast::<ID3D12InfoQueue>().ok())
.flatten();
Expand Down
33 changes: 24 additions & 9 deletions crates/victory-gpu/src/shader_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ static MISSES: AtomicU64 = AtomicU64::new(0);

/// Keeps translated shaders in a folder of `dir` from now on: the folder
/// of this translator, `None` if it cannot be opened.
///
/// Computing the folder name calls [`build`], which initializes the host
/// device (`crate::host::host`) if it does not exist yet so the host's
/// view heap cap is known before the cache key is fixed.
pub fn use_shader_cache(dir: PathBuf) -> Option<PathBuf> {
let dir = dir.join(&blake3::Hash::from(*build()).to_hex()[..16]);
match Cache::open(&dir) {
Expand All @@ -53,29 +57,38 @@ pub fn counts() -> (u64, u64) {
/// (`victory_shader::SOURCE_HASH`: its sources, manifest, the lock file and
/// the compiler), the entry's encoding (this file's text) and the
/// translation settings (the loop limit, which a diagnostics build can
/// change at run time).
/// change at run time, and the host view heap cap).
///
/// Side effect: initializes the host device (`crate::host::host`) on first
/// call so the host's view heap cap is probed and recorded before the cache
/// key is computed (e.g. when `use_shader_cache` runs ahead of any GPU
/// work, such as in `victory translate --cache`).
fn build() -> &'static [u8; 32] {
static BUILD: OnceLock<[u8; 32]> = OnceLock::new();
BUILD.get_or_init(|| {
// The host device sets the view heap cap; it must exist first.
let _ = crate::host::host();
let cap = victory_shader::emit::view_heap_limit().unwrap_or(0);
let limit = victory_shader::emit::loop_limit();
if limit != victory_shader::emit::DEFAULT_LOOP_LIMIT {
tracing::warn!(
limit,
"VICTORY_SHADER_LOOP_LIMIT: translated loops stop sooner"
);
}
key(victory_shader::SOURCE_HASH, ENCODING, limit)
key(victory_shader::SOURCE_HASH, ENCODING, limit, cap)
})
}

/// This file, whose `encode` and `decode` define the entries.
const ENCODING: &[u8] = include_bytes!("shader_cache.rs");

fn key(translator: &str, encoding: &[u8], limit: u32) -> [u8; 32] {
fn key(translator: &str, encoding: &[u8], limit: u32, cap: u32) -> [u8; 32] {
let mut h = blake3::Hasher::new();
h.update(translator.as_bytes());
h.update(blake3::hash(encoding).as_bytes());
h.update(&limit.to_le_bytes());
h.update(&cap.to_le_bytes());
*h.finalize().as_bytes()
}

Expand Down Expand Up @@ -435,17 +448,19 @@ mod tests {
/// written before it is read.
#[test]
fn the_key_covers_translator_encoding_and_settings() {
let k = key("0123456789abcdef", b"encoding", 1 << 20);
assert_eq!(k, key("0123456789abcdef", b"encoding", 1 << 20));
assert_ne!(k, key("0123456789abcdee", b"encoding", 1 << 20));
assert_ne!(k, key("0123456789abcdef", b"encoding.", 1 << 20));
assert_ne!(k, key("0123456789abcdef", b"encoding", 1 << 19));
let k = key("0123456789abcdef", b"encoding", 1 << 20, 0);
assert_eq!(k, key("0123456789abcdef", b"encoding", 1 << 20, 0));
assert_ne!(k, key("0123456789abcdee", b"encoding", 1 << 20, 0));
assert_ne!(k, key("0123456789abcdef", b"encoding.", 1 << 20, 0));
assert_ne!(k, key("0123456789abcdef", b"encoding", 1 << 19, 0));
assert_ne!(k, key("0123456789abcdef", b"encoding", 1 << 20, 1_000_000));
assert_eq!(
*build(),
key(
victory_shader::SOURCE_HASH,
ENCODING,
victory_shader::emit::loop_limit()
victory_shader::emit::loop_limit(),
victory_shader::emit::view_heap_limit().unwrap_or(0)
)
);
// The encoding part is this file as built.
Expand Down
25 changes: 25 additions & 0 deletions crates/victory-shader/src/emit/bitcode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,31 @@ pub(crate) struct Module {
}

impl Module {
/// Evaluates the constant clamp feeding a heap handle in emission tests.
#[cfg(test)]
pub(crate) fn heap_handle_index(&self) -> u32 {
fn eval(m: &Module, v: V) -> u32 {
if let Some(n) = m.int_value(v) {
return n as u32;
}
let V::Inst(i) = v else { panic!("expected a constant clamp") };
match m.insts[i as usize].op {
Op::Cmp(pred::IUGT, a, b) => u32::from(eval(m, a) > eval(m, b)),
Op::Select(c, t, f) => eval(m, if eval(m, c) != 0 { t } else { f }),
_ => panic!("expected a constant clamp"),
}
}
self.insts
.iter()
.find_map(|i| match &i.op {
Op::Call(f, args) if self.funcs[*f as usize].name == "dx.op.createHandleFromHeap" => {
Some(eval(self, args[1]))
}
_ => None,
})
.expect("a heap handle")
}

fn ty(&mut self, def: TypeDef) -> Ty {
if let Some(&t) = self.type_ids.get(&def) {
return Ty(t);
Expand Down
19 changes: 19 additions & 0 deletions crates/victory-shader/src/emit/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,25 @@ pub fn loop_limit() -> u32 {
})
}

/// Size of the host's view heap when the host caps it below the title's
/// (0: not capped).
static VIEW_HEAP_LIMIT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);

/// Translations from now on keep view heap indices below `slots`, the size
/// of a host view heap whose last slot is null. Set before the first
/// translation: the value is part of it, so the shader cache keys on it.
pub fn set_view_heap_limit(slots: u32) {
VIEW_HEAP_LIMIT.store(slots, std::sync::atomic::Ordering::Relaxed);
}

/// The limit [`set_view_heap_limit`] set, if any.
pub fn view_heap_limit() -> Option<u32> {
match VIEW_HEAP_LIMIT.load(std::sync::atomic::Ordering::Relaxed) {
0 => None,
n => Some(n),
}
}

/// `VICTORY_SHADER_LOOP_LIMIT`'s value; the default when it is unset,
/// unreadable or 0. Pure, for testing.
fn parse_loop_limit(value: Option<&str>) -> u32 {
Expand Down
44 changes: 41 additions & 3 deletions crates/victory-shader/src/emit/shader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ pub const VIEW_STRIDES: u8 = 255;
/// this space (see `emit` "Title memory").
pub const MEMORY_SPACE: u32 = 2;
/// Heap indices are clamped below these (views, samplers): the host's heaps
/// are at least this large, the slots past their own null (`emit`, "Heap
/// indices").
/// are at least this large (or the smaller host view cap), the slots past
/// their own null (`emit`, "Heap indices").
pub const HEAP_VIEWS: u32 = 1 << 21;
pub const HEAP_SAMPLERS: u32 = 2048;
/// The heap index of the host's null raw buffer view (the null raw
Expand Down Expand Up @@ -137,6 +137,8 @@ pub(crate) struct Shader {
lds: Option<V>,
main: V,
pub entry: usize,
/// View heap indices stay below this ([`super::view_heap_limit`]).
view_limit: Option<u32>,
}

impl Shader {
Expand Down Expand Up @@ -201,6 +203,7 @@ impl Shader {
lds: None,
main,
entry,
view_limit: super::view_heap_limit(),
}
}

Expand Down Expand Up @@ -535,7 +538,12 @@ impl Shader {
self.heap_props.push(props.0);
// An index past the host's heap faults the device (a console shader
// reads whatever memory follows its heap): the last slot instead.
let last = self.m.i32(if sampler { HEAP_SAMPLERS } else { HEAP_VIEWS } - 1);
let limit = if sampler {
HEAP_SAMPLERS
} else {
self.view_limit.unwrap_or(HEAP_VIEWS).min(HEAP_VIEWS)
};
let last = self.m.i32(limit - 1);
let over = self.m.cmp(block, pred::IUGT, index, last);
let index = self.m.select(block, over, last, index);
let (s, n) = (self.m.bool(sampler), self.m.bool(nonuniform));
Expand Down Expand Up @@ -1004,3 +1012,33 @@ impl Shader {
Some(self.m.md_node(list))
}
}

#[cfg(test)]
mod tests {
use super::{HEAP_SAMPLERS, HEAP_VIEWS, Shader};

fn handle_index(limit: Option<u32>, sampler: bool, index: u32) -> u32 {
let mut s = Shader::new(false);
s.view_limit = limit;
let index = s.m.i32(index);
s.heap_handle(s.entry, index, sampler, false, (0, 0));
s.m.heap_handle_index()
}

/// The actual index passed to DXIL respects the host cap, the upstream
/// view bound and the independent sampler bound, including wraparound.
#[test]
fn heap_handles_stay_inside_the_host_limits() {
for (cap, sampler, limit) in [
(None, false, HEAP_VIEWS),
(Some(1_000_000), false, 1_000_000),
(Some(HEAP_VIEWS + 1), false, HEAP_VIEWS),
(None, true, HEAP_SAMPLERS),
(Some(1_000_000), true, HEAP_SAMPLERS),
] {
for index in [0, limit - 2, limit - 1, limit, 1_200_000, u32::MAX] {
assert_eq!(handle_index(cap, sampler, index), index.min(limit - 1));
}
}
}
}