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
99 changes: 88 additions & 11 deletions crates/xcl/src/hle/d3d12x/late_release.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,45 @@ struct Batch {
marks: Vec<(ID3D12Fence, u64)>,
}

/// A queue the title released whose reference here waits for the work it already has: a queue
/// must outlive what was submitted to it, as a resource does.
struct ReleasedQueue {
queue: usize,
fence: ID3D12Fence,
value: u64,
}

#[derive(Default)]
struct Held {
/// queue → its fence here and the last value signalled on it
fences: HashMap<usize, (ID3D12Fence, u64)>,
open: Vec<usize>,
sealed: VecDeque<Batch>,
last_seal: Option<Instant>,
/// queues let go by the title, still executing (`take_released_queues`)
queues: Vec<ReleasedQueue>,
}

// (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.queues.is_empty()
}

/// The released queues whose last signal has passed: their reference goes now.
fn take_released_queues(&mut self) -> Vec<usize> {
let mut gone = Vec::new();
self.queues.retain(|q| {
if unsafe { q.fence.GetCompletedValue() } >= q.value {
gone.push(q.queue);
false
} else {
true
}
});
gone
}

/// Close the open batch (at most every `SEAL_EVERY`, or `seal_now`) with a fence value on each of `queues`,
Expand Down Expand Up @@ -86,6 +110,53 @@ impl Held {

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

/// Forget the fence kept for a queue the title released: no batch may be waited on with it again
/// (a sealed batch holds its own clone), so its memory can go with the queue's (#1668).
pub fn forget_queue(queue: usize) {
if let Some(h) = HELD.lock().unwrap().as_mut() {
h.fences.remove(&queue);
}
}

/// `queue` is down to the one reference the submit tracking holds and the title is done with it
/// (`q_release`). The GPU may still have work submitted to the queue, and a queue has to outlive
/// it: signal a value on the queue's fence and keep the reference until every earlier
/// submission has passed it, as a resource's last release is held. Returns whether the reference
/// was taken (false: late release is off, the caller drops it now, as before).
/// The queue must not be used after this: it has left `present`'s list and `late_release`'s.
pub unsafe fn hold_queue(queue: usize) -> bool {
if !enabled() {
return false;
}
let raw = queue as *mut c_void;
let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&raw) else { return false };
let mut h = HELD.lock().unwrap();
let held = h.get_or_insert_with(Held::default);
if !held.fences.contains_key(&queue) {
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 { return false };
held.fences.insert(queue, (f, 0));
}
let (fence, value) = held.fences.get_mut(&queue).unwrap();
if q.Signal(&*fence, *value + 1).is_err() {
return false;
}
*value += 1;
let (fence, value) = (fence.clone(), *value);
held.fences.remove(&queue);
held.queues.push(ReleasedQueue { queue, fence, value });
drop(h);
ensure_thread();
true
}

/// `#[cfg(test)]`: the released queues whose reference is still held.
#[cfg(test)]
pub fn held_queues() -> Vec<usize> {
HELD.lock().unwrap().as_ref().map_or_else(Vec::new, |h| h.queues.iter().map(|q| q.queue).collect())
}

/// 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 Expand Up @@ -113,6 +184,11 @@ pub unsafe fn hold(res: usize) {
// A thread of its own lets the held ones go: the title may release a resource and then
// wait for its memory without another submit (an imported heap pins the pages under its
// resources – unmapping them stood still while one was held "until the next submit").
ensure_thread();
}

