Skip to content
Merged
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
7 changes: 6 additions & 1 deletion crates/xcl/src/hle/d3d12x/alloc_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -958,7 +958,10 @@ pub(super) fn forget_list(list: usize) {
/// only after native Reset succeeds. No pool lock is held across the driver call.
pub fn reset_list(list: usize, alloc: usize, ty: i32, reset: impl FnOnce(usize) -> HRESULT) -> HRESULT {
let backing = current(alloc);
let hr = reset(backing);
let hr = {
let _in_reset = super::late_release::InListReset::enter();
reset(backing)
};
if hr < 0 || !enabled() || alloc == 0 {
return hr;
}
Expand Down Expand Up @@ -2259,8 +2262,10 @@ mod tests {
assert!(reset, "the reserved backing is put aside instead of Reset");
assert_eq!(reset_list(list, alloc, -1, |backing| {
assert_eq!(backing, next);
assert!(crate::hle::d3d12x::late_release::in_list_reset(), "the native Reset runs with the guard set");
0
}), 0);
assert!(!crate::hle::d3d12x::late_release::in_list_reset(), "and it is cleared after");
let second = begin_submit(&[list as *mut c_void]).unwrap().execution_possible();

first.finish_with_mark(0x71, &fence, 3);
Expand Down
251 changes: 218 additions & 33 deletions crates/xcl/src/hle/d3d12x/late_release.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,54 +49,98 @@ struct Held {
open: Vec<Dead>,
sealed: VecDeque<Batch>,
last_seal: Option<Instant>,
/// a batch is being closed (its signals are made with the lock released)
sealing: bool,
}

// (the interface pointers are only used under the lock)
unsafe impl Send for Held {}

impl Held {
fn is_empty(&self) -> bool {
self.open.is_empty() && self.sealed.is_empty()
self.open.is_empty() && self.sealed.is_empty() && !self.sealing
}

/// 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: what to release now.
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;
for q in queues {
let key = q.as_raw() as usize;
if !self.fences.contains_key(&key) {
let mut dev: Option<ID3D12Device> = None;
let made = q.GetDevice(&mut dev).ok().and(dev).and_then(|d| d.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE).ok());
let Some(f) = made else {
ok = false;
break;
};
self.fences.insert(key, (f, 0));
}
let (fence, value) = self.fences.get_mut(&key).unwrap();
if super::real::native_queue_signal(q, &*fence, *value + 1).is_err() {
ok = false;
break;
}
*value += 1;
marks.push((fence.clone(), *value));
}
// (no fence or no signal: the device is gone – the batch stays open, and held)
if ok {
self.last_seal = Some(Instant::now());
let dead = std::mem::take(&mut self.open);
self.sealed.push_back(Batch { dead, marks });
/// Close the open batch (at most every `SEAL_EVERY`, or `seal_now`): take it out, and reserve a fence
/// value on each of `queues`. The signals themselves are not made here: a `Signal` takes the queue's
/// submit lease, and nothing that waits for a lease may run under `HELD` (the thread that holds the
/// lease may be waiting for a release that needs `HELD`). One batch is closed at a time (the
/// leases are not FIFO: signals of two seals could reach a queue in the wrong order); the open
/// batch waits for the next seal. `None`: nothing to close, another seal under way, or no fence.
unsafe fn begin_seal(&mut self, queues: &[ID3D12CommandQueue], seal_now: bool) -> Option<Seal> {
if !seal_due(self.open.is_empty(), self.sealing, seal_now, self.last_seal.map(|t| t.elapsed())) {
return None;
}
let mut signals = Vec::with_capacity(queues.len());
for q in queues {
let key = q.as_raw() as usize;
if !self.fences.contains_key(&key) {
let mut dev: Option<ID3D12Device> = None;
let made = q.GetDevice(&mut dev).ok().and(dev).and_then(|d| d.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE).ok());
// (no fence: the device is gone – the batch stays open, and held)
self.fences.insert(key, (made?, 0));
}
let (fence, value) = self.fences.get_mut(&key).unwrap();
// (a value whose signal fails is never used: a later one passes it)
*value += 1;
signals.push((q.clone(), fence.clone(), *value));
}
// (taken now: what is released after this is not behind the signals)
let seal = Seal { dead: std::mem::take(&mut self.open), signals, was_sealed: self.last_seal };
self.last_seal = Some(Instant::now());
self.sealing = true;
Some(seal)
}

/// The signals of `seal` were made (`ok`) or not (the batch goes back to the open one).
fn end_seal(&mut self, seal: Seal, ok: bool) {
self.sealing = false;
if ok {
let marks = seal.signals.into_iter().map(|(_, f, v)| (f, v)).collect();
self.sealed.push_back(Batch { dead: seal.dead, marks });
} else {
self.last_seal = seal.was_sealed;
self.open.splice(0..0, seal.dead);
}
}

/// Take out the batches every queue is past: what to release now.
unsafe fn take_gone(&mut self) -> Vec<Dead> {
let mut gone = Vec::new();
while self.sealed.front().is_some_and(|b| b.marks.iter().all(|(f, v)| super::real::fence_completed(&f) >= *v)) {
gone.extend(self.sealed.pop_front().unwrap().dead);
}
gone
}

/// `begin_seal`, the signals, `end_seal` and `take_gone` in one, for a `Held` nobody else uses.
#[cfg(test)]
unsafe fn drain(&mut self, queues: &[ID3D12CommandQueue], seal_now: bool) -> Vec<Dead> {
if let Some(seal) = self.begin_seal(queues, seal_now) {
let ok = seal.signal();
self.end_seal(seal, ok);
}
self.take_gone()
}
}

/// Whether the open batch is closed now: there is one, no other seal is under way, and it is
/// `seal_now` or the last seal is `SEAL_EVERY` back.
fn seal_due(open_is_empty: bool, sealing: bool, seal_now: bool, since_last: Option<Duration>) -> bool {
!open_is_empty && !sealing && (seal_now || since_last.is_none_or(|t| t >= SEAL_EVERY))
}

/// A batch being closed: `signals` (queue, fence, value) are made outside the lock.
struct Seal {
dead: Vec<Dead>,
signals: Vec<(ID3D12CommandQueue, ID3D12Fence, u64)>,
was_sealed: Option<Instant>,
}

impl Seal {
unsafe fn signal(&self) -> bool {
self.signals.iter().all(|(q, f, v)| super::real::native_queue_signal(q, f, *v).is_ok())
}
}

static HELD: Mutex<Option<Held>> = Mutex::new(None);
Expand Down Expand Up @@ -140,6 +184,37 @@ impl Busy {

static BUSY: Busy = Busy(Mutex::new(None));

thread_local! {
static IN_LIST_RESET: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// Set while this thread is inside a native command list `Reset`. D3D12Core holds its allocator/list
/// lock there and may release objects (DRED's breadcrumb buffer) into `hold`; a look at the queues
/// would take a queue's submit lease, which a thread waiting on that same lock holds. Releases made
/// there are left to the late-release thread.
pub(super) struct InListReset(bool);

impl InListReset {
pub(super) fn enter() -> Self {
Self(IN_LIST_RESET.with(|c| c.replace(true)))
}
}

impl Drop for InListReset {
fn drop(&mut self) {
IN_LIST_RESET.with(|c| c.set(self.0));
}
}

pub(super) fn in_list_reset() -> bool {
IN_LIST_RESET.with(|c| c.get())
}

/// Whether `hold` leaves the release to the thread without a look at the queues.
fn leaves_to_thread(pinned: bool, queues_busy: bool, in_list_reset: bool) -> bool {
!pinned || queues_busy || in_list_reset
}

/// `res` (an adopted resource) holds one reference that is now this module's. With `pinned` (it may
/// be over pages that are freed next) and 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
Expand All @@ -148,7 +223,7 @@ static BUSY: Busy = Busy(Mutex::new(None));
pub unsafe fn hold(res: usize, pinned: bool) {
HELD.lock().unwrap().get_or_insert_with(Held::default).open.push(Dead::Resource(res));
let start = Instant::now();
let busy = !pinned || BUSY.is(start);
let busy = leaves_to_thread(pinned, BUSY.is(start), in_list_reset());
if !busy {
drain_known(true);
while start.elapsed() < IDLE_WAIT && HELD.lock().unwrap().as_ref().is_some_and(|h| !h.is_empty()) {
Expand Down Expand Up @@ -235,8 +310,19 @@ pub unsafe fn drain_known(seal_now: bool) {
let mut queues = super::present::active_queues_held();
queues.extend(super::sparse::queue());
queues.extend(super::title_textures::upload_queues());
// (the signals are made with `HELD` unlocked: they take the queues' submit leases)
let seal = match HELD.lock().unwrap().as_mut() {
Some(h) => h.begin_seal(&queues, seal_now),
None => return,
};
if let Some(seal) = seal {
let ok = seal.signal();
if let Some(h) = HELD.lock().unwrap().as_mut() {
h.end_seal(seal, ok);
}
}
let gone = match HELD.lock().unwrap().as_mut() {
Some(h) => h.drain(&queues, seal_now),
Some(h) => h.take_gone(),
None => return,
};
// (outside the lock: a release may end other objects, whose releases come back here)
Expand Down Expand Up @@ -342,6 +428,28 @@ mod tests {
assert!(busy.is(t + BUSY_FOR + BUSY_FOR / 2));
}

/// A release made inside a native list Reset is left to the thread: a look at the queues there
/// takes a submit lease that a thread waiting on the Reset's lock may hold.
#[test]
fn a_release_inside_a_list_reset_is_left_to_the_thread() {
assert!(!leaves_to_thread(true, false, false), "pinned, idle queues, outside a Reset: looked at");
assert!(leaves_to_thread(true, false, true), "inside a Reset: left to the thread");
assert!(leaves_to_thread(false, false, false) && leaves_to_thread(true, true, false));
assert!(!in_list_reset());
{
let _outer = InListReset::enter();
assert!(in_list_reset());
drop(InListReset::enter());
assert!(in_list_reset(), "a nested guard restores the outer state");
}
assert!(!in_list_reset());
let r = std::panic::catch_unwind(|| {
let _g = InListReset::enter();
panic!("inside");
});
assert!(r.is_err() && !in_list_reset(), "a panic does not leave it set");
}

/// With no queue at all nothing can be in flight: the next drain lets the batch go.
#[test]
fn without_queues_a_batch_goes_at_once() {
Expand Down Expand Up @@ -382,4 +490,81 @@ mod tests {
assert_eq!(fake.refs.load(Ordering::SeqCst), 0, "released once the queues are past");
hold_pipeline(0);
}

/// Inside a native list Reset `hold` makes no look at the queues: the last release is not made on
/// the calling thread (the late-release thread lets it go, at its own time).
#[test]
fn hold_inside_a_list_reset_leaves_the_release_to_the_thread() {
use std::sync::atomic::AtomicU32;
use std::thread::ThreadId;
#[repr(C)]
struct Fake {
vt: *const usize,
refs: AtomicU32,
released_on: Mutex<Option<ThreadId>>,
}
unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 {
(*(this as *const Fake)).refs.fetch_add(1, Ordering::SeqCst) + 1
}
unsafe extern "system" fn release(this: *mut c_void) -> u32 {
let f = &*(this as *const Fake);
*f.released_on.lock().unwrap() = Some(std::thread::current().id());
f.refs.fetch_sub(1, Ordering::SeqCst) - 1
}
// (an adopted object: the original table sits before the one the object points at)
let orig = [0usize, add_ref as usize, release as usize];
let ext = [orig.as_ptr() as usize, 0, 0, 0];
let fake = Box::new(Fake { vt: unsafe { ext.as_ptr().add(1) }, refs: AtomicU32::new(1), released_on: Mutex::new(None) });
let p = &*fake as *const Fake as usize;
{
let _in_reset = InListReset::enter();
unsafe { hold(p, true) };
}
assert_ne!(*fake.released_on.lock().unwrap(), Some(std::thread::current().id()), "not released by the caller");
let start = Instant::now();
while fake.refs.load(Ordering::SeqCst) != 0 && start.elapsed() < Duration::from_secs(10) {
std::thread::sleep(Duration::from_millis(5));
}
assert_eq!(fake.refs.load(Ordering::SeqCst), 0, "the thread lets it go");
assert_ne!(*fake.released_on.lock().unwrap(), Some(std::thread::current().id()));
}

/// Closing a batch takes the open one out (what is released meanwhile is behind later signals),
/// and a batch whose signals failed goes back, in order.
#[test]
fn a_batch_whose_signals_failed_goes_back_in_order() {
let mut held = Held::default();
held.open.push(Dead::Resource(0x1000));
let seal = unsafe { held.begin_seal(&[], true) }.expect("a batch to close");
assert!(held.open.is_empty() && held.sealed.is_empty());
held.open.push(Dead::Resource(0x2000));
held.end_seal(seal, false);
assert_eq!(held.open, vec![Dead::Resource(0x1000), Dead::Resource(0x2000)], "back, in order");
assert!(held.sealed.is_empty());
let seal = unsafe { held.begin_seal(&[], true) }.unwrap();
held.end_seal(seal, true);
assert!(held.open.is_empty() && held.sealed.len() == 1);
assert!(unsafe { held.begin_seal(&[], true) }.is_none(), "nothing open");
}

/// A batch in the middle of its seal still counts as held (a pinned `hold` waits for it), and
/// only one seal runs at a time: the open batch waits for the next one.
#[test]
fn a_seal_in_flight_counts_as_held_and_is_the_only_one() {
let mut held = Held::default();
held.open.push(Dead::Resource(0x1000));
let seal = unsafe { held.begin_seal(&[], true) }.unwrap();
assert!(held.open.is_empty() && held.sealed.is_empty());
assert!(!held.is_empty(), "the batch in the seal is not lost to is_empty");
held.open.push(Dead::Resource(0x2000));
assert!(unsafe { held.begin_seal(&[], true) }.is_none(), "no second seal at once");
assert_eq!(held.open, vec![Dead::Resource(0x2000)], "left open for the next one");
held.end_seal(seal, true);
assert!(!held.is_empty());
let seal = unsafe { held.begin_seal(&[], true) }.expect("free again");
held.end_seal(seal, true);
assert!(!seal_due(true, false, true, None) && !seal_due(false, true, true, None));
assert!(seal_due(false, false, true, Some(Duration::ZERO)));
assert!(!seal_due(false, false, false, Some(Duration::ZERO)) && seal_due(false, false, false, Some(SEAL_EVERY)));
}
}
5 changes: 4 additions & 1 deletion crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4140,7 +4140,10 @@ unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, in
std::mem::transmute(orig_fn(this, pc_slot!("ID3D12GraphicsCommandList", "Reset")));
let prepared = super::bind::PreparedNativePipeline::new(initial_state as usize);
let resolved = prepared.raw();
let hr = f(this, allocator, resolved as *mut c_void);
let hr = {
let _in_reset = super::late_release::InListReset::enter();
f(this, allocator, resolved as *mut c_void)
};
preserve_vtable(this, ext);
if hr >= 0 {
if !super::title_textures::is_own_work() && !super::present::presenting() {
Expand Down
Loading