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
152 changes: 151 additions & 1 deletion crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1472,6 +1472,145 @@ pub(crate) unsafe fn record_dispatch_chain<'a>(
}
}

/// Bytes of one indirect chain command: eight slab constants followed by Dispatch arguments.
pub(crate) const CHAIN_COMMAND_BYTES: u32 = 44;

pub(crate) fn chain_command_signature(dev: &ID3D12Device, rs: &ID3D12RootSignature) -> Result<ID3D12CommandSignature, String> {
let args = [
D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT, Anonymous: D3D12_INDIRECT_ARGUMENT_DESC_0 {
Constant: D3D12_INDIRECT_ARGUMENT_DESC_0_1 { RootParameterIndex: 7, DestOffsetIn32BitValues: 0, Num32BitValuesToSet: 8 } } },
D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, ..Default::default() },
];
let desc = D3D12_COMMAND_SIGNATURE_DESC { ByteStride: CHAIN_COMMAND_BYTES, NumArgumentDescs: 2, pArgumentDescs: args.as_ptr(), NodeMask: 0 };
let mut sig = None;
unsafe { dev.CreateCommandSignature(&desc, rs, &mut sig) }.map_err(|e| format!("CreateCommandSignature: {e}"))?;
sig.ok_or_else(|| "CreateCommandSignature".into())
}

pub(crate) fn dispatch_command_signature(dev: &ID3D12Device) -> Result<ID3D12CommandSignature, String> {
static MADE: Mutex<Option<(usize, ID3D12CommandSignature)>> = Mutex::new(None);
let mut made = MADE.lock().unwrap();
if let Some((_, sig)) = made.as_ref().filter(|m| m.0 == windows::core::Interface::as_raw(dev) as usize) {
return Ok(sig.clone());
}
let arg = D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, ..Default::default() };
let desc = D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 12, NumArgumentDescs: 1, pArgumentDescs: &arg, NodeMask: 0 };
let mut sig = None;
unsafe { dev.CreateCommandSignature(&desc, None, &mut sig) }.map_err(|e| format!("CreateCommandSignature: {e}"))?;
let sig: ID3D12CommandSignature = sig.ok_or("CreateCommandSignature")?;
*made = Some((windows::core::Interface::as_raw(dev) as usize, sig.clone()));
Ok(sig)
}

const INDIRECT_SLICER: &str = r#"
#define RS "RootConstants(num32BitConstants=3, b0), SRV(t0), UAV(u0)"
cbuffer C : register(b0) { uint rounds; uint most; uint pieces; };
ByteAddressBuffer args : register(t0);
RWByteAddressBuffer cmds : register(u0);
void put(uint r, uint3 n, uint3 o) {
for (uint i = 0; i < pieces; i++) {
uint at = (r * pieces + i) * 44;
cmds.Store4(at, uint4(n, i));
cmds.Store4(at + 16, uint4(o, 0));
cmds.Store3(at + 32, n);
}
}
[RootSignature(RS)]
[numthreads(1, 1, 1)]
void main() {
uint3 g = min(args.Load3(0), 65535);
uint3 s;
s.x = min(g.x, max(most, 1));
s.y = s.x == g.x ? min(g.y, max(most / max(g.x, 1), 1)) : 1;
s.z = s.x == g.x && s.y == g.y ? min(g.z, max(most / max(g.x, 1) / max(g.y, 1), 1)) : 1;
uint3 c = (g + s - 1) / s;
bool partial = any(g == 0) ? false : c.x > rounds || c.y > rounds / max(c.x, 1) || c.z > rounds / max(c.x * c.y, 1);
uint r = 0;
if (!partial && all(g != 0))
for (uint oz = 0; oz < g.z; oz += s.z)
for (uint oy = 0; oy < g.y; oy += s.y)
for (uint ox = 0; ox < g.x; ox += s.x) {
uint3 o = uint3(ox, oy, oz);
put(r++, min(s, g - o), o);
}
for (; r < rounds; r++) put(r, 0, 0);
uint at = (rounds * pieces * 44 + 7) & ~7u;
cmds.Store3(at, partial ? g : 0);
}
"#;

