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
173 changes: 169 additions & 4 deletions crates/xcl/src/hle/d3d12x/alloc_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,13 @@ struct Backing {
}

impl Backing {
/// The GPU has passed every submit of a recording on this allocator.
unsafe fn idle(&self) -> bool {
self.marks.values().all(|(f, v)| f.GetCompletedValue() >= *v)
}

unsafe fn free(&self) -> bool {
self.users.is_empty() && self.marks.values().all(|(f, v)| f.GetCompletedValue() >= *v)
self.users.is_empty() && self.idle()
}
}

Expand Down Expand Up @@ -106,6 +111,13 @@ pub(super) fn recording_backing_for_test(list: usize) -> Option<usize> {
STATE.lock().unwrap().as_ref()?.of_list.get(&list).copied()
}

/// The title's allocator `alloc` stands for the PC allocator `pc` (as after a Reset put its own
/// aside); `pc == alloc` ends that.
#[cfg(test)]
pub(super) fn stand_in_for_test(alloc: usize, pc: usize) {
STATE.lock().unwrap().get_or_insert_with(State::default).cur.insert(alloc, pc);
}

/// The PC allocator the title's allocator `alloc` stands for now.
pub fn current(alloc: usize) -> usize {
if !enabled() {
Expand Down Expand Up @@ -185,20 +197,50 @@ pub unsafe fn forget(alloc: usize) {
};
// (outside the lock: their Release comes back here)
for b in made {
// what ended recordings on it used goes with it
super::console_list::allocator_reset(b as *mut c_void);
drop(ID3D12CommandAllocator::from_raw(b as *mut c_void));
}
}

/// The title resets its allocator `alloc`. `None`: reset it as it is (nothing holds a
/// recording on it, or this is off). `Some(hr)`: done here – the PC allocator in use was put
/// aside with its recordings and another one took its place.
///
/// What ended recordings left in unified memory is held per PC allocator
/// (`console_list::hold_until_reset`). It goes back here for the PC allocators of `alloc` whose
/// submits the GPU has passed – not for one put aside because the GPU still runs what was
/// recorded on it (#1358).
pub unsafe fn title_reset(alloc: *mut c_void) -> Option<HRESULT> {
title_reset_with(alloc, |raw| super::real::reset_pc_allocator(raw))
}

/// `title_reset` with the PC Reset supplied (tests).
unsafe fn title_reset_with(alloc: *mut c_void, reset: impl FnMut(*mut c_void) -> HRESULT) -> Option<HRESULT> {
if !enabled() {
return None;
}
let mut g = STATE.lock().unwrap();
let s = g.get_or_insert_with(State::default);
title_reset_in(s, alloc, |raw| super::real::reset_pc_allocator(raw))
let (hr, done) = {
let mut g = STATE.lock().unwrap();
let s = g.get_or_insert_with(State::default);
let hr = title_reset_in(s, alloc, reset);
(hr, done_with(s, alloc as usize))
};
// (outside the lock)
for b in done {
super::console_list::allocator_reset(b as *mut c_void);
}
hr
}

/// The PC allocators of the title's allocator `a` (the one in use and those put aside) whose
/// submits the GPU has passed: the recordings on them that have ended need their memory no more.
unsafe fn done_with(s: &State, a: usize) -> Vec<usize> {
let cur = s.cur.get(&a).copied().unwrap_or(a);
std::iter::once(cur)
.chain(s.aside.get(&a).into_iter().flatten().copied())
.filter(|b| s.backings.get(b).is_none_or(|x| x.idle()))
.collect()
}

/// The allocator transition, with the PC Reset supplied so failure/retry needs no GPU in tests.
Expand Down Expand Up @@ -368,6 +410,129 @@ mod tests {
assert_eq!(fence.releases.get(), 1);
}

/// What an ended recording left in unified memory stays while the GPU has not passed the
/// submits on its PC allocator – also when the title's Reset puts that allocator aside and
/// goes on with another (#1358) – and goes back at the first Reset after the GPU has.
#[test]
fn ended_recordings_keep_their_memory_until_the_gpu_passes_their_allocator() {
use std::cell::Cell;
use std::mem::{offset_of, size_of};

#[repr(C)]
struct Fence {
vtable: *const usize,
value: Cell<u64>,
}
unsafe extern "system" fn completed(this: *mut c_void) -> u64 {
(*this.cast::<Fence>()).value.get()
}
unsafe extern "system" fn release(_: *mut c_void) -> u32 {
0
}
extern "system" fn unexpected_call() { std::process::abort(); }

const SLOT: usize = size_of::<usize>();
let mut vtable = [unexpected_call as usize; size_of::<ID3D12Fence_Vtbl>() / SLOT];
vtable[offset_of!(ID3D12Fence_Vtbl, GetCompletedValue) / SLOT] = completed as usize;
vtable[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.Release) / SLOT] = release as usize;
let mut fence = Fence { vtable: vtable.as_ptr(), value: Cell::new(0) };
let mut ids = Box::new([0u8; 4]);
let alloc = ids.as_mut_ptr() as usize;
let (spare, list, block) = (alloc + 1, alloc + 2, alloc + 3);
// a list recorded on the title's allocator, was submitted, and is gone; the GPU has not
// run the submit yet
created_on(list, alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0);
{
let mut g = STATE.lock().unwrap();
let s = g.as_mut().unwrap();
// the map owns one synthetic fence reference, dropped below
let f = unsafe { ID3D12Fence::from_raw(std::ptr::from_mut(&mut fence).cast()) };
s.backings.get_mut(&alloc).unwrap().marks.insert(1, (f, 1));
// a PC allocator put aside earlier that nothing uses any more
s.aside.insert(alloc, vec![spare]);
}
forget_list(list);
super::super::console_list::hold_until_reset(alloc, vec![block]);

let mut resets = Vec::new();
let first = unsafe { title_reset_with(alloc as *mut c_void, |raw| { resets.push(raw as usize); 0 }) };
let stand_in = current(alloc);
let held = super::super::console_list::take_pending_for_test(alloc);
super::super::console_list::hold_until_reset(alloc, held.clone());
fence.value.set(1);
let second = unsafe { title_reset_with(alloc as *mut c_void, |raw| { resets.push(raw as usize); 0 }) };
let after = super::super::console_list::take_pending_for_test(alloc);
// (before the assertions: nothing synthetic stays in the pool)
{
let mut g = STATE.lock().unwrap();
let s = g.as_mut().unwrap();
for b in [alloc, spare] {
s.backings.remove(&b);
s.cur.remove(&b);
s.aside.remove(&b);
s.types.remove(&b);
}
}
assert_eq!((first, stand_in), (Some(0), spare), "the GPU still runs the submit: the spare takes the place");
assert_eq!(held, vec![block], "the memory of a recording the GPU still runs is held over the Reset");
assert_eq!((second, resets), (Some(0), vec![spare, spare]));
assert!(after.is_empty(), "the GPU passed the submit: the memory goes back");
}