/// The one thread that lets held resources and released queues go (`hold`, `hold_queue`).
fn ensure_thread() {
static THREAD: std::sync::Once = std::sync::Once::new();
THREAD.call_once(|| {
let _ = std::thread::Builder::new().name("xcl-late-release".into()).spawn(|| loop {
Expand All @@ -128,24 +204,25 @@ pub unsafe fn drain_known(seal_now: bool) {
if HELD.lock().unwrap().as_ref().is_none_or(Held::is_empty) {
return;
}
let mut queues: Vec<ID3D12CommandQueue> = Vec::new();
for raw in super::present::known_queues() {
let raw = raw as *mut c_void;
if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&raw) {
queues.push(q.clone());
}
}
let mut queues: Vec<ID3D12CommandQueue> = super::present::known_queues_held();
queues.extend(super::sparse::queue());
queues.extend(super::title_textures::upload_queues());
let gone = match HELD.lock().unwrap().as_mut() {
Some(h) => h.drain(&queues, seal_now),
None => return,
let (gone, released) = {
let mut h = HELD.lock().unwrap();
let Some(h) = h.as_mut() else { return };
let gone = h.drain(&queues, seal_now);
(gone, h.take_released_queues())
};
// (outside the lock: a release may end other objects, whose releases come back here)
for res in gone {
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);
}
for q in released {
let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(super::real::orig_fn(q as *mut c_void, 2));
f(q as *mut c_void);
super::list_x::on_queue_release(q);
}
}

#[cfg(test)]
Expand Down
42 changes: 42 additions & 0 deletions crates/xcl/src/hle/d3d12x/present.rs
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,46 @@ pub fn known_queues() -> Vec<usize> {
QUEUES.lock().unwrap().clone()
}

/// The queues the title submitted work to, each with a reference of the caller's taken while it
/// is listed: `q_release` frees a queue the title lets go as soon as it has left the list, so a
/// pointer from [`known_queues`] may be freed before it is used (#1668).
pub fn known_queues_held() -> Vec<ID3D12CommandQueue> {
let q = QUEUES.lock().unwrap();
q.iter()
.filter_map(|&raw| {
let raw = raw as *mut c_void;
unsafe { ID3D12CommandQueue::from_raw_borrowed(&raw) }.cloned()
})
.collect()
}

/// `queue` is down to the one reference `note_execute` took to keep it valid for `late_release`:
/// the title is done with it. Forget it – and any use of it here – so the caller can let that
/// reference go: otherwise every queue a title ever submitted to (and the driver memory behind
/// it) stays allocated for the life of the process (#1668).
pub fn forget_queue(queue: usize) -> bool {
let tracked = {
let mut q = QUEUES.lock().unwrap();
let at = q.iter().position(|&x| x == queue);
if let Some(at) = at {
q.remove(at);
}
at.is_some()
};
// (a candidate for the window's present that is this queue: drop the resource it holds)
let dropped = {
let mut c = CANDIDATE.lock().unwrap();
match *c {
Some((q, _)) if q == queue => c.take().map(|(_, r)| r),
_ => None,
}
};
if let Some(r) = dropped {
unsafe { release(r) };
}
tracked
}

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

/// (PresentX calls, ExecuteCommandLists calls) so far
Expand Down Expand Up @@ -672,6 +712,7 @@ unsafe fn new_presenter(queue: usize) -> Option<Presenter> {
list.Close().ok()?;
let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
let event = CreateEventW(None, false, false, None).ok()?;
add_ref(queue); // (a swap chain may still be made for it: the title's own reference is not ours)
Some(Presenter {
queue, dev: dev.clone(), sc: None, w: 0, h: 0, fmt: DXGI_FORMAT_UNKNOWN,
alloc, spare_alloc, ring: PresentRing::new(actual_slots),
Expand Down Expand Up @@ -1112,6 +1153,7 @@ impl Drop for Presenter {
let _ = fence::wait(&self.fence, self.value, &self.dev, Some(self.event), 1000);
}
let _ = CloseHandle(self.event);
release(self.queue);
}
}
}
Expand Down
122 changes: 118 additions & 4 deletions crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6771,9 +6771,23 @@ unsafe extern "system" fn cl_release(this: *mut c_void) -> u32 {

unsafe extern "system" fn q_release(this: *mut c_void) -> u32 {
let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2));
let n = f(this);
let mut n = f(this);
if n == 0 {
super::list_x::on_queue_release(this as usize);
} else if n == 1 && super::present::forget_queue(this as usize) {
// Only the reference `present` keeps (to fence what `late_release` holds) is left: the
// title is done with this queue, so it does not stay allocated for the life of the
// process, as it did before #1668. The GPU may still have work submitted to it, though,
// and a queue must outlive that: the reference goes once the queue's fence has passed
// its last signal – `late_release` holds it, as it holds a resource's last release.
super::late_release::forget_queue(this as usize);
if super::late_release::hold_queue(this as usize) {
return 1;
}
n = f(this);
if n == 0 {
super::list_x::on_queue_release(this as usize);
}
}
n
}
Expand Down Expand Up @@ -7046,9 +7060,7 @@ pub fn drain_gpu() {
unsafe {
// a fence per queue (they finish in any order)
let mut fences = Vec::new();
for q in super::present::known_queues() {
let qr = q as *mut c_void;
let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&qr) else { continue };
for q in super::present::known_queues_held() {
let submit = || {
let f: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)
.map_err(|e| fence::api_error(dev, "CreateFence", e))?;
Expand Down Expand Up @@ -7726,6 +7738,108 @@ mod console_format_query_tests {
dev
}

/// #1668: a title that submits work to a queue and then releases it leaves nothing of that
/// queue behind. `note_execute` keeps a reference so `late_release` can fence what it holds;
/// when the title's own last release brings the count down to that one, the reference goes
/// too – otherwise every queue the title ever submitted to stays allocated, and a loop of
/// them made `CreateCommandQueue` fail with `E_OUTOFMEMORY` after 63 of 128 (issue #1668).
#[test]
fn a_queue_the_title_releases_is_not_kept_alive_by_the_submit_tracking() {
unsafe {
let Some(dev) = device() else { return };
let (raw, release) = submitted_queue(&dev);
// (not the count it returns: another test's `drain_known` may hold a reference of its
// own at this moment, and then its release is the one that lets the queue go)
release(raw);
assert!(untracked_soon(raw), "a queue let go is not tracked any more");
}
}

/// A reader of the tracked queues (`late_release`'s drain, `drain_gpu`) takes its references
/// while the queues are listed, so the title's last release cannot free one under it: the
/// queue stays – and stays listed – until the reader lets go, and goes then.
#[test]
fn a_tracked_queue_a_reader_holds_outlives_the_titles_release() {
unsafe {
let Some(dev) = device() else { return };
let (raw, release) = submitted_queue(&dev);
let held = crate::hle::d3d12x::present::known_queues_held();
assert!(held.iter().any(|q| q.as_raw() == raw), "the reader holds the tracked queue");
assert!(release(raw) >= 2, "the reader's reference and the tracking's are left");
assert!(
crate::hle::d3d12x::present::known_queues().contains(&(raw as usize)),
"a queue a reader still uses stays tracked"
);
drop(held);
assert!(untracked_soon(raw), "the reader's release lets the queue go");
}
}

/// A queue the title releases is not destroyed while the GPU still has work submitted to it:
/// its reference here is held until the queue's fence has passed the last signal, as a
/// resource's last release is (#1691, the device loss @upipibi saw in one run of six with
/// this PR merged onto `main`). The queue here waits on a fence nobody has signalled yet.
#[test]
fn a_released_queue_is_held_until_its_submitted_work_is_done() {
unsafe {
let Some(dev) = device() else { return };
let (raw, release) = submitted_queue(&dev);
let qraw = raw as *mut c_void;
let queue = ID3D12CommandQueue::from_raw_borrowed(&qraw).expect("the queue");
let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("CreateFence");
queue.Wait(&gate, 1).expect("Wait");
assert!(release(raw) >= 1, "the tracking reference is not dropped on the title's release");
assert!(
crate::hle::d3d12x::late_release::held_queues().contains(&(raw as usize)),
"the GPU may still run what was submitted to the queue: its reference is held"
);
// (the queue is usable while `late_release` holds it: it is alive, not gone)
assert_eq!(queue.GetDesc().Type, D3D12_COMMAND_LIST_TYPE_DIRECT, "the held queue is alive");
// the work completes, and then the reference goes
let signaller: ID3D12CommandQueue = dev
.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() })
.expect("CreateCommandQueue");
signaller.Signal(&gate, 1).expect("Signal");
let end = std::time::Instant::now() + std::time::Duration::from_secs(5);
while crate::hle::d3d12x::late_release::held_queues().contains(&(raw as usize)) {
assert!(std::time::Instant::now() < end, "the queue is let go once its work is done");
std::thread::sleep(std::time::Duration::from_millis(5));
}
}
}

/// A queue adopted as the title's, with work submitted to it: its pointer – the title's one
/// reference – and its (hooked) `Release`.
unsafe fn submitted_queue(dev: &ID3D12Device) -> (*mut c_void, unsafe extern "system" fn(*mut c_void) -> u32) {
let queue: ID3D12CommandQueue = dev
.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() })
.expect("CreateCommandQueue");
let raw = queue.as_raw() as *mut c_void;
std::mem::forget(queue); // (the only reference left is the title's)
super::adopt(raw, Kind::CommandQueue);
crate::hle::d3d12x::present::note_execute(raw, &[]);
assert!(
crate::hle::d3d12x::present::known_queues().contains(&(raw as usize)),
"a queue work was submitted to is tracked, for late_release to fence"
);
(raw, std::mem::transmute(*(*(raw as *const *mut usize)).add(2)))
}

/// Whether `queue` leaves the tracked queues (within 5 s: a reader in another test may hold
/// it for a moment).
fn untracked_soon(queue: *mut c_void) -> bool {
let end = std::time::Instant::now() + std::time::Duration::from_secs(5);
loop {
if !crate::hle::d3d12x::present::known_queues().contains(&(queue as usize)) {
return true;
}
if std::time::Instant::now() >= end {
return false;
}
std::thread::sleep(std::time::Duration::from_millis(5));
}
}

/// CheckFeatureSupport of the PC device as `dev_check_feature_support` reaches it (vtable #13).
fn pc_check(dev: &ID3D12Device) -> CheckFeatureSupportFn {
unsafe { std::mem::transmute(*(*(dev.as_raw() as *const *const usize)).add(13)) }
Expand Down
Loading