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
154 changes: 120 additions & 34 deletions crates/xcl/src/hle/d3d12x/bind.rs

Large diffs are not rendered by default.

55 changes: 44 additions & 11 deletions crates/xcl/src/hle/d3d12x/console_list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,8 @@ struct ListState {
uma: Vec<usize>,
/// where the next draw's argument table and io go (blocks in `uma`)
arena: crate::gpu::uma::Arena,
/// Retained PC pipeline objects bound to this recording, dropped on Reset or Release.
retained_psos: HashMap<usize, ID3D12PipelineState>,
}

static LISTS: Mutex<Option<HashMap<usize, ListState>>> = Mutex::new(None);
Expand Down Expand Up @@ -389,7 +391,8 @@ unsafe extern "system" fn cl_release(this: *mut c_void) -> u32 {
})
.unwrap_or(0);
if left == 0 {
if let Some(st) = LISTS.lock().unwrap().as_mut().and_then(|m| m.remove(&obj)) {
let dead = LISTS.lock().unwrap().as_mut().and_then(|m| m.remove(&obj));
if let Some(st) = dead {
free_uma(&st.uma);
let release: unsafe extern "system" fn(usize) -> u32 = std::mem::transmute(pc_vtable_call(st.pc, 2));
release(st.pc);
Expand Down Expand Up @@ -422,20 +425,36 @@ unsafe extern "system" fn cl_close(this: *mut c_void) -> HRESULT {

unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, pso: *mut c_void) -> HRESULT {
let obj = this as usize;
let Some((pc, old_alloc, blocks)) = with_list(obj, |st| {
let Some((pc, old_alloc, blocks, old_psos)) = with_list(obj, |st| {
st.chunks.clear();
st.arena = Default::default();
(st.pc, std::mem::replace(&mut st.allocator, allocator as usize), std::mem::take(&mut st.uma))
(
st.pc,
std::mem::replace(&mut st.allocator, allocator as usize),
std::mem::take(&mut st.uma),
std::mem::take(&mut st.retained_psos),
)
}) else {
return crate::util::E_FAIL;
};
drop(old_psos);
// what the previous recording left in unified memory lives until its allocator resets
if !blocks.is_empty() {
PENDING.lock().unwrap().get_or_insert_with(HashMap::new).entry(old_alloc).or_default().extend(blocks);
}
with_list(obj, |st| new_chunk(obj, st));
let init_pso = super::pso_async::resolve_for_bind_retained(pc_pso(pso) as usize);
let init_ptr = init_pso.ptr();
let f: unsafe extern "system" fn(usize, *mut c_void, *mut c_void) -> HRESULT = std::mem::transmute(pc_vtable_call(pc, 10));
f(pc, allocator, pc_pso(pso))
let hr = f(pc, allocator, init_ptr as *mut c_void);
if hr >= 0 {
if let Some(com) = init_pso.into_com() {
with_list(obj, |st| {
st.retained_psos.entry(init_ptr).or_insert(com);
});
}
}
hr
}

unsafe extern "system" fn cl_dispatch(this: *mut c_void, x: u32, y: u32, z: u32) {
Expand Down Expand Up @@ -606,7 +625,15 @@ pub unsafe fn create(pc: *mut c_void) -> *mut c_void {
pub unsafe fn create_with_allocator(pc: *mut c_void, allocator: *mut c_void) -> *mut c_void {
let obj = Box::into_raw(vec![0u8; OBJECT_BYTES].into_boxed_slice()) as *mut u8 as usize;
*field(obj, 0) = list_vtable();
let mut st = ListState { pc: pc as usize, allocator: allocator as usize, refs: 1, chunks: Vec::new(), uma: Vec::new(), arena: Default::default() };
let mut st = ListState {
pc: pc as usize,
allocator: allocator as usize,
refs: 1,
chunks: Vec::new(),
uma: Vec::new(),
arena: Default::default(),
retained_psos: HashMap::new(),
};
new_chunk(obj, &mut st);
LISTS.lock().unwrap().get_or_insert_with(HashMap::new).insert(obj, st);
obj as *mut c_void
Expand Down Expand Up @@ -881,12 +908,13 @@ pub unsafe fn close(obj: *mut c_void) -> Result<Translation, String> {
// a pipeline still being built in the background is waited for; if
// the background translation failed, skip instead of binding XCL's
// ABI root signature onto the stand-in
let real = super::pso_async::resolve_wait((*p).pc);
if !super::real::is_translated_compute(real) {
let real = super::pso_async::resolve_wait_retained((*p).pc);
let real_ptr = real.ptr();
if !super::real::is_translated_compute(real_ptr) {
out.skipped_dispatches += 1;
continue;
}
let user_sgprs = super::real::pso_user_sgprs(real);
let user_sgprs = super::real::pso_user_sgprs(real_ptr);
let inline = layout.as_ref().map_or(0, |l| inline_for(l, user_sgprs) as usize).min(table.len());
let table_at = uma_copy(st, &table[inline..]).ok_or("UMA: argument table")?;
let mut io = match layout.as_ref() {
Expand All @@ -898,7 +926,7 @@ pub unsafe fn close(obj: *mut c_void) -> Result<Translation, String> {
let io_at = uma_copy(st, bytemuck_u32(&io)).ok_or("UMA: io")?;
let res_at = uma_copy(st, &[0u8; 256]).ok_or("UMA: res")?;
// the pipeline's own root signature when it has static samplers
let own = super::real::pso_root_signature(real).or(((*p).rs != 0).then_some((*p).rs)).map(|r| r as *mut c_void);
let own = super::real::pso_root_signature(real_ptr).or(((*p).rs != 0).then_some((*p).rs)).map(|r| r as *mut c_void);
match own.as_ref().and_then(|r| ID3D12RootSignature::from_raw_borrowed(r)) {
Some(r) => list.SetComputeRootSignature(r),
None => list.SetComputeRootSignature(rs.as_ref().ok_or("no XCL ABI root signature")?),
Expand All @@ -909,10 +937,15 @@ pub unsafe fn close(obj: *mut c_void) -> Result<Translation, String> {
for k in 0..4 {
list.SetComputeRootUnorderedAccessView(2 + k as u32, windows.get(k).copied().unwrap_or(uma_va));
}
let raw = real as *mut c_void;
let raw = real_ptr as *mut c_void;
let pc = ID3D12PipelineState::from_raw_borrowed(&raw).ok_or("PSO")?;
list.SetPipelineState(pc);
super::real::dispatch_chain::dispatch(&list, real, st.allocator, [x, y, z])?;
if !st.retained_psos.contains_key(&real_ptr) {
if let Some(com) = real.clone().into_com() {
st.retained_psos.insert(real_ptr, com);
}
}
super::real::dispatch_chain::dispatch(&list, real_ptr, st.allocator, [x, y, z])?;
out.dispatches += 1;
}
_ => out.skipped_dispatches += 1,
Expand Down
8 changes: 5 additions & 3 deletions crates/xcl/src/hle/d3d12x/device_x.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,13 +95,15 @@ unsafe fn create_list(this: *mut c_void, node: u32, ty: u32, alloc: usize, pso:
let hr = if super::console_list::enabled() {
real::dev_create_command_list_x(this, node, ty, alloc, pso, riid, ppv)
} else {
let resolved_pso = super::pso_async::resolve_for_bind(pso);
let hr = real::dev_create_command_list(this, node, ty, alloc, resolved_pso, riid, ppv);
let resolved_pso = super::pso_async::resolve_for_bind_retained(pso);
let resolved_ptr = resolved_pso.ptr();
let hr = real::dev_create_command_list(this, node, ty, alloc, resolved_ptr, riid, ppv);
if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() {
super::list_x::on_create(*ppv, alloc, pso, D3D12_COMMAND_LIST_TYPE(ty as i32));
super::list_x::retain_pso(*ppv, resolved_pso);
super::dred::reset(*ppv);
if pso != 0 {
super::dred::mark_pipeline(*ppv, pso, resolved_pso);
super::dred::mark_pipeline(*ppv, pso, resolved_ptr);
}
}
hr
Expand Down
134 changes: 117 additions & 17 deletions crates/xcl/src/hle/d3d12x/late_release.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ impl Held {
}
let (fence, value) = self.fences.get_mut(&key).unwrap();
if q.Signal(&*fence, *value + 1).is_err() {
self.fences.remove(&key);
ok = false;
break;
}
Expand Down Expand Up @@ -95,6 +96,23 @@ pub fn enabled() -> bool {
/// how long a last `Release` itself waits for queues with nothing to do to say so
const IDLE_WAIT: Duration = Duration::from_micros(300);

fn ensure_thread() {
static THREAD: std::sync::Once = std::sync::Once::new();
THREAD.call_once(|| {
let _ = std::thread::Builder::new().name("xcl-late-release".into()).spawn(|| loop {
std::thread::sleep(TICK);
unsafe { drain_known(false) };
});
});
}

/// Queue `obj` for release on the background thread once all queues pass the current fence,
/// without spinning the caller thread.
pub unsafe fn hold_deferred(obj: usize) {
HELD.lock().unwrap().get_or_insert_with(Held::default).open.push(obj);
ensure_thread();
}

/// `res` (an adopted resource) holds one reference that is now this module's. With no work in
/// flight it goes before this returns (the queues pass a fence value at once): a title that
/// frees the memory under a resource right after its last `Release` finds it unpinned, as
Expand All @@ -113,13 +131,18 @@ pub unsafe fn hold(res: usize) {
// A thread of its own lets the held ones go: the title may release a resource and then
// wait for its memory without another submit (an imported heap pins the pages under its
// resources – unmapping them stood still while one was held "until the next submit").
static THREAD: std::sync::Once = std::sync::Once::new();
THREAD.call_once(|| {
let _ = std::thread::Builder::new().name("xcl-late-release".into()).spawn(|| loop {
std::thread::sleep(TICK);
unsafe { drain_known(false) };
});
});
ensure_thread();
}

unsafe fn release_obj(obj: usize) {
let raw = obj as *mut c_void;
let release_fn = if super::real::is_adopted(raw) {
super::real::orig_fn(raw, 2)
} else {
*(*(raw as *const *const usize)).add(2)
};
let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(release_fn);
f(raw);
}

/// Release what every queue XCL knows of is past: the title's, the tile-mapping one, the
Expand All @@ -128,26 +151,32 @@ pub unsafe fn drain_known(seal_now: bool) {
if HELD.lock().unwrap().as_ref().is_none_or(Held::is_empty) {
return;
}
let mut queues: Vec<ID3D12CommandQueue> = Vec::new();
for raw in super::present::known_queues() {
let raw = raw as *mut c_void;
if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&raw) {
queues.push(q.clone());
}
}
let mut queues = super::present::known_queue_refs();
queues.extend(super::sparse::queue());
queues.extend(super::title_textures::upload_queues());
let gone = match HELD.lock().unwrap().as_mut() {
Some(h) => h.drain(&queues, seal_now),
None => return,
};
// (outside the lock: a release may end other objects, whose releases come back here)
for res in gone {
let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(super::real::orig_fn(res as *mut c_void, 2));
f(res as *mut c_void);
for obj in gone {
release_obj(obj);
}
}

#[cfg(test)]
pub(super) fn forget_queue_for_test(queue: usize) {
if let Some(h) = HELD.lock().unwrap().as_mut() {
h.fences.remove(&queue);
}
}

#[cfg(test)]
pub(super) fn is_held(obj: usize) -> bool {
let g = HELD.lock().unwrap();
g.as_ref().is_some_and(|h| h.open.contains(&obj) || h.sealed.iter().any(|b| b.dead.contains(&obj)))
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -208,4 +237,75 @@ mod tests {
assert_eq!(unsafe { held.drain(&[], false) }, vec![0x1000]);
assert!(held.is_empty());
}

/// An unadopted COM object held until GPU retirement is released safely via vtable slot 2
/// once the blocking queue passes its batch fence.
#[test]
fn unadopted_com_object_is_released_after_queue_retirement() {
use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering};
use std::sync::Arc;
use windows::core::GUID;

#[repr(C)]
struct TestComObj {
vt: *const [usize; 3],
refs: AtomicU32,
drops: Arc<AtomicUsize>,
}
unsafe extern "system" fn qi(_: *mut c_void, _: *const GUID, out: *mut *mut c_void) -> i32 {
if !out.is_null() {
*out = std::ptr::null_mut();
}
-2147467262 // E_NOINTERFACE
}
unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 {
(&*(this as *const TestComObj)).refs.fetch_add(1, Ordering::AcqRel) + 1
}
unsafe extern "system" fn release(this: *mut c_void) -> u32 {
let n = (&*(this as *const TestComObj)).refs.fetch_sub(1, Ordering::AcqRel) - 1;
if n == 0 {
let obj = Box::from_raw(this as *mut TestComObj);
obj.drops.fetch_add(1, Ordering::AcqRel);
}
n
}
let vt: *const [usize; 3] = Box::leak(Box::new([qi as usize, add_ref as usize, release as usize]));

unsafe {
let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0) else {
return crate::gpu::recomp::runner::skip_test("no GPU");
};
let queue: ID3D12CommandQueue =
dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).unwrap();
let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
queue.Wait(&gate, 1).unwrap();

let drops = Arc::new(AtomicUsize::new(0));
let obj = Box::into_raw(Box::new(TestComObj {
vt,
refs: AtomicU32::new(1),
drops: drops.clone(),
})) as usize;
assert!(!super::super::real::is_adopted(obj as *mut c_void));

let mut held = Held::default();
held.open.push(obj);
let queues = [queue];
assert!(held.drain(&queues, false).is_empty());
assert_eq!(drops.load(Ordering::Acquire), 0);

gate.Signal(1).unwrap();
let start = Instant::now();
let mut gone = Vec::new();
while gone.is_empty() && start.elapsed() < Duration::from_secs(10) {
std::thread::sleep(Duration::from_millis(5));
gone = held.drain(&queues, false);
}
assert_eq!(gone, vec![obj]);
for raw in gone {
release_obj(raw);
}
assert_eq!(drops.load(Ordering::Acquire), 1);
}
}
}
Loading
Loading