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
12 changes: 12 additions & 0 deletions crates/xcl/src/gpu/uma.rs
Original file line number Diff line number Diff line change
Expand Up @@ -603,6 +603,18 @@ impl Uma {
true
}

/// Whether `p` is a block handed out and not freed since (tests).
#[cfg(test)]
pub fn is_allocated(&self, p: usize) -> bool {
{
let g = self.pool.lock().unwrap();
if p >= g.0 && p < g.1 {
return !g.2.contains(&p);
}
}
p.checked_sub(self.base).is_some_and(|off| self.inner.lock().unwrap().used.contains_key(&off))
}

/// Bytes handed out.
pub fn used(&self) -> usize {
self.inner.lock().unwrap().used.values().sum()
Expand Down
109 changes: 96 additions & 13 deletions crates/xcl/src/hle/d3d12x/late_release.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,12 @@ const SEAL_EVERY: Duration = Duration::from_millis(10);
/// how often the thread here looks for batches that can go
const TICK: Duration = Duration::from_millis(4);

/// A held resource and the unified-memory or sparse-VRAM block XCL placed under it (given back
/// when it goes: until then the queues may still use it).
type Dead = (usize, Option<usize>);

struct Batch {
dead: Vec<usize>,
dead: Vec<Dead>,
/// (fence, value) a queue: all reached = nothing submitted before the batch closed is left
marks: Vec<(ID3D12Fence, u64)>,
}
Expand All @@ -31,7 +35,7 @@ struct Batch {
struct Held {
/// queue → its fence here and the last value signalled on it
fences: HashMap<usize, (ID3D12Fence, u64)>,
open: Vec<usize>,
open: Vec<Dead>,
sealed: VecDeque<Batch>,
last_seal: Option<Instant>,
}
Expand All @@ -46,7 +50,7 @@ impl Held {

/// Close the open batch (at most every `SEAL_EVERY`, or `seal_now`) with a fence value on each of `queues`,
/// and take out the batches every queue is past: the resources to release now.
unsafe fn drain(&mut self, queues: &[ID3D12CommandQueue], seal_now: bool) -> Vec<usize> {
unsafe fn drain(&mut self, queues: &[ID3D12CommandQueue], seal_now: bool) -> Vec<Dead> {
if !self.open.is_empty() && (seal_now || self.last_seal.is_none_or(|t| t.elapsed() >= SEAL_EVERY)) {
let mut marks = Vec::with_capacity(queues.len());
let mut ok = true;
Expand Down Expand Up @@ -82,6 +86,11 @@ impl Held {
}
gone
}

/// `dead`, which every queue is past already, go at the next drain.
fn again(&mut self, dead: Vec<Dead>) {
self.sealed.push_front(Batch { dead, marks: Vec::new() });
}
}

static HELD: Mutex<Option<Held>> = Mutex::new(None);
Expand All @@ -96,11 +105,12 @@ pub fn enabled() -> bool {
const IDLE_WAIT: Duration = Duration::from_micros(300);

/// `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
/// before. Otherwise the thread here lets it go.
pub unsafe fn hold(res: usize) {
HELD.lock().unwrap().get_or_insert_with(Held::default).open.push(res);
/// flight it goes before this returns (the queues pass a fence value at once; unless the sparse
/// state is busy): a title that frees the memory under a resource right after its last
/// `Release` finds it unpinned, as before. Otherwise the thread here lets it go. `memory`: the
/// block XCL placed under it, given back (and its sparse tiles unpinned) only when it goes.
pub unsafe fn hold(res: usize, memory: Option<usize>) {
HELD.lock().unwrap().get_or_insert_with(Held::default).open.push((res, memory));
let start = Instant::now();
drain_known(true);
while start.elapsed() < IDLE_WAIT && HELD.lock().unwrap().as_ref().is_some_and(|h| !h.is_empty()) {
Expand Down Expand Up @@ -142,10 +152,36 @@ pub unsafe fn drain_known(seal_now: bool) {
None => return,
};
// (outside the lock: a release may end other objects, whose releases come back here)
for res in gone {
let later = let_go(gone);
if !later.is_empty() {
if let Some(h) = HELD.lock().unwrap().as_mut() {
h.again(later);
}
}
}

/// Release `gone`, which the queues are past, with their tiles and memory – except those the
/// sparse state is busy for: returned, to go at a later drain.
unsafe fn let_go(gone: Vec<Dead>) -> Vec<Dead> {
let mut later = Vec::new();
for (res, memory) in gone {
// its tiles and a sparse block under it go first, while it is still alive (its address
// is no other resource's yet), and without waiting for the sparse state: a drain runs
// where the state's holder can be waiting for this thread
if !super::sparse::try_forget_held(res, memory) {
later.push((res, memory));
continue;
}
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);
// a block in a coherent window after it
if let (Some(p), Some(u)) = (memory, crate::gpu::uma::get()) {
if !u.is_sparse(p) {
u.free(p);
}
}
}
later
}

#[cfg(test)]
Expand Down Expand Up @@ -180,7 +216,7 @@ mod tests {
let raw = res.unwrap().into_raw() as usize;

let mut held = Held::default();
held.open.push(raw);
held.open.push((raw, None));
let queues = [queue.clone()];
assert!(held.drain(&queues, false).is_empty(), "the queue has not passed the batch's fence value");
std::thread::sleep(Duration::from_millis(100));
Expand All @@ -194,7 +230,7 @@ mod tests {
std::thread::sleep(Duration::from_millis(5));
gone = held.drain(&queues, false);
}
assert_eq!(gone, vec![raw], "released once the queue is past the batch");
assert_eq!(gone, vec![(raw, None)], "released once the queue is past the batch");
assert!(held.is_empty());
drop(ID3D12Resource::from_raw(raw as *mut c_void));
}
Expand All @@ -204,8 +240,55 @@ mod tests {
#[test]
fn without_queues_a_batch_goes_at_once() {
let mut held = Held::default();
held.open.push(0x1000);
assert_eq!(unsafe { held.drain(&[], false) }, vec![0x1000]);
held.open.push((0x1000, Some(0x2000)));
assert_eq!(unsafe { held.drain(&[], false) }, vec![(0x1000, Some(0x2000))]);
assert!(held.is_empty());
}

/// Letting held resources go does not wait for the sparse state's lock: a drain runs inside
/// XCL's own submit while that thread holds the lock (an upload going out on a queue whose
/// submits are hooked), and inside D3D12 calls the lock's holder can wait for. The resource
/// is kept for a later drain instead.
#[test]
fn letting_go_does_not_wait_for_the_sparse_state() {
let locked = super::super::sparse::lock_for_test();
let (tx, rx) = std::sync::mpsc::channel();
let drain = std::thread::spawn(move || {
let _ = tx.send(unsafe { let_go(vec![(0x1000, None)]) });
});
let answered = rx.recv_timeout(Duration::from_secs(5));
drop(locked);
drain.join().unwrap();
assert_eq!(answered.ok(), Some(vec![(0x1000, None)]), "the drain waited for the sparse state's lock");
}

/// A resource put back (the sparse state was busy) goes at the next drain, ahead of a batch a
/// queue has not got past.
#[test]
fn a_resource_put_back_goes_at_the_next_drain() {
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 gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
queue.Wait(&gate, 1).unwrap();
let queues = [queue.clone()];

let mut held = Held::default();
held.open.push((0x1000, None));
assert!(held.drain(&queues, true).is_empty(), "the queue has not passed the batch's fence value");
held.again(vec![(0x2000, None)]);
assert_eq!(held.drain(&queues, false), vec![(0x2000, None)], "put back: goes at the next drain");
assert!(!held.is_empty(), "the batch the queue has not passed stays");

gate.Signal(1).unwrap();
let start = Instant::now();
while !held.is_empty() && start.elapsed() < Duration::from_secs(10) {
std::thread::sleep(Duration::from_millis(5));
held.drain(&queues, false);
}
assert!(held.is_empty());
}
}
}
73 changes: 70 additions & 3 deletions crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1563,6 +1563,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 {
} else {
f(this)
};
let mut memory = None;
if n == 0 {
if let Some(s) = UNMAPPABLE.lock().unwrap().as_mut() {
s.remove(&(this as usize));
Expand All @@ -1576,20 +1577,26 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 {
if let Some(m) = TITLE_ADDRESS.lock().unwrap().as_mut() {
m.remove(&(this as usize));
}
super::sparse::forget_buffer(this as usize);
// a held resource's tiles stay pinned until it goes (`late_release`)
if !held {
super::sparse::forget_buffer(this as usize);
}
super::vram::forget(this as usize);
super::title_textures::forget(this as usize);
let gone = UMA_BUFFERS.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize)));
if let (Some((p, _, true)), Some(u)) = (gone, crate::gpu::uma::get()) {
if u.is_sparse(p) {
if held {
// its memory goes with it: a queue may still be using it
memory = Some(p);
} else if u.is_sparse(p) {
super::sparse::free(p);
} else {
u.free(p);
}
}
}
if held {
super::late_release::hold(this as usize);
super::late_release::hold(this as usize, memory);
}
n
}
Expand Down Expand Up @@ -5765,3 +5772,63 @@ mod console_format_query_tests {
}
}
}

#[cfg(test)]
mod held_release_tests {
use super::*;
use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC;

/// A resource whose last `Release` is held (a queue still has work) keeps the unified memory
/// XCL placed under it until the hold ends: given back at the title's `Release`, the block
/// could go to the next allocation while the GPU still used it.
#[test]
fn a_held_resource_keeps_its_unified_memory_until_it_goes() {
unsafe {
if !super::super::late_release::enabled() {
return;
}
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 Some(u) = crate::gpu::uma::get() else {
return crate::gpu::recomp::runner::skip_test("no GPU");
};
// a queue with work in flight (it waits for a fence nobody has signalled yet) that
// the title has submitted to: late release waits for the queues it knows
let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap();
let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
queue.Wait(&gate, 1).unwrap();
super::super::present::note_execute(queue.as_raw(), &[]);

let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: 4096,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
..Default::default()
};
let mut res: Option<ID3D12Resource> = None;
dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut res).unwrap();
let raw = res.unwrap().into_raw();
adopt(raw, Kind::Resource);
// the block XCL placed under it, recorded as `place_console_buffer` does
let p = u.alloc(0x1_0000, crate::gpu::uma::GRAIN).expect("unified memory") as usize;
UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(raw as usize, (p, 0x1_0000, true));

// the title's last Release, while the queue still has work
let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(raw as *const *const usize)).add(2));
assert_eq!(release(raw), 0);
assert!(u.is_allocated(p), "the block under a held resource went back while a queue still had work");

gate.Signal(1).unwrap();
let start = std::time::Instant::now();
while u.is_allocated(p) && start.elapsed() < std::time::Duration::from_secs(10) {
std::thread::sleep(std::time::Duration::from_millis(5));
}
assert!(!u.is_allocated(p), "the block goes back once the held resource goes");
}
}
}
60 changes: 49 additions & 11 deletions crates/xcl/src/hle/d3d12x/sparse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1201,14 +1201,19 @@ pub unsafe fn alloc_in(window: usize, size: usize, align: usize) -> Option<(usiz

/// Release a sparse allocation from `alloc` / `alloc_in` (false: not a sparse allocation).
pub unsafe fn free(p: usize) -> bool {
free_with(p, |a, n| decommitted(a, n))
}

/// `free`, telling the state about the decommit through `decommit`.
unsafe fn free_with(p: usize, decommit: impl FnOnce(usize, usize)) -> bool {
let Some(u) = crate::gpu::uma::get() else { return false };
if !u.is_sparse(p) {
return false;
}
// decommitted before the address goes back: once released, another thread may get it,
// commit it and write there
let Some((start, len)) = u.sparse_reservation(p).filter(|&(start, _)| start == p) else { return false };
decommitted(start, len);
decommit(start, len);
VirtualFree(p as *mut c_void, len, MEM_DECOMMIT);
u.sparse_release(p).is_some()
}
Expand Down Expand Up @@ -1318,7 +1323,11 @@ pub unsafe fn decommitted(a: usize, n: usize) {
if n == 0 {
return;
}
let mut g = STATE.lock().unwrap();
decommitted_in(&mut STATE.lock().unwrap(), a, n);
}

/// `decommitted` with the state's lock held (`g`).
unsafe fn decommitted_in(g: &mut Option<State>, a: usize, n: usize) {
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 @@ -1576,15 +1585,44 @@ pub unsafe fn place_buffer(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_D

/// A placed buffer is gone: its tiles are not pinned by it any more.
pub fn forget_buffer(res: usize) {
let mut g = STATE.lock().unwrap();
let Some(s) = g.as_mut() else { return };
let Some(tiles) = s.buffers.remove(&res) else { return };
for tile in tiles {
if let Some(c) = s.pinned.get_mut(&tile) {
*c -= 1;
if *c == 0 {
s.pinned.remove(&tile);
s.release_if_unused(tile);
if let Some(s) = STATE.lock().unwrap().as_mut() {
s.forget_buffer(res);
}
}

/// `forget_buffer(res)`, and `free(block)` when `block` is a sparse block, for a resource whose
/// last `Release` `late_release` held – only if the state's lock is free right now (false:
/// nothing was done, ask again later). The late-release drain runs where the lock's holder can
/// be waiting for this thread: inside a D3D12 call that made a resource's last `Release`, or
/// inside XCL's own submit while the state is locked.
pub unsafe fn try_forget_held(res: usize, block: Option<usize>) -> bool {
let Ok(mut g) = STATE.try_lock() else { return false };
if let Some(s) = g.as_mut() {
s.forget_buffer(res);
}
if let Some(p) = block {
free_with(p, |a, n| decommitted_in(&mut g, a, n));
}
true
}

/// The state's lock, held by a test (as XCL's own uploads hold it).
#[cfg(test)]
pub(super) fn lock_for_test() -> impl Sized {
STATE.lock().unwrap_or_else(|e| e.into_inner())
}

impl State {
/// `forget_buffer` with the state locked
fn forget_buffer(&mut self, res: usize) {
let Some(tiles) = self.buffers.remove(&res) else { return };
for tile in tiles {
if let Some(c) = self.pinned.get_mut(&tile) {
*c -= 1;
if *c == 0 {
self.pinned.remove(&tile);
self.release_if_unused(tile);
}
}
}
}
Expand Down
Loading