Skip to content
Draft
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
27 changes: 27 additions & 0 deletions crates/xcl/src/hle/d3d12x/alloc_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,33 @@ unsafe impl Send for State {}

static STATE: Mutex<Option<State>> = Mutex::new(None);

/// Remove completion caches for a retired queue before its raw address can be reused. This is
/// called only after its retirement mark completes; every removed COM fence drops unlocked.
pub(super) fn forget_queue(id: super::present::QueueId) {
let queue = id.raw();
let gone = {
let mut state = STATE.lock().unwrap();
let Some(state) = state.as_mut() else { return };
let mut gone = Vec::new();
if let Some((fence, _)) = state.fences.remove(&queue) {
gone.push(fence);
}
for backing in state.backings.values_mut() {
if let Some((fence, _)) = backing.marks.remove(&queue) {
gone.push(fence);
}
}
let lists: Vec<_> = state.last_submit.iter().filter_map(|(&list, submit)| (submit.queue == queue).then_some(list)).collect();
for list in lists {
if let Some(submit) = state.last_submit.remove(&list) {
gone.push(submit.fence);
}
}
gone
};
drop(gone);
}

pub(super) fn release_with_probe(
add_ref: impl FnOnce(),
mut release: impl FnMut() -> u32,
Expand Down
10 changes: 10 additions & 0 deletions crates/xcl/src/hle/d3d12x/cpu_writes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,16 @@ unsafe impl Send for QueueFence {}

static FENCES: Mutex<Option<HashMap<usize, QueueFence>>> = Mutex::new(None);

/// Forget a retired queue's cached fence before its address can be reused. Submitted jobs own
/// fence clones, so extracting this entry cannot let their writes run early.
pub(super) fn forget_queue(id: super::present::QueueId) {
let gone = {
let mut fences = FENCES.lock().unwrap();
fences.as_mut().and_then(|fences| fences.remove(&id.raw()))
};
drop(gone);
}

/// how long the worker waits for one submission before writing anyway (a removed device, a
/// queue that never gets there)
const WAIT_MS: u32 = 10_000;
Expand Down
10 changes: 10 additions & 0 deletions crates/xcl/src/hle/d3d12x/late_release.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,16 @@ impl Held {

static HELD: Mutex<Option<Held>> = Mutex::new(None);

/// Remove cached state for a retired queue before its final owner can be released. Sealed
/// batches own their fence clones, so they remain gated. The removed fence drops unlocked.
pub(super) fn forget_queue(id: super::present::QueueId) {
let gone = {
let mut held = HELD.lock().unwrap();
held.as_mut().and_then(|held| held.fences.remove(&id.raw()))
};
drop(gone);
}

/// Whether last releases are held (`XCL_LATE_RELEASE=0` turns it off).
pub fn enabled() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
Expand Down
100 changes: 100 additions & 0 deletions crates/xcl/src/hle/d3d12x/list_x.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1119,6 +1119,46 @@ pub(super) fn on_queue_release(queue: usize) {
}
}

/// Remove every cached use of a retired raw queue address before it can be reused. This is later
/// than `on_queue_release`: the retirement marker has completed, so old sync edges are finished.
/// Cached COM fences are extracted and dropped after their locks are gone.
pub(super) fn forget_queue(id: super::present::QueueId) {
let queue = id.raw();
let scratch_fences = {
let mut scratch = COPY_SCRATCH.lock().unwrap();
let mut gone = Vec::new();
if let Some((fence, _)) = scratch.fences.remove(&queue) {
gone.push(fence);
}
for allocation in scratch.active.values_mut() {
if let Some((fence, _)) = allocation.marks.remove(&queue) {
gone.push(fence);
}
}
for allocation in &mut scratch.released {
if let Some((fence, _)) = allocation.marks.remove(&queue) {
gone.push(fence);
}
}
gone
};
drop(scratch_fences);
LIVE_QUEUES.lock().unwrap().retain(|info| info.queue != queue);
if let Some(lists) = LISTS.lock().unwrap().as_mut() {
for state in lists.values_mut() {
if state.last_queue == Some(queue) {
state.last_queue = None;
}
}
}
let removed_waits = SYNC_GRAPH.lock().unwrap().as_mut().map_or(0, |graph| graph.forget_queue(queue));
if removed_waits != 0 {
ARMED_GPU_WAITS.fetch_sub(removed_waits, Ordering::AcqRel);
}
let internal_waits = INTERNAL_WAITS.lock().unwrap().as_mut().and_then(|waits| waits.remove(&queue));
drop(internal_waits);
}

#[cfg(test)]
thread_local! {
/// Optional test interceptor for `try_native_depth_bias` so unit tests deterministically
Expand Down Expand Up @@ -1507,6 +1547,28 @@ impl SyncGraph {
*s += 1;
*s
}

fn forget_queue(&mut self, queue: usize) -> usize {
self.queue_seq.remove(&queue);
let mut armed = 0;
for cell in self.cells.values_mut() {
if cell.recorded_last_queue == Some(queue) {
cell.recorded_last_queue = None;
}
if cell.submitted_queue == Some(queue) {
cell.submitted_queue = None;
}
let before = cell.armed_waits.len();
cell.armed_waits.retain(|wait| wait.waiting_queue != queue);
armed += before - cell.armed_waits.len();
cell.submitted_signals.retain(|signal| signal.queue != queue);
}
for fence in self.title_fences.values_mut() {
fence.waits.retain(|&(_, waiting_queue, _)| waiting_queue != queue);
fence.signals.retain(|signal| signal.queue != queue);
}
armed
}
}

static SYNC_GRAPH: Mutex<Option<SyncGraph>> = Mutex::new(None);
Expand Down Expand Up @@ -6077,6 +6139,44 @@ mod tests {
assert_eq!(pick_queue(None, dev, D3D12_COMMAND_LIST_TYPE_DIRECT), None);
}

#[test]
fn sync_graph_forgets_every_reference_to_a_retired_queue() {
let (gone, kept) = (0x9100usize, 0x9200usize);
let mut graph = SyncGraph::default();
graph.queue_seq.insert(gone, 3);
graph.queue_seq.insert(kept, 4);
let mut cell = SyncCell { recorded_last_queue: Some(gone), submitted_queue: Some(gone), ..Default::default() };
cell.armed_waits.push(ArmedGpuWait {
val: 1,
waiting_queue: gone,
waiting_queue_ty: 0,
wait_seq: 1,
armed_at: Instant::now(),
after_write64: false,
});
cell.armed_waits.push(ArmedGpuWait { waiting_queue: kept, ..cell.armed_waits[0] });
cell.submitted_signals.push(SubmittedSignal { val: 1, queue: gone, seq: 1 });
cell.submitted_signals.push(SubmittedSignal { val: 2, queue: kept, seq: 2 });
graph.cells.insert(0x1000, cell);
graph.title_fences.insert(
0x2000,
TitleFenceSync {
waits: vec![(1, gone, 1), (2, kept, 2)],
signals: vec![SubmittedSignal { val: 1, queue: gone, seq: 1 }, SubmittedSignal { val: 2, queue: kept, seq: 2 }],
},
);

assert_eq!(graph.forget_queue(gone), 1);
assert!(!graph.queue_seq.contains_key(&gone) && graph.queue_seq.contains_key(&kept));
let cell = &graph.cells[&0x1000];
assert_eq!((cell.recorded_last_queue, cell.submitted_queue), (None, None));
assert_eq!(cell.armed_waits.iter().map(|wait| wait.waiting_queue).collect::<Vec<_>>(), [kept]);
assert_eq!(cell.submitted_signals.iter().map(|signal| signal.queue).collect::<Vec<_>>(), [kept]);
let title = &graph.title_fences[&0x2000];
assert_eq!(title.waits.iter().map(|&(_, queue, _)| queue).collect::<Vec<_>>(), [kept]);
assert_eq!(title.signals.iter().map(|signal| signal.queue).collect::<Vec<_>>(), [kept]);
}

#[test]
fn depth_bias_state_tracks_fallback_and_clear() {
let l = 0x9000_0001usize as *mut c_void;
Expand Down
26 changes: 26 additions & 0 deletions crates/xcl/src/hle/d3d12x/present.rs
Original file line number Diff line number Diff line change
Expand Up @@ -462,6 +462,32 @@ pub(super) fn sweep_queue_retirements(completed: &[QueueId]) -> Vec<ID3D12Comman
retired.into_iter().map(|(owner, _mark)| owner).collect()
}

/// Remove every cache keyed by this queue's raw address after its retirement mark completes and
/// before the final owner is released. No callee holds one subsystem lock while taking another.
#[allow(dead_code)] // Stage C seam: called by the retirement worker in a later unit.
pub(super) fn invalidate_queue_caches(id: QueueId) {
let raw = id.raw();
let candidate = {
let mut candidate = CANDIDATE.lock().unwrap();
candidate.is_some_and(|(queue, _)| queue == raw).then(|| candidate.take().unwrap().1)
};
let presenter = {
let mut presenter = PRESENTER.lock().unwrap();
presenter.as_ref().is_some_and(|p| p.queue == raw).then(|| presenter.take().unwrap())
};
super::list_x::forget_queue(id);
super::alloc_pool::forget_queue(id);
super::cpu_writes::forget_queue(id);
super::late_release::forget_queue(id);
super::sparse::forget_queue(id);
super::title_textures::forget_queue(id);
super::vram::forget_queue(id);
if let Some(resource) = candidate {
unsafe { release(resource) };
}
drop(presenter);
}

static EXECUTES: AtomicU64 = AtomicU64::new(0);

/// (PresentX calls, ExecuteCommandLists calls) so far
Expand Down
13 changes: 13 additions & 0 deletions crates/xcl/src/hle/d3d12x/sparse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,19 @@ static STATE: Mutex<Option<State>> = Mutex::new(None);
/// (a list's `Reset`, with `XCL_DRED=1` on every start): the two then waited for each other.
static QUEUE: Mutex<Option<ID3D12CommandQueue>> = Mutex::new(None);

/// Remove raw queue-address state before a retired queue's final owner is released. Retired tile
/// batches own fence clones independently; the cached queue and fence drop after unlocking.
pub(super) fn forget_queue(id: super::present::QueueId) {
let gone = {
let mut state = STATE.lock().unwrap();
state.as_mut().and_then(|state| {
state.waited.remove(&id.raw());
state.queue_fences.remove(&id.raw())
})
};
drop(gone);
}

/// (bytes of video memory in pool heaps, of those mapped) – `XCL_ACTIVITY`
pub fn pool_bytes() -> (usize, usize) {
let g = lock_state();
Expand Down
6 changes: 6 additions & 0 deletions crates/xcl/src/hle/d3d12x/title_textures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1097,6 +1097,12 @@ unsafe impl Send for QueueUploads {}

static ON_QUEUE: Mutex<BTreeMap<usize, QueueUploads>> = Mutex::new(BTreeMap::new());

/// Drop completed uploads cached for a retired title queue after releasing the cache lock.
pub(super) fn forget_queue(id: super::present::QueueId) {
let gone = ON_QUEUE.lock().unwrap().remove(&id.raw());
drop(gone);
}

const IN_FLIGHT_BYTES: u64 = 512 << 20;

unsafe fn title_queue_for(dev: &ID3D12Device, title: Option<&ID3D12CommandQueue>) -> Option<ID3D12CommandQueue> {
Expand Down
41 changes: 41 additions & 0 deletions crates/xcl/src/hle/d3d12x/vram.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1143,13 +1143,40 @@ impl<H, F: Clone> RetireQueue<H, F> {
let pruned = stale.into_iter().filter_map(|k| self.fences.remove(&k).map(|(f, _)| f)).collect();
(done, pruned)
}

/// In-flight batches own their marks; only the address-keyed reusable fence is removed.
fn forget_queue(&mut self, queue: usize) -> Option<F> {
self.fences.remove(&queue).map(|(fence, _)| fence)
}
}

unsafe impl Send for RetireQueue<ID3D12Heap, ID3D12Fence> {}

static RETIRE: Mutex<Option<std::collections::HashMap<usize, RetireQueue<ID3D12Heap, ID3D12Fence>>>> = Mutex::new(None);
static RETIRING_BATCHES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

/// Remove raw queue-address state before a retired queue's final owner can be released. Fence
/// objects are extracted from both locks and dropped afterward; retirement batches keep clones.
pub(super) fn forget_queue(id: super::present::QueueId) {
let queue = id.raw();
{
let mut pages = PAGES.lock().unwrap();
for pages in pages.values_mut().flatten() {
pages.waited.remove(&queue);
}
}
let gone = {
let mut retire = RETIRE.lock().unwrap();
retire
.as_mut()
.into_iter()
.flat_map(|devices| devices.values_mut())
.filter_map(|queues| queues.forget_queue(queue))
.collect::<Vec<_>>()
};
drop(gone);
}

/// Collect all known live command queues belonging to `dev_key` (deduplicated by raw ptr).
unsafe fn collect_device_queues(dev_key: usize, extra: Option<&ID3D12CommandQueue>) -> Vec<(usize, ID3D12CommandQueue)> {
let (mut seen, mut out) = (HashSet::new(), Vec::new());
Expand Down Expand Up @@ -1713,6 +1740,20 @@ mod tests {
assert_eq!(rq.retire_with(vec![303], None, &[] as &[(usize, usize)], mk, |_, _, _| true), vec![303]);
}

#[test]
fn forgetting_queue_cache_preserves_inflight_batch_marks() {
use std::sync::{atomic::AtomicU64, Arc};
let mut rq = RetireQueue::<u32, Arc<AtomicU64>>::new();
assert!(rq
.retire_with(vec![101], None, &[(7, 7usize)], || Some(Arc::new(AtomicU64::new(0))), |_, _, _| true)
.is_empty());
let cached = rq.fences[&7].0.clone();
let gone = rq.forget_queue(7).expect("cached queue fence");
assert!(Arc::ptr_eq(&gone, &cached) && !rq.fences.contains_key(&7));
assert_eq!(rq.batches.len(), 1);
assert!(Arc::strong_count(&cached) >= 3, "the in-flight batch lost its own fence clone");
}

#[test]
fn gpu_retire_queue_holds_heap_until_blocked_queue_passes_mark() {
let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
Expand Down
Loading