pub(crate) fn chain_tail_offset(rounds: u32, pieces: u32) -> u64 {
(u64::from(rounds) * u64::from(pieces) * u64::from(CHAIN_COMMAND_BYTES)).next_multiple_of(8)
}

fn indirect_slicer(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> {
static MADE: Mutex<Option<(usize, ID3D12RootSignature, ID3D12PipelineState)>> = Mutex::new(None);
let mut made = MADE.lock().unwrap();
if let Some((_, rs, pso)) = made.as_ref().filter(|m| m.0 == windows::core::Interface::as_raw(dev) as usize) {
return Ok((rs.clone(), pso.clone()));
}
let dxil = super::dxc::compile(INDIRECT_SLICER, "main", "cs_6_0", &[])?;
unsafe {
let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).map_err(|e| format!("indirect slicer root signature: {e}"))?;
let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&rs),
CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() }, ..Default::default() };
let pso: ID3D12PipelineState = dev.CreateComputePipelineState(&desc).map_err(|e| format!("indirect slicer pipeline: {e}"))?;
*made = Some((windows::core::Interface::as_raw(dev) as usize, rs.clone(), pso.clone()));
Ok((rs, pso))
}
}

pub(crate) unsafe fn chain_commands_buffer(dev: &ID3D12Device, rounds: u32, pieces: u32) -> Option<ID3D12Resource> {
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: chain_tail_offset(rounds, pieces) + 12, Height: 1, DepthOrArraySize: 1, MipLevels: 1,
SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, ..Default::default()
};
let mut resource = None;
dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, CreationNodeMask: 1, VisibleNodeMask: 1, ..Default::default() },
D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, None, &mut resource).ok()?;
resource
}

pub(crate) unsafe fn record_indirect_slicer(
list: &ID3D12GraphicsCommandList, args: u64, rounds: u32, most: u64, pieces: u32, out: &ID3D12Resource,
) -> Result<(), String> {
let mut dev = None;
list.GetDevice(&mut dev).map_err(|e| e.to_string())?;
let (rs, pso) = indirect_slicer(&dev.ok_or("device")?)?;
let constants = [rounds, most.min(u64::from(u32::MAX)) as u32, pieces];
list.SetComputeRootSignature(&rs);
list.SetPipelineState(&pso);
list.SetComputeRoot32BitConstants(0, 3, constants.as_ptr().cast(), 0);
list.SetComputeRootShaderResourceView(1, args);
list.SetComputeRootUnorderedAccessView(2, out.GetGPUVirtualAddress());
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);
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 }) } }]);
Ok(())
}

pub(crate) unsafe fn record_dispatch_chain_indirect<'a>(
list: &ID3D12GraphicsCommandList, sig: &ID3D12CommandSignature, commands: &ID3D12Resource, rounds: u32,
scratch: &ID3D12Resource, pieces: impl IntoIterator<Item = &'a ID3D12PipelineState> + Clone,
) {
let n = pieces.clone().into_iter().count() as u32;
list.SetComputeRootUnorderedAccessView(6, scratch.GetGPUVirtualAddress());
for r in 0..rounds {
for (i, piece) in pieces.clone().into_iter().enumerate() {
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.SetPipelineState(piece);
let offset = (u64::from(r) * u64::from(n) + i as u64) * u64::from(CHAIN_COMMAND_BYTES);
list.ExecuteIndirect(sig, 1, commands, offset, None::<&ID3D12Resource>, 0);
}
}
}