/// The title's Reset (through `real::alloc_reset`) while the GPU has not run a submit of a
/// recording on its allocator: the allocator is put aside, and what the recording left in
/// unified memory stays until the GPU has passed it (#1358).
#[test]
fn a_reset_that_puts_the_allocator_aside_keeps_what_the_gpu_still_reads() {
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_DIRECT, ..Default::default() }).unwrap();
let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap();
let a = alloc.as_raw();
if !super::super::real::is_adopted(a) {
super::super::real::adopt(a, super::super::real::Kind::CommandAllocator);
}
let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap();
let l = list.as_raw() as usize;
created_on(l, a as usize, D3D12_COMMAND_LIST_TYPE_DIRECT.0);
list.Close().unwrap();
// the queue runs the list only once `gate` is signalled
let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
queue.Wait(&gate, 1).unwrap();
queue.ExecuteCommandLists(&[Some(list.cast::<ID3D12CommandList>().unwrap())]);
executed(queue.as_raw(), &[l as *mut c_void]);
// the list's recording ends; what it put in unified memory is held for the allocator
forget_list(l);
let block = l + 1;
super::super::console_list::hold_until_reset(a as usize, vec![block]);

alloc.Reset().unwrap();
let stand_in = current(a as usize);
let held = super::super::console_list::take_pending_for_test(a as usize);
super::super::console_list::hold_until_reset(a as usize, held.clone());

