Skip to content
Closed
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
58 changes: 58 additions & 0 deletions crates/xcl/src/hle/d3d12x/console_heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1191,6 +1191,64 @@ pub unsafe fn publish(s: &Slot, uav: bool, res: usize) {
names().note(s.index + uav as u32, res);
}

/// Clear any prior PC SRV/UAV descriptors and `NAMES` tracking for view slot `s` when it is
/// overwritten by a UMA-only view (CBV, acceleration structure, or buffer view by address) that
/// creates no PC view of its own. Clears both the title's mirror slot and the shared heap so a
/// later `CopyDescriptors` or `resource_gone` cannot copy or observe a stale resource view.
pub unsafe fn clear_views(s: &Slot) {
if s.sampler {
return;
}
note_resource(s, 0);
if s.shared_srv == 0 || names_of(s) == (0, 0) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The early return when shared_srv == 0 or names_of(s) == (0, 0) skips nulling the mirror descriptors at pc_srv/pc_uav, even if they hold a live view. If slot k got its views via CopyDescriptors from a source with no shared place (names (0,0)), the mirror holds tex while NAMES says 0. A CBV over k skips the clear, and a later copy of k publishes the mirror's tex view into another shared index with NAMES 0. resource_gone(tex) never nulls it, so after tex is released the shared heap keeps a descriptor of a destroyed resource. Nulling the mirror needs no GLOBAL state and could be done unconditionally.

return;
}
let snapshot = (|| {
let heaps = HEAPS.lock().unwrap();
let h = heaps.iter().find(|h| {
h.generation == s.generation
&& !h.sampler
&& s.k < h.n
&& s.at == h.shadow + (s.k * h.slot_bytes()) as usize
})?;
let raw = h.obj as *mut std::ffi::c_void;
let source_owner = ID3D12DescriptorHeap::from_raw_borrowed(&raw)?.clone();
let first = *h.pages.get((s.k / PAGE_SLOTS) as usize)?;
let expected_src = h.pc_cpu + (2 * s.k) as u64 * h.inc as u64;
if first == UNMAPPED || expected_src != s.pc_srv {
return None;
}
let idx = first + 2 * (s.k % PAGE_SLOTS);
let mut globals = GLOBAL.lock().unwrap();
let global = globals.as_mut()?;
let dst = global.cpu + idx as u64 * global.inc as u64;
if dst != s.shared_srv {
return None;
}
let (nulls_heap, nulls_cpu) = global.nulls.as_ref().map(|(nh, ptr)| (nh.clone(), *ptr))?;
global.leases.acquire(idx, 2);
Some((
global.dev.clone(),
source_owner,
nulls_heap,
PublishLease { sampler: false, range: (idx, 2) },
dst,
s.pc_srv,
nulls_cpu,
idx,
))
})();
let Some((dev, _source_owner, _nulls_heap, _lease, dst, pc_srv, nulls_cpu, idx)) = snapshot else {
return;
};
let _w = SLOT_WRITES.lock().unwrap();
copy_views(&dev, 2, pc_srv, nulls_cpu);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

clear_views writes null views into the shared-heap SRV/UAV pair at the slot's index, but the module documents that titles keep T#s, each holding a shared-heap index, in their own memory. If a title makes a texture SRV in slot k, copies the T# words into a material table, then reuses slot k for a CBV, the copied T# still samples the texture on the console. Before this PR the PC shared index still held the live view. Now it's null, so the material renders black. This might also be related to the 1695 -> 1554 frames in the PR's smoke run.

copy_views(&dev, 2, dst, nulls_cpu);
let m = names();
m.note(idx, 0);
m.note(idx + 1, 0);
}

/// The PC resources the SRV and the UAV of view slot `s` name in the shared heap (0: not known,
/// a sampler, or the slot has no place there): what `publish_range` takes for a copy of it.
pub fn names_of(s: &Slot) -> (usize, usize) {
Expand Down
218 changes: 216 additions & 2 deletions crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2805,6 +2805,7 @@ unsafe extern "system" fn dev_create_cbv_x(this: *mut c_void, desc: *const D3D12
});
super::view_want::want(super::view_want::Path::Cbv, va, size as u64);
super::vram::clear_tracked_srv(&slot);
super::console_heap::clear_views(&slot);
super::console_heap::write(&slot, &words);
}

