Skip to content
Open
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
195 changes: 194 additions & 1 deletion crates/xcl/src/hle/d3d12x/console_heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -500,7 +500,6 @@ pub unsafe fn shared_heap(dev: &ID3D12Device) -> bool {
let cpu = heap.GetCPUDescriptorHandleForHeapStart().ptr as u64;
let start = std::time::Instant::now();
null_views(dev, cpu, inc);
null_window_views(dev, cpu, inc);
// D3D12 leaves a new heap's descriptors undefined: every one XCL has not handed out holds a
// null view, so an index a shader takes from a stale or garbage T# reads zeros, never a
// descriptor of whatever the memory held (the memory windows' views come over theirs next)
Expand All @@ -511,6 +510,9 @@ pub unsafe fn shared_heap(dev: &ID3D12Device) -> bool {
fill_nulls(dev, cpu, inc, crate::gpu::recomp::MEM_HEAP_BASE, cap, at);

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 fix for slots 20/21 looks right, but fill_nulls still starts at MEM_HEAP_BASE, so it writes Texture2D null SRV/UAVs over the window slots 4..19, which are reserved for raw buffer UAVs too. set_window_views only rewrites windows.len().max(MAX_WINDOWS) slots (4 for a normal layout), so slots 8..19 keep Texture2D nulls. A heap-windows shader that reaches window k >= count (a cached PSO translated for a wider layout, or the #3096 expansion) hits the same type mismatch this PR fixes for 20/21 (GBV 939/941, undefined on hardware). Starting fill_nulls at MEM_NULL_STORE + 1 (where Global.next starts), and having null_window_views write raw null UAVs for all of MEM_HEAP_BASE..=MEM_NULL_STORE once, would fix the whole region.

(h, at)
});
// Written after `fill_nulls` so the two out-of-layout raw buffer null UAVs at
// `MEM_NULL_LOAD` and `MEM_NULL_STORE` are not overwritten with Texture2D null SRV/UAVs.
null_window_views(dev, cpu, inc);

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.

Not certain about this one: with slots 20/21 holding raw buffer UAVs again, a stale or garbage T# index that lands on them reaches a raw UAV through a Texture2D access. The image guard only checks tw0 < VIEW_HEAP_MAX_SRV, with no lower bound past the window region. A T# with word 0 = 20 indexes ResourceDescriptorHeap[20] as Texture2D and [21] as RWTexture2D and finds a 4-byte raw buffer UAV. The MEM_HEAP_BASE doc already records that a raw buffer UAV read as a texture hangs NVIDIA GPUs, and the shared_heap comment's promise that garbage T# indexes read zeros no longer holds for 4..21.

crate::xlog_info!(
"console descriptor heaps: one shader-visible PC heap of {cap} view descriptors for all of them ({})",
if nulls.is_some() { format!("null views in the rest, {} ms", start.elapsed().as_millis()) } else { "no null views past the first: no CPU-only heap for them".into() }
Expand Down Expand Up @@ -2848,4 +2850,195 @@ mod tests {
}
assert_eq!((device.refs.load(Ordering::Relaxed), global_heap.refs.load(Ordering::Relaxed), source_heap.refs.load(Ordering::Relaxed)), (0, 0, 1));
}

/// `shared_heap` must leave `MEM_NULL_LOAD` and `MEM_NULL_STORE` populated with raw buffer
/// null UAVs (`RWByteAddressBuffer`), not overwritten by `fill_nulls` with `Texture2D` null
/// SRV/UAV descriptors. Verified on WARP with D3D12 debug layer + GPU-based validation.
#[test]
fn shared_heap_preserves_null_window_raw_uavs() {
const CHILD: &str = "XCL_TEST_SHARED_HEAP_NULL_WINDOW_UAVS_CHILD";
if std::env::var_os(CHILD).is_none() {
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "hle::d3d12x::console_heap::tests::shared_heap_preserves_null_window_raw_uavs", "--nocapture"])
.env(CHILD, "1")
.output()
.unwrap();
assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr));
return;
}

