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
9 changes: 7 additions & 2 deletions crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1936,11 +1936,16 @@ pub(crate) unsafe fn record_indirect_slicer(
list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }) } }]);
list.Dispatch(1, 1, 1);
// INDIRECT_ARGUMENT alone: vkd3d-proton hoists an ExecuteIndirect's preprocessing to the start
// of its command buffer (or of the submit) unless the list transitions something to exactly
// that state before it, so with any other bit set the pieces read the commands before this
// pass wrote them: zeros or a dispatch before's groups and slab origins (RADV: a TCP page
// fault where a split chain's indirect dispatch runs)
list.ResourceBarrier(&[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::transmute_copy(out), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
StateBefore: D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
StateAfter: D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT | D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER }) } }]);
StateAfter: D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT }) } }]);
Ok(())
}

Expand All @@ -1950,7 +1955,7 @@ pub(crate) unsafe fn restore_indirect_commands(list: &ID3D12GraphicsCommandList,
list.ResourceBarrier(&[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::transmute_copy(commands), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
StateBefore: D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT | D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER,
StateBefore: D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
StateAfter: D3D12_RESOURCE_STATE_UNORDERED_ACCESS }) } }]);
}

Expand Down
40 changes: 34 additions & 6 deletions crates/xcl/src/hle/d3d12x/bind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3809,13 +3809,13 @@ unsafe fn execute_indirect_snapshot(
if gfx && super::present::trace_frame() {
trace_ui_draw(this, raw_pso, pso, true);
}
// (binds a compute root signature and a pipeline: before the dispatch's or draw's own)
let checked = super::indirect_guard::check(this, pso, sig, max, args, args_off, count_buf);
// a split compute program's one Dispatch-only command runs its chain (`dispatch_chain`)
if compute && max == 1 && count_buf == 0 && signature.dispatch_only().is_some() {
use super::real::dispatch_chain::Indirect;
let chained = indirect_address(args, args_off_title, args_off).map_or(Ok(Indirect::Whole), |address| {
super::real::dispatch_chain::execute_indirect(list, raw_pso, pso, with(this, |s| s.allocator), address,
|root| bind_abi_with_root_resolved(this, list, raw_pso, pso, false, root, [0; 3], None, 0).map(|_| ()))
});
let chained = execute_indirect_chain(this, list, raw_pso, pso, with(this, |s| s.allocator), checked.as_ref(), args, args_off_title, args_off,
|root| bind_abi_with_root_resolved(this, list, raw_pso, pso, false, root, [0; 3], None, 0).map(|_| ()));
match chained {
Ok(Indirect::Ran) => {
ei_work(this, dispatches, super::targets::RAN);
Expand All @@ -3834,8 +3834,6 @@ unsafe fn execute_indirect_snapshot(
}
}
}
// (binds a compute root signature and a pipeline: before the dispatch's or draw's own)
let checked = super::indirect_guard::check(this, pso, sig, max, args, args_off, count_buf);
match bind_abi_resolved(this, list, raw_pso, pso, gfx) {
Ok(b) => {
let mut whole = None;
Expand Down Expand Up @@ -3960,6 +3958,36 @@ fn take_indirect_skip_counts() -> [u32; 2] {
INDIRECT_SKIP_COUNTS.with(|counts| counts.replace([0; 2]))
}

/// A split compute program's one Dispatch-only ExecuteIndirect through its chain
/// (`dispatch_chain::execute_indirect`, `allocator` the list's), from the counts as the guard let
/// them through (`checked`; the title's own where it checks none): the slicer clamps each count to
/// 65 535 but runs a partial split's whole count in one dispatch, up to 65 535^3 groups of
/// garbage. `bind(root)` binds the program's arguments under the chain's root signature.
pub(super) unsafe fn execute_indirect_chain(
this: *mut c_void, list: &ID3D12GraphicsCommandList, raw_pso: usize, pso: usize, allocator: usize,
checked: Option<&super::indirect_guard::Checked>, args: usize, args_off_title: u64, args_off: u64,
bind: impl FnOnce(usize) -> Result<(), String>,
) -> Result<super::real::dispatch_chain::Indirect, String> {
use super::real::dispatch_chain::Indirect;
let address = match checked {
Some(c) => Some(c.gpu_address()),
None => indirect_address(args, args_off_title, args_off),
};
let Some(address) = address else { return Ok(Indirect::Whole) };
let (out, _) = checked.map_or((0, 0), |c| c.arguments());
let chained = super::real::dispatch_chain::execute_indirect(list, raw_pso, pso, allocator, address, bind,
// (the slicer reads the checked counts as a root SRV; only when a chain records it)
|reading| if out != 0 {
let (uav, srv) = (D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
let (before, after) = if reading { (uav, srv) } else { (srv, uav) };
super::list_x::transition(this, out, before, after);
});
if let (Some(c), Ok(Indirect::Ran) | Err(_)) = (checked, &chained) {
c.read(this);
}
chained
}

unsafe fn indirect_address(resource: usize, title_offset: u64, pc_offset: u64) -> Option<u64> {
match super::real::console_buffer(resource) {
Some((base, size)) if title_offset.checked_add(12).is_some_and(|end| end <= size as u64) => {
Expand Down
81 changes: 66 additions & 15 deletions crates/xcl/src/hle/d3d12x/indirect_guard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,11 +199,13 @@ unsafe fn guard_of(list: &ID3D12GraphicsCommandList) -> Option<Arc<Guard>> {
let mut dev: Option<ID3D12Device> = None;
list.GetDevice(&mut dev).ok()?;
let dev = dev?;
// (before `GUARD`: DXC's pool may make the first ExecuteIndirect wait, `counts` must not)
let dxil = dxil();
let mut g = GUARD.lock().unwrap();
if let Some(g) = g.as_ref().filter(|g| g.dev == dev.as_raw() as usize) {
return Some(g.clone());
}
match super::title_textures::own_work(|| make(&dev)) {
match super::title_textures::own_work(|| make(&dev, dxil)) {
Ok(n) => {
let n = Arc::new(n);
*g = Some(n.clone());
Expand All @@ -217,11 +219,16 @@ unsafe fn guard_of(list: &ID3D12GraphicsCommandList) -> Option<Arc<Guard>> {
}
}

unsafe fn make(dev: &ID3D12Device) -> Result<Guard, String> {
let cs = real::compile(&program(), "cs_5_0");
if cs.is_empty() {
return Err("its program does not compile".into());
}
/// The guard's program as DXIL, compiled once for every device. DXC, not D3DCompile: Wine's
/// d3dcompiler (vkd3d-shader) has no Load3 on a RWByteAddressBuffer, so under Wine the guard
/// never ran and garbage counts reached the GPU (RADV: a ring timeout in a DISPATCH_INDIRECT of a
/// small program).
fn dxil() -> &'static Result<Vec<u8>, String> {
static DXIL: std::sync::OnceLock<Result<Vec<u8>, String>> = std::sync::OnceLock::new();
DXIL.get_or_init(|| crate::gpu::recomp::dxc::compile(&program(), "main", "cs_6_0", &[]))
}

unsafe fn make(dev: &ID3D12Device, dxil: &Result<Vec<u8>, String>) -> Result<Guard, String> {
let root = |ty, anonymous| D3D12_ROOT_PARAMETER { ParameterType: ty, Anonymous: anonymous, ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL };
let uav = |k| root(D3D12_ROOT_PARAMETER_TYPE_UAV, D3D12_ROOT_PARAMETER_0 { Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: k, RegisterSpace: 0 } });
let params = [
Expand All @@ -236,10 +243,22 @@ unsafe fn make(dev: &ID3D12Device) -> Result<Guard, String> {
D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None).map_err(|e| format!("root signature: {e}"))?;
let blob = blob.ok_or("root signature")?;
let rs: ID3D12RootSignature = dev.CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize())).map_err(|e| format!("CreateRootSignature: {e}"))?;
let code = D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as *const c_void, BytecodeLength: cs.len() };
let pso: ID3D12PipelineState = dev
.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: transmute_copy(&rs), CS: code, ..Default::default() })
.map_err(|e| format!("CreateComputePipelineState: {e}"))?;
let pso_of = |cs: &[u8]| -> Result<ID3D12PipelineState, String> {
let code = D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as *const c_void, BytecodeLength: cs.len() };
dev.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: transmute_copy(&rs), CS: code, ..Default::default() })
.map_err(|e| format!("CreateComputePipelineState: {e}"))
};
// D3DCompile's when DXC failed, or the device refused its DXIL (unsigned: no dxil.dll)
let pso = match dxil.as_ref().map_err(String::clone).and_then(|cs| pso_of(cs)) {
Ok(pso) => pso,
Err(e) => {
let cs = real::compile(&program(), "cs_5_0");
if cs.is_empty() {
return Err(format!("its program does not compile ({e})"));
}
pso_of(&cs).map_err(|e5| format!("{e5} (DXC: {e})"))?
}
};
let buffer = |heap: D3D12_HEAP_PROPERTIES, width: u64| -> Result<ID3D12Resource, String> {
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Expand Down Expand Up @@ -376,6 +395,12 @@ impl Checked {
(self.guard.out.as_raw() as usize, self.slot as u64 * SLOT as u64)
}

/// The GPU address of the checked counts (`arguments`), for a pass that reads them through a
/// root view; `read` after it.
pub(super) fn gpu_address(&self) -> u64 {
self.guard.out_va + self.slot as u64 * SLOT as u64
}

/// After a pass read the counts at `arguments`: the buffer back to COMMON (its write and that
/// read left it in UNORDERED_ACCESS).
pub(super) unsafe fn read(&self, list: *mut c_void) {
Expand Down Expand Up @@ -447,7 +472,7 @@ fn report(g: &Guard) {
}

#[cfg(test)]
mod tests {
pub(super) mod tests {
use super::super::list_x;
use super::*;
use crate::gpu::{fence, recomp::runner::skip_test};
Expand All @@ -456,7 +481,7 @@ mod tests {
type Close = unsafe extern "system" fn(*mut c_void) -> windows::core::HRESULT;

/// the guard (and its count of what was out of range) is the device's: one test at a time
static ONE: Mutex<()> = Mutex::new(());
pub(in crate::hle::d3d12x) static ONE: Mutex<()> = Mutex::new(());

unsafe fn device() -> Option<ID3D12Device> {
let mut dev: Option<ID3D12Device> = None;
Expand Down Expand Up @@ -529,6 +554,18 @@ mod tests {
assert_eq!(counts_va_in(0x100, in_one_window, va_of), None, "not in a window");
}

/// The guard's program compiles with DXC (`make`): Wine's D3DCompile refuses it, which left
/// the guard off in every run under Wine.
#[test]
fn the_guards_program_compiles_with_dxc() {
if crate::gpu::recomp::dxc::location().is_err() {
crate::gpu::recomp::runner::skip_test("no DXC");
return;
}
let dxil = crate::gpu::recomp::dxc::compile(&program(), "main", "cs_6_0", &[]).unwrap();
assert!(!dxil.is_empty());
}

#[test]
fn a_counter_is_logged_at_its_first_values_and_at_each_doubling_however_it_jumps() {
assert!(logged_again(0, 1) && logged_again(0, 7) && logged_again(3, 5));
Expand Down Expand Up @@ -562,7 +599,12 @@ void main() { c.InterlockedAdd(0, 1u); }
unsafe {
let _one = ONE.lock().unwrap_or_else(|e| e.into_inner());
let Some(dev) = device() else { return };
let cs = real::compile(src, "cs_5_0");
if crate::gpu::recomp::dxc::location().is_err() {
crate::gpu::recomp::runner::skip_test("no DXC");
return;
}
// (DXC: Wine's D3DCompile has no InterlockedAdd on a RWByteAddressBuffer either)
let cs = crate::gpu::recomp::dxc::compile(src, "main", "cs_6_0", &[]).unwrap();
assert!(!cs.is_empty());
let param = D3D12_ROOT_PARAMETER {
ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV,
Expand Down Expand Up @@ -593,11 +635,13 @@ void main() { c.InterlockedAdd(0, 1u); }
let raw = list.as_raw();
type Ei = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64);
let ei: Ei = std::mem::transmute(real::orig_fn(raw, 59));
let before = GUARD.lock().unwrap().as_ref().map_or(0, |g| bad_so_far(g));
if let Some(g) = GUARD.lock().unwrap().as_ref() {
g.next.store(0, Ordering::Relaxed);
}
let checked = check(raw, 0, s, 1, a, off, 0).expect("checked");
// (after `check`: the guard is the device's, and the test before may have left
// another device's; nothing is counted until the list runs)
let before = bad_so_far(&checked.guard);
assert!(k == 0 || checked.slot == 0);
list.SetComputeRootSignature(&rs);
list.SetPipelineState(&pso);
Expand Down Expand Up @@ -647,7 +691,14 @@ void main() { c.InterlockedAdd(0, 1u); }
let (_alloc, list) = title_list(&dev, ty);
let raw = list.as_raw();
let sig = if is_indexed { &indexed } else { &plain };
let checked = check(raw, 0, sig.as_raw() as usize, 1, args.as_raw() as usize, 0, 0).expect("checked");
let Some(checked) = check(raw, 0, sig.as_raw() as usize, 1, args.as_raw() as usize, 0, 0) else {
// (no guard without a compiler for its program: under Wine that takes DXC)
if crate::gpu::recomp::dxc::location().is_err() {
crate::gpu::recomp::runner::skip_test("no DXC");
return;
}
panic!("checked");
};
// (the arguments, copied out instead of drawn)
checked.run(raw, |b, o| {
list_x::transition(raw, b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE);
Expand Down
Loading
Loading