Expand Down Expand Up @@ -3246,6 +3247,7 @@ unsafe fn dev_create_srv_inner(this: *mut c_void, res: *mut c_void, desc: *const
// translated shaders read BVH nodes from UMA (`bvh_intersect`), never from a PC DXR SRV,
// so write the RDNA2 BVH descriptor directly and skip forwarding the console VA to PC.
if let Some(v) = desc.as_ref().filter(|v| v.ViewDimension == D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE) {
super::console_heap::clear_views(&slot);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The !s.sampler guard was added to the buffer branches of #70/#71 but not to the RTAS branch, which this PR also touches. dev_create_srv_inner takes console_heap::slot(cpu) with no sampler filter. clear_views returns early for samplers, then console_heap::write(&slot, &[bvh w0..w3,0,0,0,0]) writes 4 words over the S#, including word 3 [11:0], the PC sampler index. Later samples through that slot use a garbage sampler index, which is the defect this PR fixes for #70/#71.

let va = v.Anonymous.RaytracingAccelerationStructure.Location;
// in a GPU view: its tiles are asked for from the root's on (the size is not known; the
// build wrote the nodes through views that asked for theirs, and a buffer placed there
Expand Down Expand Up @@ -3415,9 +3417,10 @@ unsafe extern "system" fn dev_create_srv_at_x(this: *mut c_void, rdesc: *const u
if v.ViewDimension == D3D12_SRV_DIMENSION_BUFFER {
let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor);
let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ViewDescriptor);
let Some(slot) = super::console_heap::slot(cpu) else { return };
let Some(slot) = super::console_heap::slot(cpu).filter(|s| !s.sampler) else { return };
let _tracked_write_lock = super::vram::lock_tracked_srv_write();
super::vram::clear_tracked_srv(&slot);
super::console_heap::clear_views(&slot);
let b = &v.Anonymous.Buffer;
let raw = b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0;
let (words, at, len) = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw);
Expand All @@ -3440,9 +3443,10 @@ unsafe extern "system" fn dev_create_uav_at_x(this: *mut c_void, rdesc: *const u
let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor);
if v.ViewDimension == D3D12_UAV_DIMENSION_BUFFER {
let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ViewDescriptor);
let Some(slot) = super::console_heap::slot(cpu) else { return };
let Some(slot) = super::console_heap::slot(cpu).filter(|s| !s.sampler) else { return };
let _tracked_write_lock = super::vram::lock_tracked_srv_write();
super::vram::clear_tracked_srv(&slot);
super::console_heap::clear_views(&slot);
let b = &v.Anonymous.Buffer;
let raw = b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0;
let (words, at, len) = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw);
Expand Down Expand Up @@ -15008,3 +15012,213 @@ mod heap_release_order_tests {
}
}

#[cfg(test)]
mod stale_view_clear_tests {
use super::*;
use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R32_UINT, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC};
use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, IDXGIAdapter1, IDXGIFactory4};

const CHILD_ENV: &str = "XCL_TEST_STALE_VIEW_CLEAR_CHILD";

fn run_in_child(test_name: &str) -> bool {
if std::env::var_os(CHILD_ENV).is_some() {
return true;
}
let exe = std::env::current_exe().expect("test binary path");
let out = std::process::Command::new(exe)
.env(CHILD_ENV, "1")
.args(["--exact", test_name, "--nocapture"])
.output()
.expect("spawn child test");
assert!(
out.status.success(),
"child test {test_name} failed ({}):\nstdout:\n{}\nstderr:\n{}",
out.status,
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr),
);
false
}

