Skip to content
Open
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
2 changes: 1 addition & 1 deletion crates/xcl/src/hle/d3d12x/alloc_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ pub fn created_on(list: usize, raw: usize, ty: i32) {
}
let mut g = STATE.lock().unwrap();
let s = g.get_or_insert_with(State::default);
s.types.entry(raw).or_insert(ty);
s.types.insert(raw, ty);
move_list(s, list, raw);
*s.recordings.entry(list).or_default() += 1;
}
Expand Down
2 changes: 1 addition & 1 deletion crates/xcl/src/hle/d3d12x/bind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us
match bind_abi(this, list, pso, gfx) {
Ok(()) => {
if compute {
match super::real::dispatch_chain::whole(pso) {
match super::real::dispatch_chain::whole(list, pso, with(this, |s| s.allocator)) {
Ok(Some(whole)) => list.SetPipelineState(&whole),
Ok(None) => {}
Err(e) => {
Expand Down
109 changes: 102 additions & 7 deletions crates/xcl/src/hle/d3d12x/list_x.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2816,14 +2816,21 @@ unsafe fn split(list: *mut c_void, dispatch: Option<Deferred>) -> Option<*mut c_
}
let next_pc = match next_pc {
Some(p) => p,
None => match real::create_raw_pc_command_list(dev.as_raw(), ty, super::alloc_pool::current(alloc), init_pso) {
Some(p) => p,
None => {
static CREATE_ERR: AtomicU64 = AtomicU64::new(0);
warn(&CREATE_ERR, "mid-list split", format_args!("CreateCommandList failed"));
return None;
None => {
let pc_alloc = super::alloc_pool::current(alloc);
match real::create_raw_pc_command_list(dev.as_raw(), ty, pc_alloc, init_pso) {
Some(p) => {
super::alloc_pool::created_on(p as usize, pc_alloc, ty.0);
real::dispatch_chain::list_reset(p as usize);
p
}
None => {
static CREATE_ERR: AtomicU64 = AtomicU64::new(0);
warn(&CREATE_ERR, "mid-list split", format_args!("CreateCommandList failed"));
return None;
}
}
},
}
};

// the next segment is a recording of its own (reset or made here, not through `cl_reset`)
Expand Down Expand Up @@ -7233,6 +7240,94 @@ mod tests {
}
}

/// A fresh Wait-split segment created after `alloc_pool` swapped the title's allocator must
/// register on its active PC backing allocator (`pc_alloc`) so `dispatch_chain` keys scratch
/// and retained PSOs to `pc_alloc` rather than the title allocator (which a later Reset can
/// reuse and reset while the split segment on `pc_alloc` is still alive).
#[test]
fn wait_split_fresh_segment_tracks_swapped_backing_allocator() {
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
if !super::super::alloc_pool::enabled() {
return;
}
unsafe {
let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else {
crate::gpu::recomp::runner::skip_test("no GPU");
return;
};
let a_title: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).unwrap();
let a_raw = a_title.as_raw() as usize;
if !real::is_adopted(a_title.as_raw()) {
real::adopt(a_title.as_raw(), real::Kind::CommandAllocator);
}

let l_hold: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &a_title, None).unwrap();
real::adopt(l_hold.as_raw(), real::Kind::CommandList);
on_create(l_hold.as_raw(), a_raw, 0, D3D12_COMMAND_LIST_TYPE_COMPUTE);
l_hold.Close().unwrap();

let raw_c: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &a_title, None).unwrap();
let pc_c0 = raw_c.into_raw();
real::adopt(pc_c0, real::Kind::CommandList);
on_create(pc_c0, a_raw, 0, D3D12_COMMAND_LIST_TYPE_COMPUTE);
super::super::bind::reset(pc_c0, a_raw, 0);
let wrap_c = super::super::title_list::wrap(pc_c0);

// Title Reset while both lists still record on `a_title` swaps `a_title` -> backing B.
a_title.Reset().unwrap();
let pc_alloc_b = super::super::alloc_pool::current(a_raw);
assert_ne!(pc_alloc_b, a_raw, "title Reset with live recordings must swap to a backing PC allocator");

// Close and reset `wrap_c` on `a_title` so `pc_c0` records on backing B.
let close_fn: unsafe extern "system" fn(*mut c_void) -> i32 = std::mem::transmute(*(*(wrap_c as *const *const usize)).add(9));
let reset_fn: unsafe extern "system" fn(*mut c_void, usize, usize) -> i32 = std::mem::transmute(*(*(wrap_c as *const *const usize)).add(10));
assert_eq!(close_fn(wrap_c), 0);
assert_eq!(reset_fn(wrap_c, a_raw, 0), 0);
assert_eq!(super::super::alloc_pool::recording_backing_for_test(pc_c0 as usize), Some(pc_alloc_b));

// Trigger a mid-list Wait split with no idle spare -> creates a fresh segment on B.
let cell_a = Box::new(AtomicU64::new(0));
let cell_b = Box::new(AtomicU64::new(0));
let va_a = &*cell_a as *const AtomicU64 as u64;
let va_b = &*cell_b as *const AtomicU64 as u64;
note_write64_recorded(pc_c0, va_a, 1);
{
let mut g = SYNC_GRAPH.lock().unwrap();
let entry = g.get_or_insert_with(SyncGraph::default).cells.entry(va_b).or_default();
entry.recorded_max = entry.recorded_max.max(1);
entry.recorded_list_type = Some(D3D12_COMMAND_LIST_TYPE_DIRECT);
}
wait64_x(pc_c0, va_b, D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32, 1, 0, 0);

let mut segs = Vec::new();
assert!(super::super::title_list::push_segments(wrap_c, &mut segs));
assert_eq!(segs.len(), 2, "mid-list Wait64 after Write64 must split into 2 segments");
let seg1 = segs[1];
assert_ne!(seg1, pc_c0);

// Fresh split segment must be tracked on B (not untracked / falling back to title A).
assert_eq!(super::super::alloc_pool::recording_backing_for_test(seg1 as usize), Some(pc_alloc_b));
assert_eq!(real::dispatch_chain::resolve_allocator_for_test(seg1 as usize, a_raw), pc_alloc_b);

// Releasing `l_hold` frees A in `aside[A]`; a title Reset now reuses and resets A
// while B stays alive for `seg1`, so `seg1` must still resolve to B.
drop(l_hold);
a_title.Reset().unwrap();
assert_eq!(super::super::alloc_pool::current(a_raw), a_raw, "title Reset must reuse freed A");
assert_eq!(super::super::alloc_pool::recording_backing_for_test(seg1 as usize), Some(pc_alloc_b));
assert_eq!(real::dispatch_chain::resolve_allocator_for_test(seg1 as usize, a_raw), pc_alloc_b);

assert_eq!(close_fn(wrap_c), 0);
let rel_fn: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(wrap_c as *const *const usize)).add(2));
assert_eq!(rel_fn(wrap_c), 0);
drop(a_title);
if let Some(gr) = SYNC_GRAPH.lock().unwrap().as_mut() {
gr.cells.remove(&va_a);
gr.cells.remove(&va_b);
}
}
}

