Skip to content
Draft
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
24 changes: 24 additions & 0 deletions crates/xcl/src/gpu/desc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,30 @@ pub fn sampler_d3d12(w: &[u32; 4], comparison: bool) -> D3D12_SAMPLER_DESC {
}
}

/// Views in the shader-visible heap recompiled shaders index (`ResourceDescriptorHeap` with T#
/// word 0), on every device: the least a resource binding tier 3 GPU has, which SM 6.6
/// dynamic resources need. A constant, so translated shaders do not depend on the device.
pub const VIEW_HEAP_SIZE: u32 = 1_000_000;
/// The texture types recompiled shaders declare (`Texture<type>` / `RWTexture<type>`), in the
/// order of their null views.
pub const NULL_SRV_TYPES: [&str; 7] = ["1D", "2D", "3D", "CubeArray", "1DArray", "2DArray", "2DMS"];
pub const NULL_UAV_TYPES: [&str; 5] = ["1D", "2D", "3D", "1DArray", "2DArray"];
/// The heap's last 12 slots, which no view heap gets: a null SRV of each type in
/// `NULL_SRV_TYPES`, then a null UAV of each in `NULL_UAV_TYPES`. A T# whose word 0 is no heap
/// index reads 0 through the one of the type the shader declares and its writes are dropped
/// (D3D12 needs a null view's dimension to match the declaration).
pub const NULL_VIEWS: u32 = VIEW_HEAP_SIZE - (NULL_SRV_TYPES.len() + NULL_UAV_TYPES.len()) as u32;

/// The null SRV for a texture type of `NULL_SRV_TYPES` ("2D", "CubeArray", …).
pub fn null_srv(ty: &str) -> u32 {
NULL_VIEWS + NULL_SRV_TYPES.iter().position(|&t| t == ty).expect("a texture type with a null SRV") as u32
}

/// The null UAV for a texture type of `NULL_UAV_TYPES`.
pub fn null_uav(ty: &str) -> u32 {
NULL_VIEWS + (NULL_SRV_TYPES.len() + NULL_UAV_TYPES.iter().position(|&t| t == ty).expect("a texture type with a null UAV")) as u32
}