use crate::gpu::dxil::container::Stage;
use crate::gpu::dxil::module::BinOp;
use crate::gpu::dxil::shader::Shader;
use windows::Win32::Graphics::Direct3D::{ID3DBlob, D3D_FEATURE_LEVEL_12_0};
use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory2, IDXGIAdapter1, IDXGIFactory4, DXGI_CREATE_FACTORY_FLAGS};
use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject, INFINITE};

unsafe {
let mut dbg: Option<ID3D12Debug> = None;
if D3D12GetDebugInterface(&mut dbg).is_err() {
return crate::gpu::recomp::runner::skip_test("no D3D12 debug layer");
}
let dbg = dbg.unwrap();
dbg.EnableDebugLayer();
let Ok(dbg1) = dbg.cast::<ID3D12Debug1>() else {
return crate::gpu::recomp::runner::skip_test("no ID3D12Debug1 GPU-based validation");
};
dbg1.SetEnableGPUBasedValidation(true);

let factory: IDXGIFactory4 = match CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)) {
Ok(f) => f,
Err(_) => return crate::gpu::recomp::runner::skip_test("no DXGI factory"),
};
let adapter: IDXGIAdapter1 = match factory.EnumWarpAdapter() {
Ok(a) => a,
Err(_) => return crate::gpu::recomp::runner::skip_test("no WARP adapter"),
};
let mut dev: Option<ID3D12Device> = None;
if D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut dev).is_err() {
return crate::gpu::recomp::runner::skip_test("no WARP D3D12 device");
}
let dev = dev.unwrap();
let mut sm = D3D12_FEATURE_DATA_SHADER_MODEL { HighestShaderModel: D3D_SHADER_MODEL_6_6 };
if dev.CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &mut sm as *mut _ as *mut _, std::mem::size_of_val(&sm) as u32).is_err()
|| sm.HighestShaderModel.0 < D3D_SHADER_MODEL_6_6.0
{
return crate::gpu::recomp::runner::skip_test("WARP lacks SM 6.6");
}
let iq: ID3D12InfoQueue = match dev.cast() {
Ok(q) => q,
Err(_) => return crate::gpu::recomp::runner::skip_test("no ID3D12InfoQueue"),
};
iq.ClearStoredMessages();

assert!(shared_heap(&dev), "shared_heap must initialize on WARP");
let heap = global_heap().expect("global_heap");

let mut s = Shader::new(Stage::Compute, (6, 6));
let out = s.raw_uav(0, 0);
let null_load_idx = s.m.i32c(crate::gpu::recomp::MEM_NULL_LOAD);
let null_store_idx = s.m.i32c(crate::gpu::recomp::MEM_NULL_STORE);
let m_load = s.heap_raw_buffer_uav(null_load_idx, false);
let m_store = s.heap_raw_buffer_uav(null_store_idx, false);
let zero = s.m.i32c(0);
let loaded = s.raw_load(m_load, zero, 1)[0];
let sentinel = s.m.i32c(0xDEAD_BEEF);
s.raw_store(m_store, zero, &[sentinel]);
let tag = s.m.i32c(0xA5A5_5A5A);
let marked = s.m.bin(BinOp::Xor, loaded, tag);
s.raw_store(out, zero, &[marked]);
let dxil = s.finish([1, 1, 1], None);

let param = D3D12_ROOT_PARAMETER {
ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV,
Anonymous: D3D12_ROOT_PARAMETER_0 {
Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: 0, RegisterSpace: 0 },
},
ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL,
};
let rs_desc = D3D12_ROOT_SIGNATURE_DESC {
NumParameters: 1,
pParameters: &param,
NumStaticSamplers: 0,
pStaticSamplers: std::ptr::null(),
Flags: D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED,
};
let mut blob: Option<ID3DBlob> = None;
let mut err_blob: Option<ID3DBlob> = None;
D3D12SerializeRootSignature(&rs_desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, Some(&mut err_blob)).expect("serialize root sig");
let blob = blob.unwrap();
let rs_bytes = std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize());
let root_sig: ID3D12RootSignature = dev.CreateRootSignature(0, rs_bytes).expect("CreateRootSignature");