/// A buffer outside unified memory that has a mirror is bound at its mirror again without
/// asking whether the title's memory is readable: the source made unreadable after the first
/// bind still binds the same mirror (before, the bind asked `readable` first and gave the
Expand Down
105 changes: 92 additions & 13 deletions crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,24 @@ pub(super) fn forget(pso: usize) {
drop(gone); // releasing a tail PSO also goes through forget_pso
}

pub(in crate::hle::d3d12x) unsafe fn whole(pso: usize) -> Result<Option<ID3D12PipelineState>, String> {
let chain = CHAINS.lock().unwrap().get(&pso).cloned();
chain.map(|c| c.whole()).transpose()
fn resolve_allocator_with(pool_enabled: bool, list: usize, allocator: usize, backing: impl FnOnce(usize) -> Option<usize>) -> usize {
if pool_enabled { backing(list).unwrap_or(allocator) } else { allocator }
}

fn resolve_allocator(list: usize, allocator: usize) -> usize {
resolve_allocator_with(super::super::alloc_pool::enabled(), list, allocator, super::super::alloc_pool::recording_backing)
}

#[cfg(test)]
pub(in crate::hle::d3d12x) fn resolve_allocator_for_test(list: usize, allocator: usize) -> usize {
resolve_allocator(list, allocator)
}

pub(in crate::hle::d3d12x) unsafe fn whole(list: &ID3D12GraphicsCommandList, pso: usize, allocator: usize) -> Result<Option<ID3D12PipelineState>, String> {
let Some(chain) = CHAINS.lock().unwrap().get(&pso).cloned() else { return Ok(None) };
let whole = chain.whole()?;
retain_whole(resolve_allocator(list.as_raw() as usize, allocator), chain);
Ok(Some(whole))
}

struct Scratch {
Expand All @@ -121,8 +136,8 @@ impl Drop for Scratch {
}

struct Recording {
scratch: Arc<Scratch>,
first: ID3D12PipelineState,
scratch: Option<Arc<Scratch>>,
first: Option<ID3D12PipelineState>,
chain: Arc<Chain>,
}

Expand Down Expand Up @@ -182,6 +197,19 @@ unsafe fn scratch_for(dev: &ID3D12Device, list: usize, allocator: usize, needed:
Some((s, false))
}

fn retain_whole(allocator: usize, chain: Arc<Chain>) {
if allocator == 0 { return; }
{
let mut map = RECORDINGS.lock().unwrap();
let entries = map.entry(allocator).or_default();
if !entries.iter().any(|r| Arc::ptr_eq(&r.chain, &chain)) {
entries.push(Arc::new(Recording { scratch: None, first: None, chain }));
return;
}
}
drop(chain); // outside RECORDINGS.lock()
}

pub(in crate::hle::d3d12x) fn allocator_reset(allocator: usize) {
let recordings = RECORDINGS.lock().unwrap().remove(&allocator);
drop(recordings);
Expand All @@ -208,10 +236,8 @@ pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList,
let Some(chain) = chain else { list.Dispatch(x, y, z); return Ok(()) };
if grid.contains(&0) { return Ok(()); }
// A title Reset can switch to a different PC allocator while this
// recording is still submitted on the old one. Retain by backing.
let allocator = if super::super::alloc_pool::enabled() {
super::super::alloc_pool::recording_backing(list.as_raw() as usize).unwrap_or(0)
} else { allocator };
// recording is still submitted on the old one; untracked lists keep theirs.
let allocator = resolve_allocator(list.as_raw() as usize, allocator);
let group = u64::from(chain.words) * 4;
let needed = grid.into_iter().fold(group, |s, n| s.saturating_mul(n as u64));
WANTED.fetch_max(needed, Ordering::Relaxed);
Expand All @@ -220,22 +246,24 @@ pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList,
let most = scratch.as_ref().map_or(1, |(s, _)| (s.bytes / group).max(1));
let slabs = pso::dispatch_slabs(grid, most);
let Some((scratch, used)) = scratch else {
list.SetPipelineState(&chain.whole()?);
let whole = chain.whole()?;
retain_whole(allocator, chain);
list.SetPipelineState(&whole);
list.Dispatch(x, y, z);
return Ok(());
};
let first = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).ok_or("first compute piece")?.clone();
let held = Arc::new(Recording { scratch, first, chain });
let held = Arc::new(Recording { scratch: Some(scratch), first: Some(first), chain });
RECORDINGS.lock().unwrap().entry(allocator).or_default().push(held.clone());
DISPATCHES.fetch_add(1, Ordering::Relaxed);
SLABS.fetch_add(slabs.len() as u64, Ordering::Relaxed);
pso::record_dispatch_chain(list, grid, most, &held.scratch.buffer, used, std::iter::once(&held.first).chain(&held.chain.tail));
pso::record_dispatch_chain(list, grid, most, &held.scratch.as_ref().unwrap().buffer, used, std::iter::once(held.first.as_ref().unwrap()).chain(&held.chain.tail));
Ok(())
}

#[cfg(test)]
mod tests {
use super::{scratch_bytes, LEAST};
use super::*;

const MB: u64 = 1 << 20;

Expand Down Expand Up @@ -284,4 +312,55 @@ mod tests {
assert_eq!(scratch_bytes(9 * MB, 9 * MB, 4 * MB, None, 400 * MB, 384 * MB), (9 * MB, true));
assert_eq!(scratch_bytes(9 * MB, 9 * MB, 4 * MB, Some(MB), 400 * MB, 384 * MB), (9 * MB, true));
}

unsafe extern "system" fn unused_pso_fn(_: *mut c_void, _: *const c_void, _: *const GUID, _: *mut *mut c_void) -> HRESULT { crate::util::E_FAIL }

#[test]
fn untracked_list_keeps_caller_allocator_when_alloc_pool_is_enabled() {
assert_eq!(resolve_allocator_with(true, 0x1000, 0x2000, |_| None), 0x2000);
assert_eq!(resolve_allocator_with(true, 0x1000, 0x2000, |_| Some(0x3000)), 0x3000);
assert_eq!(resolve_allocator_with(false, 0x1000, 0x2000, |_| Some(0x3000)), 0x2000);
assert_eq!(resolve_allocator(0x7D00_DEAD, 0x2000), 0x2000);
}

#[test]
fn whole_fallback_and_indirect_retain_chain_until_allocator_reset() {
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
unsafe {
let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else {
return crate::gpu::recomp::runner::skip_test("no GPU");
};
let mut ser = None;
D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC::default(), D3D_ROOT_SIGNATURE_VERSION_1, &mut ser, None).unwrap();
let ser = ser.unwrap();
let rs: ID3D12RootSignature = dev.CreateRootSignature(0, std::slice::from_raw_parts(ser.GetBufferPointer() as *const u8, ser.GetBufferSize())).unwrap();
let cs = dummy_cs_bytecode();
let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::ManuallyDrop::new(Some(rs.clone())), CS: D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as _, BytecodeLength: cs.len() }, ..Default::default() };
let whole_pso: ID3D12PipelineState = dev.CreateComputePipelineState(&desc).unwrap();
std::mem::ManuallyDrop::drop(&mut desc.pRootSignature);
let bundle_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_BUNDLE).unwrap();
let bundle: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_BUNDLE, &bundle_alloc, None).unwrap();
bundle.SetComputeRootSignature(&rs);
let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap();
let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap();
let mk = |words| Arc::new(Chain { builder: Arc::new(PipelineBuilder { device: dev.clone(), create: unused_pso_fn, signature: rs.clone(), flags: D3D12_PIPELINE_STATE_FLAG_NONE, node: 0, record: 0 }), tail: Vec::new(), words, whole_code: Vec::new(), whole: OnceLock::from(whole_pso.clone()), build_whole: Mutex::new(()) });
let (c1, c2) = (mk(4), mk(4));
let (w1, w2) = (Arc::downgrade(&c1), Arc::downgrade(&c2));
let (p1, a1, p2, a2) = (0x7D00_0001usize, 0x7D00_A001usize, 0x7D00_0002usize, 0x7D00_A002usize);
CHAINS.lock().unwrap().extend([(p1, c1), (p2, c2)]);
dispatch(&bundle, p1, a1, [1, 1, 1]).unwrap();
forget(p1);
assert!(w1.upgrade().is_some(), "dispatch whole fallback must retain Chain until allocator_reset");
allocator_reset(a1);
assert!(w1.upgrade().is_none());
assert!(whole(&list, p2, a2).unwrap().is_some() && whole(&list, p2, a2).unwrap().is_some());
assert_eq!(RECORDINGS.lock().unwrap().get(&a2).map(Vec::len), Some(1));
forget(p2);
assert!(w2.upgrade().is_some(), "whole() must retain Chain until allocator_reset");
allocator_reset(a2);
assert!(w2.upgrade().is_none());
bundle.Close().unwrap();
list.Close().unwrap();
}
}
}
Loading