/// The T# as recompiled shaders read it (XCL shader ABI): BASE_ADDRESS – word 0 and the
/// high byte of word 1 – replaced by the descriptor heap index of the SRV (UAV at index + 1);
/// every other field (format, size, swizzle …) stays as the console wrote it.
Expand Down
33 changes: 26 additions & 7 deletions crates/xcl/src/gpu/recomp/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2085,6 +2085,18 @@ impl Em {
};
let t = self.t();
let tw0 = self.sreg(srsrc);
// a T# whose word 0 is no heap index (a console address the title wrote without a view)
// must not read past the heap: RADV faults on the GPU (SQC page fault, device removed).
// Views sit below the null ones in pairs (SRV, UAV at + 1): anything else gets the null
// view of the texture type the declaration names ("2D", "CubeArray", …). So does a T#
// with no image TYPE (word 3 [31:28] < 8): a null view's T# is all zero, and its word 0
// would be the view at index 0.
use crate::gpu::desc::{null_srv, null_uav, NULL_VIEWS};
let views = NULL_VIEWS - 1;
let tw3 = self.sreg(srsrc + 3);
let view = format!("({tw0} < {views}u && {tw3} >= 0x80000000u)");
let srv_i = |ty: &str| format!("({view} ? {tw0} : {}u)", null_srv(ty));
let uav_i = |ty: &str| format!("({view} ? {tw0} + 1u : {}u)", null_uav(ty));
let tw1 = self.sreg(srsrc + 1);
let act = self.act();
let ps = matches!(self.opt.mode, Mode::Pixel(_));
Expand Down Expand Up @@ -2171,7 +2183,7 @@ impl Em {
return Err("MIMG unorm");
}
let samp = if has_c { "SamplerComparisonState" } else { "SamplerState" };
self.line(&format!("{ty} {t}_T = ResourceDescriptorHeap[NonUniformResourceIndex({tw0})];"));
self.line(&format!("{ty} {t}_T = ResourceDescriptorHeap[NonUniformResourceIndex({})];", srv_i(ty.trim_start_matches("Texture").trim_end_matches("<float4>"))));
let sampler = self.sampler_ref(d.pc, has_c, &s3);
self.line(&format!("{samp} {t}_S = {sampler};"));
if let Some(o) = &offset {
Expand Down Expand Up @@ -2275,7 +2287,7 @@ impl Em {
_ => return Err("MIMG dim"),
};
let s3 = self.sreg(ssamp + 3);
self.line(&format!("{ty} {t}_T = ResourceDescriptorHeap[NonUniformResourceIndex({tw0})];"));
self.line(&format!("{ty} {t}_T = ResourceDescriptorHeap[NonUniformResourceIndex({})];", srv_i(ty.trim_start_matches("Texture").trim_end_matches("<float4>"))));
let sampler = self.sampler_ref(d.pc, false, &s3);
self.line(&format!("SamplerState {t}_S = {sampler};"));
self.line(&format!(
Expand All @@ -2298,7 +2310,7 @@ impl Em {
5 => ("Texture2DArray", format!("{t}_T.GetDimensions({mipv}, {t}_w, {t}_h, {t}_d, {t}_n);")),
_ => return Err("get_resinfo dim"),
};
self.line(&format!("{ty}<float4> {t}_T = ResourceDescriptorHeap[NonUniformResourceIndex({tw0})];"));
self.line(&format!("{ty}<float4> {t}_T = ResourceDescriptorHeap[NonUniformResourceIndex({})];", srv_i(ty.trim_start_matches("Texture"))));
self.line(&format!("uint {t}_w, {t}_h, {t}_d, {t}_n; {call}"));
self.line(&format!("uint4 {t}_r = uint4({t}_w, {t}_h, {t}_d, {t}_n);"));
let comps2 = comps.clone();
Expand All @@ -2321,12 +2333,19 @@ impl Em {
if dim == 3 && base.starts_with("load") {
return Err("image_load cube");
}
// (SM 6.6 has no RWTexture2DMS)
if dim == 6 && !base.starts_with("load") {
return Err("MIMG 2DMS store");
}
// (a 2DMS T# is only loaded from)
let uav_i = if dim == 6 { String::new() } else { uav_i(rty) };
self.line(&format!("uint {t}_cls = img_cls(({tw1} >> 20) & 0x1FFu);"));
match base {
"load" | "load_mip" => {
self.line(&format!("uint4 {t}_r;"));
let ld = if dim == 6 { format!("{t}_T.Load({icoord}, {})", ic.get(2).cloned().unwrap_or("0u".into())) } else { format!("{t}_T.Load({load_arg})") };
let tex = |vt: &str| format!("Texture{rty}<{vt}4> {t}_T = ResourceDescriptorHeap[NonUniformResourceIndex({tw0})];");
let srv_i = srv_i(rty);
let tex = |vt: &str| format!("Texture{rty}<{vt}4> {t}_T = ResourceDescriptorHeap[NonUniformResourceIndex({srv_i})];");
self.line(&format!(
"if ({t}_cls == 1u) {{ {} {t}_r = {ld}; }} else if ({t}_cls == 2u) {{ {} {t}_r = asuint({ld}); }} else {{ {} {t}_r = asuint({ld}); }}",
tex("uint"),
Expand Down Expand Up @@ -2355,7 +2374,7 @@ impl Em {
});
}
let v4 = format!("uint4({})", vals.join(", "));
let uav = |vt: &str| format!("RWTexture{rty}<{vt}4> {t}_U = ResourceDescriptorHeap[NonUniformResourceIndex({tw0} + 1u)];");
let uav = |vt: &str| format!("RWTexture{rty}<{vt}4> {t}_U = ResourceDescriptorHeap[NonUniformResourceIndex({uav_i})];");
self.line(&format!(
"if ({act}) {{ if ({t}_cls == 1u) {{ {} {t}_U[{icoord}] = {v4}; }} else if ({t}_cls == 2u) {{ {} {t}_U[{icoord}] = (int4){v4}; }} else {{ {} {t}_U[{icoord}] = asfloat({v4}); }} }}",
uav("uint"),
Expand All @@ -2366,7 +2385,7 @@ impl Em {
_ if base.starts_with("atomic_") && matches!(&base[7..], "cmpswap" | "sub" | "inc" | "dec" | "fcmpswap" | "fmin" | "fmax") => {
// the operations without an int view: on the uint texel (CAS loops where needed)
let (v, cmp) = (self.vreg(vdata), self.vreg(vdata + 1));
self.line(&format!("RWTexture{rty}<uint> {t}_U = ResourceDescriptorHeap[NonUniformResourceIndex({tw0} + 1u)];"));
self.line(&format!("RWTexture{rty}<uint> {t}_U = ResourceDescriptorHeap[NonUniformResourceIndex({uav_i})];"));
self.line(&format!("uint {t}_old = 0u;"));
let body = rmw32(&base[7..], &At::Ref(format!("{t}_U[{icoord}]")), &v, &cmp, &format!("{t}_old"), &t).ok_or("image_atomic")?;
self.line(&format!("if ({act}) {{ {body} }}"));
Expand All @@ -2389,7 +2408,7 @@ impl Em {
let v = self.vreg(vdata);
let vt = if signed { "int" } else { "uint" };
let val = if signed { format!("(int){v}") } else { v.clone() };
self.line(&format!("RWTexture{rty}<{vt}> {t}_U = ResourceDescriptorHeap[NonUniformResourceIndex({tw0} + 1u)];"));
self.line(&format!("RWTexture{rty}<{vt}> {t}_U = ResourceDescriptorHeap[NonUniformResourceIndex({uav_i})];"));
self.line(&format!("{vt} {t}_old = 0;"));
self.line(&format!("if ({act}) {{ {op}({t}_U[{icoord}], {val}, {t}_old); }}"));
if f("GLC") == 1 {
Expand Down
6 changes: 5 additions & 1 deletion crates/xcl/src/gpu/recomp/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,8 @@ struct Bound {
/// Create the descriptor heaps (always, so the directly indexed root signature is valid),
/// the test textures and samplers; record the uploads into `list`.
unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, textures: &[TestTexture], samplers: &[TestSampler]) -> Result<Bound, String> {
let n = (2 * textures.len()).max(2) as u32;
// with textures: the heap translated shaders get in a title, with its null views at the end
let n = if textures.is_empty() { 2 } else { crate::gpu::desc::VIEW_HEAP_SIZE };
let heap: ID3D12DescriptorHeap = dev
.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
Expand All @@ -186,6 +187,9 @@ unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, t
let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize;
let sinc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) as usize;
let at = |h: &ID3D12DescriptorHeap, k: usize, step: usize| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: h.GetCPUDescriptorHandleForHeapStart().ptr + k * step };
if !textures.is_empty() {
crate::hle::d3d12x::console_heap::write_null_views(dev, heap.GetCPUDescriptorHandleForHeapStart().ptr, inc);
}
for (j, sm) in samplers.iter().enumerate() {
let mut sd = D3D12_SAMPLER_DESC {
Filter: sm.filter,
Expand Down
97 changes: 97 additions & 0 deletions crates/xcl/src/gpu/recomp/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7187,3 +7187,100 @@ fn fspx_containers_translate_and_compile() {
println!("FSPX: {ok} / {n} translated and compiled");
assert_eq!(ok, n);
}

/// A T# whose word 0 is no heap index (a console address the title wrote without a view) must
/// not index past the shader-visible heap: RADV faulted on the GPU (SQC page fault at heap start
/// + word 0 · 32, device removed) while a retail game streamed its world. Such a T# reads the
/// null SRV at the heap's end (0) and its stores and atomics go to the null UAV (dropped), while
/// a real view next to it still works.
#[test]
fn gpu_image_with_no_heap_index_reads_zero_and_drops_writes() {
if !gpu_ready() {
return;
}
use runner::{TestSampler, TestTexture, TexDim};
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32_UINT};
let mimg = |name: &'static str, f: &[(&str, u64)]| -> Vec<u8> { encode(name, "ENC_MIMG", f, None).unwrap() };
let mut code = Vec::new();
// garbage T# in s[16:23] (SRSRC = 4), S# in s[24:27] (SSAMP = 6); real UAV T# in s[32:39] (8)
code.extend(mimg("IMAGE_SAMPLE_LZ", &[("VDATA", 10), ("VADDR", 0), ("SRSRC", 4), ("SSAMP", 6), ("DMASK", 0xF), ("DIM", 1)]));
code.extend(mimg("IMAGE_LOAD", &[("VDATA", 14), ("VADDR", 3), ("SRSRC", 4), ("DMASK", 0x1), ("DIM", 1), ("UNORM", 1)]));
code.extend(mimg("IMAGE_STORE", &[("VDATA", 6), ("VADDR", 3), ("SRSRC", 4), ("DMASK", 0x1), ("DIM", 1), ("UNORM", 1)]));
code.extend(mimg("IMAGE_ATOMIC_UMAX", &[("VDATA", 7), ("VADDR", 3), ("SRSRC", 4), ("DMASK", 0x1), ("DIM", 1), ("UNORM", 1)]));
// the other texture types, each through its own null view
code.extend(mimg("IMAGE_SAMPLE_LZ", &[("VDATA", 16), ("VADDR", 0), ("SRSRC", 4), ("SSAMP", 6), ("DMASK", 0xF), ("DIM", 2)]));
code.extend(mimg("IMAGE_SAMPLE_LZ", &[("VDATA", 20), ("VADDR", 0), ("SRSRC", 4), ("SSAMP", 6), ("DMASK", 0xF), ("DIM", 3)]));
code.extend(mimg("IMAGE_LOAD", &[("VDATA", 24), ("VADDR", 3), ("SRSRC", 4), ("DMASK", 0x1), ("DIM", 5), ("UNORM", 1)]));
code.extend(mimg("IMAGE_STORE", &[("VDATA", 6), ("VADDR", 3), ("SRSRC", 4), ("DMASK", 0x1), ("DIM", 2), ("UNORM", 1)]));
code.extend(mimg("IMAGE_STORE", &[("VDATA", 6), ("VADDR", 3), ("SRSRC", 8), ("DMASK", 0x1), ("DIM", 1), ("UNORM", 1)]));
// a null view's T# (all zero, s[40:47]) does not read the view at index 0; a real T# of it does
code.extend(mimg("IMAGE_LOAD", &[("VDATA", 25), ("VADDR", 3), ("SRSRC", 10), ("DMASK", 0x1), ("DIM", 1), ("UNORM", 1)]));
code.extend(mimg("IMAGE_LOAD", &[("VDATA", 26), ("VADDR", 3), ("SRSRC", 12), ("DMASK", 0x1), ("DIM", 1), ("UNORM", 1)]));
code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap());

let mut st = KernelState::default();
let mut garbage = tsharp(0, 77, 9);
garbage[0] = 0x9e55_ff68; // a console address, far past the heap
st.sgpr[16..24].copy_from_slice(&garbage);
st.sgpr[24..28].copy_from_slice(&[0, 0, 0, 0]);
st.sgpr[32..40].copy_from_slice(&tsharp(2, 20, 9));
st.sgpr[40..48].copy_from_slice(&[0; 8]);
st.sgpr[48..56].copy_from_slice(&tsharp(0, 77, 9));
for (l, r) in st.vgpr.iter_mut().enumerate() {
r[0] = f(0.5);
r[1] = f(0.5);
r[3] = (l % 4) as u32;
r[4] = l as u32 / 4; // lanes 16.. land outside the 4x4 texture: their stores are dropped
r[5] = 0;
r[6] = 10 * l as u32 + 1;
r[7] = 0xFFFF_FFFF;
for v in 10..27 {
r[v] = 0xDEAD_BEEF;
}
}
let tex = vec![
TestTexture { dim: TexDim::D2, format: DXGI_FORMAT_R32G32B32A32_FLOAT, width: 4, height: 4, depth: 1, texel_bytes: 16, data: vec![0x3F; 256], uav: false },
TestTexture { dim: TexDim::D2, format: DXGI_FORMAT_R32_UINT, width: 4, height: 4, depth: 1, texel_bytes: 4, data: vec![0xEE; 64], uav: true },
];
let samp = vec![TestSampler { filter: D3D12_FILTER_MIN_MAG_MIP_POINT, address: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, comparison: None }];
let r = runner::run_code_with(&code, &st, &[], &tex, &samp).unwrap();
for l in 0..64 {
assert_eq!(&r.vgpr[l][10..14], &[0, 0, 0, 0], "lane {l}: sample through the null SRV");
assert_eq!(r.vgpr[l][14], 0, "lane {l}: load through the null SRV");
assert_eq!(&r.vgpr[l][16..24], &[0; 8], "lane {l}: 3D and cube samples through their null SRVs");
assert_eq!(r.vgpr[l][24], 0, "lane {l}: 2D array load through its null SRV");
assert_eq!(r.vgpr[l][25], 0, "lane {l}: load through an all-zero T#");
// (lanes 16.. load outside the texture: 0)
assert_eq!(r.vgpr[l][26], if l < 16 { 0x3F3F_3F3F } else { 0 }, "lane {l}: load through a real T# of view 0");
}
// the real UAV got only its own stores: none of the garbage T#'s writes landed in it
let t1: Vec<u32> = r.textures[0].chunks(4).map(|c| u32::from_le_bytes(c.try_into().unwrap())).collect();
for (i, &v) in t1.iter().enumerate() {
assert_eq!(v, 10 * i as u32 + 1, "real UAV texel {i}");
}
}

/// Each image declaration falls back to the null view of its own texture type, in 12 slots past
/// every view: D3D12 needs a null view's dimension to match the declaration (a Texture2D null
/// view for a Texture3D read is undefined on Windows drivers; RADV does not mind).
#[test]
fn image_declarations_fall_back_to_the_null_view_of_their_type() {
use crate::gpu::desc::{null_srv, null_uav, NULL_SRV_TYPES, NULL_UAV_TYPES, NULL_VIEWS, VIEW_HEAP_SIZE};
let mut slots: Vec<u32> = NULL_SRV_TYPES.iter().map(|t| null_srv(t)).chain(NULL_UAV_TYPES.iter().map(|t| null_uav(t))).collect();
slots.sort();
slots.dedup();
assert_eq!(slots, (NULL_VIEWS..VIEW_HEAP_SIZE).collect::<Vec<_>>());
let code = prog(&[
("IMAGE_SAMPLE_LZ", "ENC_MIMG", &[("VDATA", 10), ("VADDR", 0), ("SRSRC", 4), ("SSAMP", 6), ("DMASK", 0xF), ("DIM", 2)], None),
("IMAGE_SAMPLE_LZ", "ENC_MIMG", &[("VDATA", 10), ("VADDR", 0), ("SRSRC", 4), ("SSAMP", 6), ("DMASK", 0xF), ("DIM", 3)], None),
("IMAGE_LOAD", "ENC_MIMG", &[("VDATA", 14), ("VADDR", 3), ("SRSRC", 4), ("DMASK", 0x1), ("DIM", 5), ("UNORM", 1)], None),
("IMAGE_STORE", "ENC_MIMG", &[("VDATA", 6), ("VADDR", 3), ("SRSRC", 4), ("DMASK", 0x1), ("DIM", 2), ("UNORM", 1)], None),
]);
let t = translate(&code, &Options::default()).unwrap();
assert!(t.complete(), "{:?}", t.unsupported);
for (decl, null) in [(" Texture3D<", null_srv("3D")), (" TextureCubeArray<", null_srv("CubeArray")), (" Texture2DArray<", null_srv("2DArray")), (" RWTexture3D<", null_uav("3D"))] {
let line = t.hlsl.lines().find(|l| l.contains(decl) && l.contains("ResourceDescriptorHeap")).unwrap_or_else(|| panic!("no{decl}: {}", t.hlsl));
assert!(line.contains(&format!(" : {null}u)")), "{line}");
}
}
Loading
Loading