Skip to content
Merged
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
84 changes: 74 additions & 10 deletions crates/xcl/src/hle/d3d12x/sparse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,7 @@ static QUEUE: Mutex<Option<ID3D12CommandQueue>> = Mutex::new(None);

/// (bytes of video memory in pool heaps, of those mapped) – `XCL_ACTIVITY`
pub fn pool_bytes() -> (usize, usize) {
let g = STATE.lock().unwrap();
let g = lock_state();
let Some(s) = g.as_ref() else { return (0, 0) };
let pools = s.pools.iter().filter(|p| p.is_some()).count() * POOL_TILES as usize * TILE;
(pools, pools.saturating_sub(s.free.len() * TILE))
Expand Down Expand Up @@ -1235,7 +1235,7 @@ pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usiz
if ranges.is_empty() {
return;
}
let mut g = STATE.lock().unwrap();
let mut g = lock_state();
let Some(s) = g.as_mut() else { return };
let mut filtered: Vec<(usize, usize)> = ranges.iter().copied().filter(|&(a, n)| n > 0 && s.window_index(a).is_some()).collect();
if filtered.is_empty() {
Expand Down Expand Up @@ -1268,7 +1268,7 @@ pub unsafe fn readback_now(va: usize, len: usize) {
if len == 0 {
return;
}
let mut g = STATE.lock().unwrap();
let mut g = lock_state();
let Some(s) = g.as_mut() else { return };
if s.window_index(va).is_none() {
return;
Expand Down Expand Up @@ -1312,7 +1312,7 @@ pub unsafe fn committed(a: usize, n: usize) {
if n == 0 {
return;
}
let mut g = STATE.lock().unwrap();
let mut g = lock_state();
let Some(s) = g.as_mut() else {
let (start, end) = page_span(a, n);
early_add(&mut EARLY.lock().unwrap(), start, end);
Expand All @@ -1328,7 +1328,7 @@ pub unsafe fn decommitted(a: usize, n: usize) {
if n == 0 {
return;
}
let mut g = STATE.lock().unwrap();
let mut g = lock_state();
let Some(s) = g.as_mut() else {
let (start, end) = page_span(a, n);
early_remove(&mut EARLY.lock().unwrap(), start, end);
Expand Down Expand Up @@ -1426,7 +1426,7 @@ impl State {
/// The sparse windows' tiles with video memory as sorted (start, end) runs: where a CPU write
/// has to reach the GPU.
pub fn mapped_ranges() -> Vec<(usize, usize)> {
let mut g = STATE.lock().unwrap();
let mut g = lock_state();
let Some(s) = g.as_mut() else { return Vec::new() };
if s.runs.is_none() {
let mut tiles: Vec<usize> = s.mapped.keys().copied().collect();
Expand Down Expand Up @@ -1458,7 +1458,7 @@ pub fn note_watch(t: std::time::Duration, pages: usize) {
/// memory, and `queue` GPU-waits for that and for new tile mappings.
pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: usize) {
let t0 = std::time::Instant::now();
let mut g = STATE.lock().unwrap();
let mut g = lock_state();
let Some(s) = g.as_mut() else { return };
// the title's work sees what was decommitted unmapped, as it was
if s.flush_parked() {
Expand Down Expand Up @@ -1546,7 +1546,7 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page:
/// description): a reserved resource over the window's tiles there, starting at the 64 KiB
/// below `va` (returned: its distance from there).
pub unsafe fn place_buffer(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, state: u32, riid: *const windows_sys::core::GUID, ppv: *mut *mut c_void) -> Option<(crate::util::HRESULT, usize)> {
let mut g = STATE.lock().unwrap();
let mut g = lock_state();
let s = g.as_mut()?;
let start = va & !(TILE - 1);
let delta = va - start;
Expand Down Expand Up @@ -1584,10 +1584,40 @@ pub unsafe fn place_buffer(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_D
Some((hr, delta))
}

/// A placed buffer is gone: its tiles are not pinned by it any more.
pub fn forget_buffer(res: usize) {
/// Placed buffers released while `STATE` was held, let go by the next `lock_state`. Held only
/// to push or take, never across a call out.
static FORGOTTEN: Mutex<Vec<usize>> = Mutex::new(Vec::new());

/// `STATE`, with the buffers released while it was held let go first.
fn lock_state() -> std::sync::MutexGuard<'static, Option<State>> {
let mut g = STATE.lock().unwrap();
forget_released(&mut g);
g
}

fn forget_released(g: &mut Option<State>) {
let gone = std::mem::take(&mut *FORGOTTEN.lock().unwrap());
let Some(s) = g.as_mut() else { return };
for res in gone {
forget_in(s, res);
}
}

/// A placed buffer is gone: its tiles are not pinned by it any more. This runs from the
/// resource's last Release, which D3D12 can make while it holds a lock of its own (in a title's
/// command list Reset), and `before_execute` calls D3D12 with `STATE` held: waiting for `STATE`
/// here deadlocked the two threads. So it does not wait: with `STATE` held, the holder's next
/// `lock_state` lets the buffer go.
pub fn forget_buffer(res: usize) {
FORGOTTEN.lock().unwrap().push(res);
match STATE.try_lock() {
Ok(mut g) => forget_released(&mut g),
Err(std::sync::TryLockError::WouldBlock) => {}
Err(e) => panic!("sparse state: {e}"),
}
}

fn forget_in(s: &mut State, res: usize) {
let Some(tiles) = s.buffers.remove(&res) else { return };
for tile in tiles {
if let Some(c) = s.pinned.get_mut(&tile) {
Expand Down Expand Up @@ -1647,6 +1677,40 @@ mod tests {
}
}

/// `f` on another thread while this one holds the sparse state (as `before_execute` does
/// around its D3D12 calls, which can wait for that thread): did `f` finish without waiting
/// for the state? The thread runs before the state is taken, so its start is not timed.
fn returns_while_the_state_is_held(f: impl FnOnce() + Send + 'static) -> bool {
let (ready_tx, ready_rx) = std::sync::mpsc::channel();
let (go_tx, go_rx) = std::sync::mpsc::channel::<()>();
let (tx, rx) = std::sync::mpsc::channel();
let t = std::thread::spawn(move || {
let _ = ready_tx.send(());
let _ = go_rx.recv();
f();
let _ = tx.send(());
});
ready_rx.recv().unwrap();
let held = STATE.lock().unwrap();
go_tx.send(()).unwrap();
let done = rx.recv_timeout(std::time::Duration::from_secs(5));
drop(held);
let joined = t.join();
assert!(joined.is_ok(), "the thread panicked: {joined:?}");
done.is_ok()
}

/// A placed buffer released while another thread holds the sparse state: the release does
/// not wait for the state, and the next `lock_state` lets the buffer go.
#[test]
fn a_buffer_released_while_the_state_is_held_does_not_wait_for_it() {
const RES: usize = 0x7ff0_dead_0000;
assert!(returns_while_the_state_is_held(|| forget_buffer(RES)), "forget_buffer waited for the sparse state's lock");
drop(lock_state());
assert!(!FORGOTTEN.lock().unwrap().contains(&RES));
}


/// Freeing the last tile in use of a pool and taking a tile again takes the retired pool
/// back, not a new 64 MB heap each time (#913: 288 pools, 18 GB asked of a 12 GB card).
#[test]
Expand Down
Loading