pub(crate) fn dispatch_chain_root_signature(dev: &ID3D12Device, samplers: &[StaticSampler]) -> Result<ID3D12RootSignature, String> {
abi_signature(dev, false, samplers, Some(ChainSlabBinding::RootConstants))
}
Expand Down Expand Up @@ -1551,7 +1690,7 @@ fn abi_signature(

#[cfg(test)]
mod slab_tests {
use super::{chain_slab_parameter, dispatch_slabs, ChainSlabBinding};
use super::{chain_slab_parameter, chain_tail_offset, dispatch_slabs, ChainSlabBinding, CHAIN_COMMAND_BYTES};
use windows::Win32::Graphics::Direct3D12::{
D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS,
D3D12_ROOT_PARAMETER_TYPE_CBV,
Expand All @@ -1573,6 +1712,17 @@ mod slab_tests {
}
}

#[test]
fn indirect_whole_arguments_follow_aligned_piece_commands() {
for (rounds, pieces) in [(1, 2), (16, 9), (1024, 64)] {
let commands = u64::from(rounds * pieces * CHAIN_COMMAND_BYTES);
let tail = chain_tail_offset(rounds, pieces);
assert!(tail >= commands);
assert_eq!(tail % 8, 0);
assert!(tail - commands < 8);
}
}

#[test]
fn slabs_cover_a_dispatch_once_within_their_size() {
for grid in [[1, 1, 1], [2, 3, 2], [240, 135, 1], [65_535, 2, 1], [5, 1, 7]] {
Expand Down
45 changes: 45 additions & 0 deletions crates/xcl/src/hle/d3d12x/bind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,18 @@ fn signature_dispatches(sig: usize) -> bool {
DISPATCH_SIGNATURES.lock().unwrap().as_ref().is_some_and(|s| s.contains(&sig))
}

/// Command signatures made of one Dispatch argument, keyed to their stride.
static DISPATCH_ONLY: Mutex<Option<HashMap<usize, u32>>> = Mutex::new(None);

pub(super) fn note_dispatch_only_signature(sig: usize, stride: Option<u32>) {
let mut signatures = DISPATCH_ONLY.lock().unwrap();
let signatures = signatures.get_or_insert_with(Default::default);
match stride {
Some(stride) => { signatures.insert(sig, stride); }
None => { signatures.remove(&sig); }
}
}

/// #59 ExecuteIndirect(signature, max count, arguments, offset, count buffer, offset): with a
/// translated pipeline, on XCL's ABI with the kept root arguments (signatures that change root
/// arguments themselves cannot be – skipped, logged)
Expand All @@ -300,6 +312,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us
}
let (pso, bound_unbuilt) = super::pso_async::resolve_wait_bound(raw_pso);
let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso));
let args_off_title = args_off;
let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf));
if !gfx && !compute {
// A pipeline still being built (or whose build failed): its stand-in draws nothing, and
Expand Down Expand Up @@ -359,6 +372,27 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us
return;
}
let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return };
if compute && max == 1 && count_buf == 0 && DISPATCH_ONLY.lock().unwrap().as_ref().is_some_and(|m| m.contains_key(&sig)) {
let chained = indirect_address(args, args_off_title, args_off).map_or(Ok(false), |address| {
super::real::dispatch_chain::execute_indirect(list, pso, with(this, |s| s.allocator), address,
|| bind_abi(this, list, pso, false))
});
match chained {
Ok(true) => {
count(DISPATCHES);
return;
}
Ok(false) => {}
Err(e) => {
count(DISPATCHES_SKIPPED);
static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
if N.fetch_add(1, Ordering::Relaxed) < 4 {
crate::xlog_warn!("D3D12.X: split ExecuteIndirect skipped: {e}");
}
return;
}
}
}
match bind_abi(this, list, pso, gfx) {
Ok(()) => {
if compute {
Expand Down Expand Up @@ -401,6 +435,17 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us
}
}

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) => {
super::real::uma_va_of(base + title_offset as usize)
}
Some(_) => None,
None => Some(ID3D12Resource::from_raw_borrowed(&(resource as *mut c_void))?.GetGPUVirtualAddress())
.filter(|&address| address != 0).and_then(|address| address.checked_add(pc_offset)),
}
}

/// XCL's own buffer for `fresh_indirect_arguments` (device, buffer): COMMON between its uses
static ARGUMENT_ORDER: Mutex<Option<(usize, ID3D12Resource)>> = Mutex::new(None);

Expand Down
4 changes: 4 additions & 0 deletions crates/xcl/src/hle/d3d12x/device_x.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1321,6 +1321,10 @@ pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_voi
}
if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() {
super::bind::note_signature_dispatches(*ppv as usize, list.iter().any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32));
let stride = u32::from_le_bytes(pc[..4].try_into().unwrap());
let dispatch_only = list.len() == 1 && list[0][0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32
&& stride >= 12 && stride % 4 == 0;
super::bind::note_dispatch_only_signature(*ppv as usize, dispatch_only.then_some(stride));
}
hr
}
Expand Down
Loading
Loading