Repository navigation
Shaders: split flat byte-offset accesses to structured buffers - #984
CitizenCinema wants to merge 1 commit into
Conversation
Table-bound structured buffers carry StructureByteStride on the host descriptor. Flat byte-offset scalar loads (s_buffer_load_dword*) and non-idxen buffer loads/stores/atomics previously annotated these handles as ByteAddressBuffer (11, 0), causing NVIDIA drivers to bounds-check offsets >= stride to 0 (reproducing the RTX 5090 hit-detection TDR hang). Annotate table-bound structured buffers as (12 | uav, stride) and split flat byte addresses into (addr / stride, addr % stride); keep root descriptors raw (11, 0).
Table-bound structured buffers carry StructureByteStride on the host descriptor. Flat byte-offset scalar loads and non-idxen buffer loads, stores and atomics went through a raw handle, whose offsets NVIDIA checks against the stride: elements past the first read zeros (upstream traced a 4.9 s DEVICE_HUNG in a hit-detection compute pass to it). Use a structured handle and split each byte address into (address / stride, address % stride), one dword at a time. Root views stay raw. From upstream PR Marvisak#984 (5011645), hand-ported. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
…ueries smem() splits scalar loads of a structured table SRV into record and offset (Marvisak#984 port), but descriptor_data() made the size query's handle for the same slot a raw view: two kinds for one descriptor, and word 2 reported bytes where the record count was read. Use the structured stride there too. Idea from upstream PR Marvisak#995 (89b6c67, Jeremy Goldberg); its PSV declaration check is not ported (our structured choice follows the table binding as in Marvisak#984). Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
RTX 5080 (Blackwell, Wave32) A/B Verification of #984 + #986 + #452 (+ #946, #948, #688)Environment:
Runs:
Takeaways:
|
… menus on NVIDIA Marvisak#984 reads table-bound buffers with a static stride taken from the shader's resource metadata (12 | uav, stride) and splits byte offsets into (index, offset). The view the title actually makes need not have that stride: the menu's final composite (VS 0602c2384acbb3b2) loads its matrices with s_buffer_load from a view whose host stride differs from the declared 64, every load returned 0, the rectangle collapsed and the presented frame was black while the menu itself rendered. This tree already reads such buffers through raw aliases of the same bytes (Marvisak#704), which is what Marvisak#984 set out to fix. Back to raw handles: the menu reaches the screen again (frame 2100 captured with and without).
…do console window)
|
In-game data for this PR on an RTX 4070 (Windows 11): diagnostics build, Series X mode,
So 2 of 2 hung in that dispatch without this PR and 3 of 3 ran to the time limit with it, which fits your reading of the second dispatch. Caveat: between the two groups #1019 also went from its first commit to its full head (which adds unordered views off an element), so this is not an A/B of this PR alone. |
|
RTX 2070 SUPER (Turing, Wave32), driver 617.42, Windows 11: this PR + Diag build, Series X mode,
So on this card the scalar split alone is not enough. The flat vector-load part of this PR, the unaligned-view companion, or both are needed. Two details from the hung runs:
Synthetic check of the underlying mismatch on the same GPU: a raw No game data attached. AI-assisted (Claude Code). |
|
Reviewed on Windows 11 / Rust 1.98.1, The test pins the bug, red and green. With i.e. the flat byte-offset load at byte 24 of a 56-byte-stride structured buffer read a dword out of element 0 instead of element 0's later bytes — exactly "elements past the first are dropped". With the branch's lowering it passes. The test is also the right shape: the same dword read two ways (indexed What I checked in the lowering, and it held. Two things worth a second look, neither blocking.
Bottom line: the defect is real, the test proves it both ways, and the lowering is consistent with the indexed path it mirrors. The only open question is the alignment assumption for sub-dword flat accesses. |
|
I found a scalar vertex-buffer case worth covering alongside the structured-host-view compute test. On a physical RTX 5070, a draw-side observer matched the active vertex shader by its guest container and inspected its selected graphics root table (slot 0, offset 0). The title supplied a buffer SRV with Offline replay of that exact shader on This provides a concrete input for the raw-host-view concern in #437. For a synthetic regression test, the observed combination is a 64-byte guest stride with a 32-DWORD raw host SRV. The descriptor observation and translation comparison are verified; the effect on the picture has not yet been isolated in a run where only this lowering differs. |
|
Independent confirmation of this root cause from a second shader and GPU. Hardware: RTX 4070 Laptop GPU, Windows 11, title v1.0.2.1, Series X mode. The shader: compute In game: Our fix: we made the same change independently. Unindexed
Your version restricts the change to table-bound resources and also covers stride 4, which is more careful than ours. We'd suggest #984 over a second PR. A GPU test that reproduces it, in case it helps. It runs a scalar load of dword 3 from a 16-byte structured element:
It's at clypeal6/VIctory, branch Related:
AI-assisted (Claude Code). Measured on our own copy of the game. No game data shared. |
Marvisak#984 (Marvisak/VIctory) makes the same change more carefully: table-bound buffers only (a root view has no stride), stride 4 too (raw buffers record 1), and one access per dword. Our version is reverted here and Marvisak#984 merged next. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
resource::track takes no structure here, Parts carries options, the guard user-data dword (Marvisak#483) gets the null slot past the views, and the one-GPU-test-at-a-time lock is shared at module level. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| } | ||
| if !typed | ||
| && index.is_none() | ||
| && let Some(stride) = structured_stride(used) |
There was a problem hiding this comment.
Could we verify that all descriptor choices have the same layout before using this stride? For merged sources, used_kind() takes the first alternative's metadata, while handle() selects the actual descriptor at runtime. If a flat load can select between stride 56 and stride 32, byte offset 80 becomes (1, 24) with the first stride even when the second view is selected; that view needs (2, 16).
Either reject differing layouts during lowering or use each choice's own layout. A two-descriptor regression would cover this; the current stride-56 test already covers reads past the first element. This is from source inspection, not a game repro.
There was a problem hiding this comment.
Follow-up: reproduced on unchanged PR head 501164509d220fd643300e080b8e68bb498ce562, Windows / RTX 2080 Ti, with a synthetic one-thread shader; no game files.
The shader selects between table-bound structured SRVs (strides 56 and 32) via a runtime root constant, then reads byte offset 80 through scalar s_buffer_load_dword and flat vector buffer_load_dword offen.
- Pristine: original test passes, exit 0.
- Mixed strides: hardware choice 0 correct; choice 1 returns
0x00000000for both reads instead of0xb000141b. Original test passes, added test fails, exit 101. - WARP: both choices correct.
- Corrected control: both metadata and actual views use stride 56, each backed by 42 distinctly tagged dwords. Both choices correct on hardware and WARP; 2 tests pass, exit 0.
- Rollback: pristine source hash restored, original test passes, exit 0.
Each scenario started with cargo clean -p victory-shader, then:
cargo test --locked -p victory-shader structured_buffer_flat_byte_offset_loads_reach_elements_past_the_first -- --nocapture
This is a test-only patch, not a compiler fix or an in-game diagnosis. Apply against this head with git -c core.autocrlf=false apply. Expected patched file SHA-256: 1eccfc898b3b6a207e74ea2955f59a268dfabfde183de04a4a61bde543f356af.
AI-assisted (OpenAI Codex); measurements executed locally.
Synthetic regression patch
--- a/crates/victory-shader/src/emit/valu_tests.rs
+++ b/crates/victory-shader/src/emit/valu_tests.rs
@@ -1108,3 +1108,201 @@
}
assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available");
}
+
+#[test]
+fn structured_buffer_flat_byte_offset_loads_reach_elements_past_the_first_mixed_stride() {
+ use super::host::Stride;
+
+ // Select one of two structured SRVs at runtime, then read flat byte offset 80.
+ let mut words = Vec::new();
+ words.push(s_mov_b32(5, 0x80)); // s5 = 0
+ words.extend_from_slice(&s_load_dwordx4(8, 4)); // s[8:11] = UAV at table+0
+ // s_load_dwordx4 s[12:15], s[4:5], 32 (table+8 dwords = slot 1)
+ words.extend_from_slice(&[
+ 0x3D << 26 | 0x02 << 18 | (12 << 6) | (4 >> 1),
+ 125 << 25 | 32,
+ ]);
+ // Slot 2: stride-32 descriptor at table+64.
+ words.extend_from_slice(&[0xF408_0402, 0xFA00_0040]);
+ words.extend_from_slice(&[
+ 0xBF06_8001, // s_cmp_eq_u32 s1, 0
+ 0x8594_100C, // s_cselect_b64 s[20:21], s[12:13], s[16:17]
+ 0x8596_120E, // s_cselect_b64 s[22:23], s[14:15], s[18:19]
+ ]);
+ // s_buffer_load_dword s24, s[20:23], s0
+ words.extend_from_slice(&[0x3D << 26 | 0x08 << 18 | (24 << 6) | (20 >> 1), 0]);
+ words.push(vop1(0x001, 1, sgpr(0))); // v1 = s0 (flat byte offset)
+ // buffer_load_dword v2, v1, s[20:23], 0 offen
+ words.extend_from_slice(&[
+ 0x38 << 26 | 0x0C << 18 | 0x1000,
+ 0x80 << 24 | ((20 >> 2) << 16) | (2 << 8) | 1,
+ ]);
+ words.push(vop1(0x001, 0, sgpr(24))); // v0 = s24
+ words.extend_from_slice(&buffer_store_dword(0, 8, 0));
+ words.extend_from_slice(&buffer_store_dword(2, 8, 4));
+ words.push(S_ENDPGM);
+
+ let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
+ let native = NativeProgram {
+ stage: HwStage::Cs,
+ wave64: false,
+ vgprs: 4,
+ layout: vec![
+ RootParam {
+ root: RootType::Constants,
+ table_offset_dwords: 0,
+ sgprs: 2,
+ base_register: 0,
+ user_data: 0,
+ slot: 0,
+ },
+ RootParam {
+ root: RootType::Table,
+ table_offset_dwords: 0,
+ sgprs: 1,
+ base_register: 0,
+ user_data: 4,
+ slot: 1,
+ },
+ ],
+ used: vec![
+ UsedResource {
+ kind: ResourceType::Uav,
+ root: RootType::Table,
+ table_offset_dwords: 0,
+ lower_bound: 0,
+ stride: 0,
+ dwords: 4,
+ user_data: 4,
+ slot: 1,
+ },
+ UsedResource {
+ kind: ResourceType::Srv,
+ root: RootType::Table,
+ table_offset_dwords: 8,
+ lower_bound: 0,
+ stride: 56,
+ dwords: 4,
+ user_data: 4,
+ slot: 1,
+ },
+ UsedResource {
+ kind: ResourceType::Srv,
+ root: RootType::Table,
+ table_offset_dwords: 16,
+ lower_bound: 0,
+ stride: 32,
+ dwords: 4,
+ user_data: 4,
+ slot: 1,
+ },
+ ],
+ io: StageIo::Cs(ComputeIo {
+ rsrc2: 5 << 1,
+ threads: [1, 1, 1],
+ }),
+ code,
+ };
+
+ let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
+ let st = structure::structure(&p).expect("structure");
+ let res =
+ resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track");
+ let io = io::raise(&p, &native).expect("io::raise");
+ let lowered = lower::lower(&lower::Parts {
+ native: &native,
+ p: &p,
+ st: &st,
+ io: &io,
+ res: &res,
+ inputs: Vec::new(),
+ outputs: Vec::new(),
+ prims: Vec::new(),
+ mesh_stride: 0,
+ })
+ .expect("lower");
+
+ let shader = HostShader {
+ stage: HwStage::Cs,
+ dxil: lowered.dxil,
+ user_data: lowered.user_data,
+ samplers: lowered.samplers,
+ static_samplers: Vec::new(),
+ root_cbvs: lowered.root_cbvs,
+ root_srvs: lowered.root_srvs,
+ };
+ if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
+ let mut copy = shader.dxil.clone();
+ v.validate(&mut copy).expect("DXIL validation failed");
+ }
+
+ // Distinct per-buffer tags also catch accidental selection of the wrong SRV.
+ let data: Vec<u32> = (0..42u32).map(|i| 0xA000_0000 | (i * 0x101 + 7)).collect();
+ let narrow: Vec<u32> = (0..24u32).map(|i| 0xB000_0000 | (i * 0x101 + 7)).collect();
+ let views = [
+ View::RawUav(2),
+ View::Buffer {
+ data: &data,
+ stride: Stride::Structured(56),
+ },
+ View::Buffer {
+ data: &narrow,
+ stride: Stride::Structured(32),
+ },
+ ];
+
+ let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
+ let mut ran = 0;
+ let mut failures = Vec::new();
+ for (label, warp) in [("hardware", false), ("warp", true)] {
+ let Ok(host) = Host::new(warp) else {
+ eprintln!("{label}: unavailable");
+ continue;
+ };
+ let (root, pso) = host
+ .compute_pipeline(&shader)
+ .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}"));
+ for (choice, input) in [&data, &narrow].into_iter().enumerate() {
+ let byte_off = 80u32;
+ let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
+ for u in &shader.user_data {
+ ud[u.index as usize] = match (u.root, u.slot) {
+ (RootType::Constants, 0) => byte_off,
+ (RootType::Table, 1) => 0,
+ other => panic!("unexpected user data {other:?}"),
+ };
+ }
+ let selector = shader
+ .user_data
+ .iter()
+ .find(|u| u.root == RootType::Constants && u.slot == 0)
+ .expect("constant block")
+ .index as usize + 1;
+ ud[selector] = choice as u32;
+ let out = host
+ .dispatch(
+ &root,
+ &pso,
+ &Dispatch {
+ roots: vec![(0, Root::Constants(ud))],
+ views: &views,
+ samplers: &[],
+ groups: [1, 1, 1],
+ },
+ )
+ .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}"));
+ let want = input[(byte_off / 4) as usize];
+ let (scalar, vector) = (out[0][0], out[0][1]);
+ let msg = format!(
+ "{label}: choice={choice} byte={byte_off} scalar={scalar:#010x} vector={vector:#010x} expected={want:#010x}"
+ );
+ eprintln!("{msg}");
+ if scalar != want || vector != want {
+ failures.push(msg);
+ }
+ }
+ ran += 1;
+ }
+ assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available");
+ assert!(failures.is_empty(), "{}", failures.join("\n"));
+}
|
Automated triage for the maintainers. Needs rebase. This PR does not merge cleanly into current The content has not been reviewed yet; it will be once the branch is rebased onto Generated by Claude Code |
Root cause
Table-bound
StructuredBuffer/RWStructuredBufferdescriptors carryStructureByteStridein the host descriptor heap, andUsedResource.striderecords that stride (>= 4, multiple of 4; rawByteAddressBufferrecordsstride = 1).Previously,
lower.rsonly checkedUsedResource.stridefor indexed (idxen) buffer operations. Flat byte-offset accesses—scalars_buffer_load_dword*insmem()and non-idxenbuffer_load/buffer_store/buffer_atomicinbuffer()—always annotated the handle asByteAddressBuffer((11, 0)) and passed the flat byte offset as the index argument.On NVIDIA D3D12 (tested on RTX 5090), reading a
StructuredBuffer<stride>heap descriptor through aByteAddressBufferhandle bounds-checks any byte offset>= strideto0. In GTA VI'svfx_proj_decal_hit_detection(CS_ComputeHitDetectionSkinnedResults,eeed82b877b44b5f), bufferB(s1+0) is aStructuredBuffer<56>read withs_buffer_load_dword: record 1 (byte_offset = 80 >= 56) returnedbase = 0, causing the shader to readA + 0(which overlaps VIctory's descriptor heap0x45495676view tags), hit the loop abortretbefore a workgroup barrier, and trigger a ~4.9 sDXGI_ERROR_DEVICE_HUNGTDR.Fix
structured_stride(used)incrates/victory-shader/src/emit/lower.rsmatching table-bound resources (RootType::Table) withstride >= 4 && stride % 4 == 0(root descriptors have no D3D12 descriptor stride and stay raw(11, 0)).smem()(handling bothResourceType::SrvandResourceType::Uav) andbuffer()(index == Noneloads, stores, and atomics) to annotate structured handles as(12 | uav, stride)and split each flat byte address into(addr / stride, addr % stride)(one dword at a time for multi-dword loads/stores so cross-element accesses stay in-bounds).structured_buffer_flat_byte_offset_loads_reach_elements_past_the_firstincrates/victory-shader/src/emit/valu_tests.rsverifyings_buffer_load_dwordand flatbuffer_load_dword offenacross elements 0, 1, and 2 of aStructuredBuffer<56>.Verification
cargo test -p victory-shader: 121 passed, 0 failed (including the new regression test on both RTX 5090 hardware and WARP) andcargo test -p victory-gpu: 50 passed, 0 failed.eeed82b877b44b5fwithBbound asStructuredBuffer<56>andA + 0populated with0x45495676tags: previously hungu6 = 1in 4896 ms (DEVICE_HUNG); after fix, bothu6 = 0(61.5 ms) andu6 = 1(52.2 ms) succeed.shaders.rpf(translate --validate --pipelines --list): 21,973 emitted, 21,645 RTX 5090 PSOs created, 0 new DXIL validator errors.fix/unaligned-buffer-srv), GTA VI ran live on RTX 5090 for 8m19s with noVICTORY_SKIP_PIPELINES(0 slow submissions, 0 GPU hangs,eeed82b877b44b5fexecuting cleanly acrossu6 = 0andu6 = 1every frame).