gate.Signal(1).unwrap();
let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
queue.Signal(&done, 1).unwrap();
let start = std::time::Instant::now();
while done.GetCompletedValue() < 1 && start.elapsed().as_secs() < 10 {
std::thread::sleep(std::time::Duration::from_millis(1));
}
let ran = done.GetCompletedValue() >= 1;
alloc.Reset().unwrap();
let after = super::super::console_list::take_pending_for_test(a as usize);
drop(list);
drop(alloc);

assert_ne!(stand_in, a as usize, "the GPU had not run the submit: another PC allocator took the place");
assert_eq!(held, vec![block], "the memory of a recording the GPU had not run is held over the Reset");
assert!(ran, "the queue finishes");
assert!(after.is_empty(), "the GPU passed the submit: the next Reset gives the memory back");
}
}

/// A list recorded once and submitted again after the title reset its allocator: the
/// recording is still there (the device is not removed), the title's allocator goes on with
/// another PC allocator, and the first one is used again once the list has moved on.
Expand Down
7 changes: 4 additions & 3 deletions crates/xcl/src/hle/d3d12x/bind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ struct State {
/// untranslated pipeline – created with it – since SetGraphicsRootSignature binds nothing
rs_gfx: usize,
pso: usize,
/// the PC allocator this recording is on (`alloc_pool`: not always the title's allocator)
allocator: usize,
/// unified memory of this recording (io, argument tables)
uma: Vec<usize>,
Expand Down Expand Up @@ -69,9 +70,9 @@ fn with<R>(list: *mut c_void, f: impl FnOnce(&mut State) -> R) -> R {
f(STATES.lock().unwrap().get_or_insert_with(HashMap::new).entry(list as usize).or_default())
}

/// The list was created or reset onto `allocator` with `initial_pso`: the previous
/// recording's memory is the previous allocator's until that one is reset, and pipeline
/// and root signature state reset per D3D12 `CreateCommandList` / `Reset` semantics.
/// The list was created or reset onto the PC allocator `allocator` with `initial_pso`: the
/// previous recording's memory is the previous allocator's until the GPU is done with it, and
/// pipeline and root signature state reset per D3D12 `CreateCommandList` / `Reset` semantics.
pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) {
let (old, blocks) = with(list, |s| {
let old = std::mem::replace(&mut s.allocator, allocator);
Expand Down
10 changes: 6 additions & 4 deletions crates/xcl/src/hle/d3d12x/console_list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -297,11 +297,12 @@ struct ListState {
}

static LISTS: Mutex<Option<HashMap<usize, ListState>>> = Mutex::new(None);
/// unified-memory blocks of finished recordings, freed when their allocator is reset
/// unified-memory blocks of finished recordings by the PC allocator they were on, freed when the
/// GPU is done with it (it is reset, or `alloc_pool` sees it pass their submits)
static PENDING: Mutex<Option<HashMap<usize, Vec<usize>>>> = Mutex::new(None);

/// Unified-memory blocks a recording on `allocator` uses: freed when it is reset (no
/// allocator known: kept until the next reset of any – never freed early).
/// Unified-memory blocks a recording on the PC allocator `allocator` uses: freed when the GPU is
/// done with it (no allocator known: kept until the next reset of any – never freed early).
pub(super) fn hold_until_reset(allocator: usize, blocks: Vec<usize>) {
if !blocks.is_empty() {
PENDING.lock().unwrap().get_or_insert_with(HashMap::new).entry(allocator).or_default().extend(blocks);
Expand All @@ -318,7 +319,8 @@ pub(crate) fn take_pending_for_test(allocator: usize) -> Vec<usize> {
PENDING.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)).unwrap_or_default()
}

/// An allocator was reset: the GPU no longer uses what its recordings put in unified memory.
/// The GPU no longer uses what recordings on the PC allocator `allocator` put in unified memory:
/// it was reset, or `alloc_pool` saw the GPU pass their submits.
pub fn allocator_reset(allocator: *mut c_void) {
let blocks = PENDING.lock().unwrap().as_mut().and_then(|m| m.remove(&(allocator as usize)));
if let Some(b) = blocks {
Expand Down
58 changes: 54 additions & 4 deletions crates/xcl/src/hle/d3d12x/list_x.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2481,9 +2481,12 @@ unsafe fn try_split_for_wait(list: *mut c_void) -> Option<*mut c_void> {
let dev_raw = dev.as_raw() as usize;

let mut next_pc: Option<*mut c_void> = None;
// the PC allocator the next segment records on
let mut on = super::alloc_pool::current(alloc);
if let Some(spare) = super::title_list::pop_spare(wrapper) {
let ext_spare = *(spare as *const usize);
let reset_hr = super::alloc_pool::reset_list(spare as usize, alloc, ty.0, |pc_alloc| {
on = pc_alloc;
pc::<unsafe extern "system" fn(*mut c_void, usize, usize) -> i32>(spare, PC_RESET)(spare, pc_alloc, init_pso)
});
real::preserve_vtable(spare, ext_spare);
Expand All @@ -2494,7 +2497,7 @@ unsafe fn try_split_for_wait(list: *mut c_void) -> Option<*mut c_void> {
}
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) {
None => match real::create_raw_pc_command_list(dev.as_raw(), ty, on, init_pso) {
Some(p) => p,
None => {
static CREATE_ERR: AtomicU64 = AtomicU64::new(0);
Expand Down Expand Up @@ -2545,7 +2548,7 @@ unsafe fn try_split_for_wait(list: *mut c_void) -> Option<*mut c_void> {
};
drop(old_next);
super::title_textures::list_reset(next_pc as usize);
super::bind::inherit_for_split(list, next_pc, alloc);
super::bind::inherit_for_split(list, next_pc, on);
restore_bindings(next_pc, &bindings, ty);

if ty == D3D12_COMMAND_LIST_TYPE_DIRECT {
Expand Down Expand Up @@ -2999,7 +3002,8 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) {
(Vec::new(), None, Bindings::default())
}
};
super::bind::inherit_for_split(this, primary, alloc);
// (`primary` records on the PC allocator the title's allocator stands for: its Reset below)
super::bind::inherit_for_split(this, primary, super::alloc_pool::current(alloc));
for seg in reclaimed {
super::bind::reset(seg as *mut c_void, 0, 0);
clear_segment_state(seg);
Expand Down Expand Up @@ -3580,7 +3584,9 @@ pub unsafe extern "system" fn reset_x(this: *mut c_void, alloc: usize, pso: usiz
let resolved = super::pso_async::resolve_for_bind(pso);
// (the PC allocator the title's allocator stands for now: `alloc_pool`)
let ty = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize))).and_then(|s| s.list_type).map_or(-1, |t| t.0);
let mut on = alloc;
let hr = super::alloc_pool::reset_list(this as usize, alloc, ty, |pc_alloc| {
on = pc_alloc;
pc::<unsafe extern "system" fn(*mut c_void, usize, usize) -> i32>(this, PC_RESET)(this, pc_alloc, resolved)
});
real::preserve_vtable(this, ext);
Expand Down Expand Up @@ -3612,7 +3618,8 @@ pub unsafe extern "system" fn reset_x(this: *mut c_void, alloc: usize, pso: usiz
s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE)
};
super::title_textures::list_reset(this as usize);
super::bind::reset(this, alloc, pso);
// (what the new recording puts in unified memory belongs to the PC allocator it is on)
super::bind::reset(this, on, pso);
if !is_bundle && pso != 0 {
if let Some((true, static_bias)) = device_x::base_depth_bias_info(pso) {
if !static_bias.is_zero() && try_native_depth_bias(this, static_bias) {
Expand Down Expand Up @@ -4237,6 +4244,49 @@ mod tests {
assert_eq!(successful_backing, Some(0x333), "only successful Reset moves the recording to its new allocator");
}

unsafe extern "system" fn reset_ok_native(_this: *mut c_void, _alloc: usize, _pso: usize) -> i32 {
0
}

/// A list reset on a title allocator that stands for another PC allocator (`alloc_pool`)
/// records on that one, and what the recording puts in unified memory is held for it after
/// the next Reset – not for the title's allocator, whose own submits the GPU may have passed
/// while this one's still run (#1358).
#[test]
fn a_recordings_memory_is_held_for_the_pc_allocator_it_is_on() {
let mut native = vec![0usize; PC_RESET + 1];
native[PC_RESET] = reset_ok_native as usize;
let extended = [native.as_ptr() as usize, 0usize];
let ext = unsafe { extended.as_ptr().add(1) as usize };
let mut object = [ext];
let list = object.as_mut_ptr() as *mut c_void;
let key = list as usize;
let ids = Box::new([0u8; 4]);
let title = ids.as_ptr() as usize;
let (pc, other, block) = (title + 1, title + 2, title + 3);
super::super::alloc_pool::stand_in_for_test(title, pc);
unsafe { on_create(list, title, 0, D3D12_COMMAND_LIST_TYPE_DIRECT) };

assert_eq!(unsafe { reset_x(list, title, 0) }, 0);
let recording_on = super::super::bind::reset_state_for_test(list).0;
super::super::bind::seed_reset_state_for_test(list, recording_on, 0, vec![block]);
assert_eq!(unsafe { reset_x(list, other, 0) }, 0);
let held_for_pc = super::super::console_list::take_pending_for_test(pc);
let held_for_title = super::super::console_list::take_pending_for_test(title);

LISTS.lock().unwrap().as_mut().unwrap().remove(&key);
super::super::bind::remove_state_for_test(list);
super::super::alloc_pool::stand_in_for_test(title, title);
unsafe {
super::super::alloc_pool::forget(title);
super::super::alloc_pool::forget(pc);
super::super::alloc_pool::forget(other);
}
assert_eq!(recording_on, pc, "the recording is on the PC allocator the title's allocator stands for");
assert_eq!(held_for_pc, vec![block]);
assert!(held_for_title.is_empty());
}

#[test]
fn fill_patterns_repeat_the_value() {
assert_eq!(pattern(&0x1122_3344u32.to_le_bytes())[..8], [0x44, 0x33, 0x22, 0x11, 0x44, 0x33, 0x22, 0x11]);
Expand Down
5 changes: 3 additions & 2 deletions crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4995,9 +4995,10 @@ pub(super) unsafe fn reset_pc_allocator(raw: *mut c_void) -> HRESULT {
}

unsafe extern "system" fn alloc_reset(this: *mut c_void) -> HRESULT {
// (lists may still hold recordings on it that the title submits again: `alloc_pool`)
// (lists may still hold recordings on it that the title submits again: `alloc_pool`, which
// also gives back what recordings on its PC allocators used once the GPU is done with them)
let hr = match super::alloc_pool::title_reset(this) {
Some(hr) => hr,
Some(hr) => return hr,
None => reset_pc_allocator(this),
};
if hr >= 0 {
Expand Down
Loading