fn warp_device() -> Option<ID3D12Device> {
unsafe {
let mut dbg: Option<ID3D12Debug> = None;
if D3D12GetDebugInterface(&mut dbg).is_ok() {
if let Some(d) = dbg {
d.EnableDebugLayer();
}
}
let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?;
let adapter: IDXGIAdapter1 = factory.EnumWarpAdapter().ok()?;
let mut dev: Option<ID3D12Device> = None;
D3D12CreateDevice(&adapter, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0, &mut dev).ok()?;
dev
}
}

#[test]
fn cbv_bvh_and_buffer_view_at_clear_stale_pc_views_and_skip_sampler_slots() {
if !run_in_child("hle::d3d12x::real::stale_view_clear_tests::cbv_bvh_and_buffer_view_at_clear_stale_pc_views_and_skip_sampler_slots") {
return;
}
let Some(dev) = warp_device() else {
crate::gpu::recomp::runner::skip_test("no WARP device");
return;
};
unsafe {
adopt(dev.as_raw(), Kind::Device);

// Create a shader-visible console view heap (8 slots).
let heap_desc: [u32; 4] = [
D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0 as u32,
8,
D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 as u32,
0,
];
let heap_iid = &ID3D12DescriptorHeap::IID as *const windows::core::GUID as *const GUID;
let mut raw_heap = std::ptr::null_mut();
let hr = dev_create_descriptor_heap_x(dev.as_raw(), &heap_desc, heap_iid, &mut raw_heap);
assert!(hr >= 0 && !raw_heap.is_null(), "create console view heap: {hr:#x}");
let base_cpu = super::super::console_heap::start(raw_heap as usize).expect("console heap start");
let step = super::super::console_heap::SLOT as u64;

// Create a UAV-capable 2D texture.
let mut tex: Option<ID3D12Resource> = None;
dev.CreateCommittedResource(
&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() },
D3D12_HEAP_FLAG_NONE,
&D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
Width: 16,
Height: 16,
DepthOrArraySize: 1,
MipLevels: 1,
Format: DXGI_FORMAT_R8G8B8A8_UNORM,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN,
Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
..Default::default()
},
D3D12_RESOURCE_STATE_COMMON,
None,
&mut tex,
)
.expect("create texture");
let tex = tex.unwrap();
let tex_raw = tex.as_raw();
let tex_addr = tex_raw as usize;

// Populate slots 0..4 with both SRV and UAV naming `tex`.
let srv_desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
Format: DXGI_FORMAT_R8G8B8A8_UNORM,
ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: 0, MipLevels: 1, PlaneSlice: 0, ResourceMinLODClamp: 0.0 },
},
};
let uav_desc = D3D12_UNORDERED_ACCESS_VIEW_DESC {
Format: DXGI_FORMAT_R8G8B8A8_UNORM,
ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D,
Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 {
Texture2D: D3D12_TEX2D_UAV { MipSlice: 0, PlaneSlice: 0 },
},
};
for k in 0..4u64 {
let cpu = base_cpu + k * step;
dev_create_srv_x(dev.as_raw(), tex_raw, &srv_desc, cpu);
dev_create_uav_x(dev.as_raw(), tex_raw, std::ptr::null_mut(), &uav_desc, cpu);
let s = super::super::console_heap::slot(cpu).expect("slot");
assert_eq!(super::super::console_heap::names_of(&s), (tex_addr, tex_addr), "slot {k} initially names tex");
}

// Overwrite slot 0 with CBV.
let cbv_desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { BufferLocation: 0, SizeInBytes: 256 };
dev_create_cbv_x(dev.as_raw(), &cbv_desc, base_cpu);

// Overwrite slot 1 with RTAS / BVH SRV.
let bvh_desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN,
ViewDimension: D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE,
Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
RaytracingAccelerationStructure: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_SRV { Location: 0 },
},
};
dev_create_srv_x(dev.as_raw(), std::ptr::null_mut(), &bvh_desc, base_cpu + step);