let pso_desc = D3D12_COMPUTE_PIPELINE_STATE_DESC {
pRootSignature: std::mem::ManuallyDrop::new(Some(root_sig.clone())),
CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as *const _, BytecodeLength: dxil.len() },
NodeMask: 0,
CachedPSO: Default::default(),
Flags: D3D12_PIPELINE_STATE_FLAG_NONE,
};
let pso: ID3D12PipelineState = dev.CreateComputePipelineState(&pso_desc).expect("CreateComputePipelineState");
std::mem::ManuallyDrop::into_inner(pso_desc.pRootSignature);

let buf_desc = |flags: D3D12_RESOURCE_FLAGS| D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Alignment: 0,
Width: 256,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN,
SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
Flags: flags,
};
let default_hp = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() };
let readback_hp = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() };
let mut out_buf: Option<ID3D12Resource> = None;
dev.CreateCommittedResource(&default_hp, D3D12_HEAP_FLAG_NONE, &buf_desc(D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), D3D12_RESOURCE_STATE_COMMON, None, &mut out_buf).expect("out_buf");
let out_buf = out_buf.unwrap();
let mut rb_buf: Option<ID3D12Resource> = None;
dev.CreateCommittedResource(&readback_hp, D3D12_HEAP_FLAG_NONE, &buf_desc(D3D12_RESOURCE_FLAG_NONE), D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb_buf).expect("rb_buf");
let rb_buf = rb_buf.unwrap();

let qdesc = D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() };
let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&qdesc).expect("CreateCommandQueue");
let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("CreateCommandAllocator");
let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, Some(&pso)).expect("CreateCommandList");

list.SetDescriptorHeaps(&[Some(heap)]);
list.SetComputeRootSignature(&root_sig);
list.SetComputeRootUnorderedAccessView(0, out_buf.GetGPUVirtualAddress());
list.Dispatch(1, 1, 1);

let barrier = D3D12_RESOURCE_BARRIER {
Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
Anonymous: D3D12_RESOURCE_BARRIER_0 {
Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
pResource: std::mem::ManuallyDrop::new(Some(out_buf.clone())),
Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
StateBefore: D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
StateAfter: D3D12_RESOURCE_STATE_COPY_SOURCE,
}),
},
};
list.ResourceBarrier(&[barrier]);
list.CopyBufferRegion(&rb_buf, 0, &out_buf, 0, 4);
list.Close().expect("Close");

queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]);
let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("CreateFence");
queue.Signal(&fence, 1).expect("Signal");
let ev = CreateEventW(None, false, false, None).expect("CreateEventW");
fence.SetEventOnCompletion(1, ev).expect("SetEventOnCompletion");
WaitForSingleObject(ev, INFINITE);
let _ = windows::Win32::Foundation::CloseHandle(ev);

let mut p: *mut std::ffi::c_void = std::ptr::null_mut();
rb_buf.Map(0, None, Some(&mut p)).expect("Map");
let got = *(p as *const u32);
rb_buf.Unmap(0, None);
assert_eq!(got, 0xA5A5_5A5A, "MEM_NULL_LOAD must read 0");

let count = iq.GetNumStoredMessages();
let mut errors = Vec::new();
for i in 0..count {
let mut len = 0usize;
let _ = iq.GetMessage(i, None, &mut len);
let mut buf = vec![0u8; len];
let msg = buf.as_mut_ptr() as *mut D3D12_MESSAGE;
if iq.GetMessage(i, Some(msg), &mut len).is_ok() {
let m = &*msg;
if matches!(m.Severity, D3D12_MESSAGE_SEVERITY_CORRUPTION | D3D12_MESSAGE_SEVERITY_ERROR) {
let text = std::ffi::CStr::from_ptr(m.pDescription as *const i8).to_string_lossy().into_owned();
errors.push(format!("[id={}] {text}", m.ID.0));
}
}
}
assert!(errors.is_empty(), "D3D12 debug/GBV errors accessing MEM_NULL_LOAD/MEM_NULL_STORE:\n{}", errors.join("\n"));

*GLOBAL.lock().unwrap() = None;
}
}
}
Loading