// Overwrite slot 2 with buffer SRV-at (#70).
let mut srv_at_buf = [0u8; 0x40];
let buf_srv = D3D12_SHADER_RESOURCE_VIEW_DESC {
Format: DXGI_FORMAT_R32_UINT,
ViewDimension: D3D12_SRV_DIMENSION_BUFFER,
Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
Buffer: D3D12_BUFFER_SRV { FirstElement: 0, NumElements: 16, StructureByteStride: 0, Flags: D3D12_BUFFER_SRV_FLAG_NONE },
},
};
std::ptr::write_unaligned(srv_at_buf.as_mut_ptr() as *mut D3D12_SHADER_RESOURCE_VIEW_DESC, buf_srv);
dev_create_srv_at_x(dev.as_raw(), std::ptr::null(), srv_at_buf.as_ptr(), base_cpu + 2 * step);

// Overwrite slot 3 with buffer UAV-at (#71).
let mut uav_at_buf = [0u8; 0x40];
let buf_uav = D3D12_UNORDERED_ACCESS_VIEW_DESC {
Format: DXGI_FORMAT_R32_UINT,
ViewDimension: D3D12_UAV_DIMENSION_BUFFER,
Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 {
Buffer: D3D12_BUFFER_UAV { FirstElement: 0, NumElements: 16, StructureByteStride: 0, CounterOffsetInBytes: 0, Flags: D3D12_BUFFER_UAV_FLAG_NONE },
},
};
std::ptr::write_unaligned(uav_at_buf.as_mut_ptr() as *mut D3D12_UNORDERED_ACCESS_VIEW_DESC, buf_uav);
dev_create_uav_at_x(dev.as_raw(), std::ptr::null(), uav_at_buf.as_ptr(), base_cpu + 3 * step);

// Copy overwritten slots 0..4 into 4..8 and confirm neither original nor copied slots name `tex`.
dev_copy_descriptors_simple_x(dev.as_raw(), 4, base_cpu + 4 * step, base_cpu, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0 as u32);
for k in 0..8u64 {
let s = super::super::console_heap::slot(base_cpu + k * step).expect("slot");
assert_eq!(
super::super::console_heap::names_of(&s),
(0, 0),
"slot {k} must not retain stale tex reference after overwrite/copy"
);
}
assert_eq!(
super::super::console_heap::resource_gone(tex_addr),
0,
"resource_gone(tex) must find 0 descriptors once all slots were overwritten"
);

// Sampler slot guard: buffer SRV-at / UAV-at must not clobber a sampler slot's S#.
let smp_heap_desc: [u32; 4] = [
D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0 as u32,
4,
D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 as u32,
0,
];
let mut raw_smp_heap = std::ptr::null_mut();
let hr_s = dev_create_descriptor_heap_x(dev.as_raw(), &smp_heap_desc, heap_iid, &mut raw_smp_heap);
assert!(hr_s >= 0 && !raw_smp_heap.is_null(), "create console sampler heap: {hr_s:#x}");
let smp_cpu = super::super::console_heap::start(raw_smp_heap as usize).expect("sampler heap start");
let smp_desc = D3D12_SAMPLER_DESC {
Filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR,
AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
MaxLOD: f32::MAX,
..Default::default()
};
dev_create_sampler_x(dev.as_raw(), &smp_desc, smp_cpu);
let before_s: [u32; 4] = (smp_cpu as *const [u32; 4]).read_unaligned();
dev_create_srv_at_x(dev.as_raw(), std::ptr::null(), srv_at_buf.as_ptr(), smp_cpu);
dev_create_uav_at_x(dev.as_raw(), std::ptr::null(), uav_at_buf.as_ptr(), smp_cpu);
let after_s: [u32; 4] = (smp_cpu as *const [u32; 4]).read_unaligned();
assert_eq!(after_s, before_s, "buffer SRV-at/UAV-at must not overwrite a sampler slot");

assert!(dev.GetDeviceRemovedReason().is_ok(), "WARP device must remain healthy");
let _ = ID3D12DescriptorHeap::from_raw(raw_smp_heap);
let _ = ID3D12DescriptorHeap::from_raw(raw_heap);
}
}
}


Loading