Queue-ordered page remap can redirect earlier GPU copy-back to the replacement backing #1131

Open
opened 2026-11-26 03:58:04 +00:00 by github-bot · 2 comments
Owner

@⁠NotADonky43 on GitHub · 2026-11-25 21:04 UTC · original

Reproduction (no game files)

On native Windows D3D12, allocate two different physical backings and initially map a destination VA to the first one. Keep an independent alias of the original physical backing so it can be inspected after the remap.

  1. Fill the original backing with 0x71 and the replacement with 0x23. Make a synthetic GPU texture copy whose readback writes 0x65 to the destination. Hold that copy on a logical queue behind an unsignalled fence.
  2. Issue CopyPageMappingsBatchX on the same queue to replace the destination backing. Before opening the fence, read the current destination byte.
  3. Signal the gate from a second queue, wait for the first queue to complete, and read both physical backings. A later GPU copy also checks which bytes the destination exposes.
Observation Expected Observed before the fix
Destination while the gate is closed 0x71 0x23
Original backing after the GPU copy 0x65 0x71
Replacement backing after the GPU copy 0x23 0x65

The test used a 256×192 RGBA8 texture on an RTX 5070 Ti. The wrong-page result was reproduced with the pre-ordering queue path after applying a separate Windows placeholder-boundary fix needed by the multi-page fixture. The current public queue handler still treats mapping as an immediate operation.

Candidate direction

Represent a page remap as work on its logical queue. Finish already-submitted work and its deferred writes before changing the destination's backing, and don't prepare newer commands on that queue against the old addresses. A local candidate retested on 085ee7c preserved both backing patterns and returned the expected bytes to the later GPU read with synchronous, deferred, and joined submission. The test also overwrites the caller's mapping descriptors after enqueueing to check that deferred work owns them.

This is a correctness finding, not an FPS claim or a diagnosis of a specific in-game artifact. A fix must also order presentation behind a pending remap and retain the queue through joined submission completion. Waiting for the shared host queue can cost time; the candidate is not ready to merge as-is.

**@⁠NotADonky43** on GitHub · 2026-11-25 21:04 UTC · [original](https://github.com/fxceless/victory-fork/issues/1131) ## Reproduction (no game files) On native Windows D3D12, allocate two different physical backings and initially map a destination VA to the first one. Keep an independent alias of the original physical backing so it can be inspected after the remap. 1. Fill the original backing with `0x71` and the replacement with `0x23`. Make a synthetic GPU texture copy whose readback writes `0x65` to the destination. Hold that copy on a logical queue behind an unsignalled fence. 2. Issue `CopyPageMappingsBatchX` on the same queue to replace the destination backing. Before opening the fence, read the current destination byte. 3. Signal the gate from a second queue, wait for the first queue to complete, and read both physical backings. A later GPU copy also checks which bytes the destination exposes. | Observation | Expected | Observed before the fix | | --- | --- | --- | | Destination while the gate is closed | `0x71` | `0x23` | | Original backing after the GPU copy | `0x65` | `0x71` | | Replacement backing after the GPU copy | `0x23` | `0x65` | The test used a 256×192 RGBA8 texture on an RTX 5070 Ti. The wrong-page result was reproduced with the pre-ordering queue path after applying a separate Windows placeholder-boundary fix needed by the multi-page fixture. [The current public queue handler](https://github.com/fxceless/victory-fork/blob/085ee7c4c3d1dfaed41d683fa9f465a6f9dac8c3/crates/victory-gpu/src/queue.rs#L1479) still treats mapping as an immediate operation. ## Candidate direction Represent a page remap as work on its logical queue. Finish already-submitted work and its deferred writes before changing the destination's backing, and don't prepare newer commands on that queue against the old addresses. A local candidate retested on `085ee7c` preserved both backing patterns and returned the expected bytes to the later GPU read with synchronous, deferred, and joined submission. The test also overwrites the caller's mapping descriptors after enqueueing to check that deferred work owns them. This is a correctness finding, not an FPS claim or a diagnosis of a specific in-game artifact. A fix must also order presentation behind a pending remap and retain the queue through joined submission completion. Waiting for the shared host queue can cost time; the candidate is not ready to merge as-is.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 03:58:04 +00:00
Author
Owner

@⁠NotADonky43 on GitHub · 2026-11-25 21:21 UTC · original

Follow-up: the source-only candidate now fixes the two issues identified in the first review.

  • A queue segment containing a page remap keeps its ordering until it drains. A resource-backed present waits behind that segment, even if the optional async-present mode is off or the remap ran inline. The legacy force-present path cannot skip either a wait before the remap or a dependent wait after it.
  • Joined submissions own their queue marks until after cleanup drops the queue mutex guard. A caller releasing its queue and fence references cannot free objects that the joined submission still needs. A deferred present retains its source through the GPU copy. First host initialization also cannot race a pre-device remap.

The tests separate queue/presentation ordering from real GPU writes. The queue test uses an observer at the host-present boundary (not a desktop or game display check). The native D3D12 fixture releases both client queues and its copy fence with work still pending, then verifies the old backing, replacement backing, and later GPU read. This is a correctness patch, not a game visual, stability, or FPS claim. Remaps can still wait on the shared host submission lane, and existing partial-map error handling is unchanged.

Applying the source patches

Start from 085ee7c4c3d1dfaed41d683fa9f465a6f9dac8c3 or c36971b213770e48f513f0d6e3ced3f1f65a32b2. Apply the standalone Windows placeholder-boundary patch from #824 first, then the runtime/queue diff below, then the fixture diff in the next comment. Both diffs are against that prerequisite; no game files or assets are needed.

Verification: On c36971b the 8 queue tests, 14 XMem tests, and real D3D12 readback on the RTX 5070 Ti passed. The GPU fixture passed with synchronous and deferred execution and with joined submissions, both with and without relay copy-back. GPU-based validation was on. The optimized build succeeded. The same patch had 588 workspace tests pass on 085ee7c, with the independently failing baseline WARP budget test excluded. No game launch or visual claim.

Part 1 of 2 — runtime and queue regressions
diff --git a/crates/victory-gpu/src/fence.rs b/crates/victory-gpu/src/fence.rs
index b820335..4486b08 100644
--- a/crates/victory-gpu/src/fence.rs
+++ b/crates/victory-gpu/src/fence.rs
@@ -35,6 +35,29 @@ struct Fence {
     asked: Mutex<Vec<pace::Asked>>,
 }
 
+/// Keep a console fence alive while a queue or a late host flight names it.
+#[cfg(windows)]
+pub(crate) struct FenceRef(usize);
+
+#[cfg(windows)]
+impl FenceRef {
+    pub(crate) fn new(this: This) -> Self {
+        object::add_ref(this);
+        Self(this as usize)
+    }
+
+    pub(crate) fn as_ptr(&self) -> This {
+        self.0 as This
+    }
+}
+
+#[cfg(windows)]
+impl Drop for FenceRef {
+    fn drop(&mut self) {
+        object::release_boxed::<Fence>(self.as_ptr());
+    }
+}
+
 fn fence<'a>(this: This) -> &'a Fence {
     // SAFETY: called from fence methods only.
     unsafe { &*this.cast::<Fence>() }
diff --git a/crates/victory-gpu/src/framelog.rs b/crates/victory-gpu/src/framelog.rs
index 7806ab6..268fcc4 100644
--- a/crates/victory-gpu/src/framelog.rs
+++ b/crates/victory-gpu/src/framelog.rs
@@ -63,6 +63,8 @@ pub enum T {
     Remaps,
     RemapUs,
     RemapWaitUs,
+    /// Queue page maps waiting for host submission and deferred copy-back.
+    MapQueueWaitUs,
     /// Texture refreshes on every thread, and of them the wait for title
     /// memory to hold still; uploads recorded.
     RefreshUs,
@@ -412,7 +414,7 @@ fn text(f: &Frame) -> String {
          send-and-hash lists {:.1} ms in {:.0}, our compare lists {:.1} ms in {:.0}, all other lists {:.1} ms in {:.0} | \
          recording, all threads: {:.1} ms in {:.0} calls; all submit calls {:.1} ms | textures: refresh {:.1} ms ({:.1} waiting for memory to hold \
          still), {:.0} uploads, staging {:.0} made {:.0} reused | remapping: {:.0} calls {:.1} ms ({:.1} waiting for \
-         readers) | pipelines: {:.0} made, {:.0} loaded, {:.1} ms waited | disk: {:.0} reads {:.1} MB {:.1} worker ms | \
+         readers), {:.1} ms queue/copy-back wait | pipelines: {:.0} made, {:.0} loaded, {:.1} ms waited | disk: {:.0} reads {:.1} MB {:.1} worker ms | \
          faults: {:.0} page, {:.0} guard | process: {:.0} user {:.0} kernel ms | pacing, all threads {:.1} ms | {:.0} \
          draws | {:.0} MB free | found on a slow core: the render thread {:.0} of {:.0} looks, the submit thread {:.0} of {:.0}, recording threads {:.0} of {:.0}",
         f.us / 1e3,
@@ -454,6 +456,7 @@ fn text(f: &Frame) -> String {
         t(T::Remaps),
         ms(T::RemapUs),
         ms(T::RemapWaitUs),
+        ms(T::MapQueueWaitUs),
         s(S_PIPELINES_MADE),
         s(S_PIPELINES_LOADED),
         ms(T::PipelineWaitUs),
diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs
index bc4a64a..f4c1b6e 100644
--- a/crates/victory-gpu/src/host.rs
+++ b/crates/victory-gpu/src/host.rs
@@ -577,10 +577,17 @@ pub(crate) fn fail(what: std::fmt::Arguments) -> ! {
     }
 }
 
+static HOST: OnceLock<Option<Host>> = OnceLock::new();
+/// Serialize the first host publication with mappings made before it exists.
+static HOST_INIT: Mutex<()> = Mutex::new(());
+
 /// The host GPU, created on first use; `None` without one (a run then
 /// behaves as before: nothing executes).
 pub(crate) fn host() -> Option<&'static Host> {
-    static HOST: OnceLock<Option<Host>> = OnceLock::new();
+    if let Some(host) = HOST.get() {
+        return host.as_ref();
+    }
+    let _initializing = HOST_INIT.lock().unwrap_or_else(|e| e.into_inner());
     HOST.get_or_init(|| match create() {
         Ok(host) => Some(host),
         Err(e) => {
@@ -2475,7 +2482,7 @@ enum Late {
     /// A bottom-of-pipe write of the flight before it: address, what, bytes.
     Write(usize, crate::queue::Written, usize),
     /// A fence (its address) signalled behind the flights before it.
-    Signal(usize, u64),
+    Signal(crate::fence::FenceRef, u64),
 }
 
 struct Line {
@@ -3066,7 +3073,7 @@ fn stale_under_flights(runs: &[&HostList]) -> bool {
 /// A fence signal on a queue ([`late`]): goes behind the flights in the
 /// air, if there are any, and is set when they are settled. Whether it
 /// did; if not the caller sets the fence now.
-pub(crate) fn late_signal(fence: usize, value: u64) -> bool {
+pub(crate) fn late_signal(fence: crate::object::This, value: u64) -> bool {
     if !late() {
         return false;
     }
@@ -3074,7 +3081,7 @@ pub(crate) fn late_signal(fence: usize, value: u64) -> bool {
     if line.line.is_empty() && !line.settling {
         return false;
     }
-    line.line.push(Late::Signal(fence, value));
+    line.line.push(Late::Signal(crate::fence::FenceRef::new(fence), value));
     LATE_STATS[14].fetch_add(1, Ordering::Relaxed);
     drop(line);
     // A signal alone (behind a settle under way) has no flight to wake
@@ -3170,6 +3177,29 @@ pub(crate) fn settle_for_fence() {
     settle_now(WHY_FENCE);
 }
 
+/// Change title memory after already submitted flights and their deferred
+/// writes. There is one host flight line, shared by the emulated queues.
+/// Keep another submission from preparing new reads between the settle
+/// and the map. The closure may acquire title-memory locks, not submit.
+pub(crate) fn with_page_mapping<T>(map: impl FnOnce() -> T) -> T {
+    let started = std::time::Instant::now();
+    // If the host doesn't exist yet, keep it from being published until
+    // this map finishes. This doesn't trigger GPU initialization for a map.
+    let initializing = HOST.get().is_none().then(|| HOST_INIT.lock().unwrap_or_else(|e| e.into_inner()));
+    let host = HOST.get();
+    let initializing = if host.is_some() { drop(initializing); None } else { initializing };
+    let submitted = host.and_then(Option::as_ref).map(|host| {
+        let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
+        host.settle(&mut submitted, WHY_SYNC);
+        submitted
+    });
+    crate::framelog::add(crate::framelog::T::MapQueueWaitUs, started.elapsed().as_micros() as u64);
+    let result = map();
+    drop(submitted);
+    drop(initializing);
+    result
+}
+
 /// Resets the host lists of settled flights and keeps them for reuse, as
 /// a queue does for the lists it ran (`crate::list::recycle`).
 fn land() {
@@ -4937,7 +4967,7 @@ impl Host {
                     landed.push((flight.lists, flight.order));
                 }
                 Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes),
-                Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value),
+                Late::Signal(fence, value) => crate::fence::set(fence.as_ptr(), value),
             }
         }
         if last > 0 {
@@ -5363,7 +5393,7 @@ impl Host {
                         landed.push((flight.lists, flight.order));
                     }
                     Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes),
-                    Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value),
+                    Late::Signal(fence, value) => crate::fence::set(fence.as_ptr(), value),
                 }
             }
             if last > 0 {
@@ -8013,6 +8043,9 @@ impl Host {
     /// shown; else, in diagnostics builds, whether the frame was black.
     pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option<bool> {
         let showing = std::time::Instant::now();
+        // Draining may itself present a queued frame. Do it before taking
+        // the presenter mutex, never from the synchronous copy below.
+        crate::queue::before_sync();
         let shown = self.present_now(texture, state, frame);
         crate::framelog::add(crate::framelog::T::PresentShowUs, showing.elapsed().as_micros() as u64);
         shown
@@ -8093,6 +8126,11 @@ impl Host {
                 None => &p.copy,
             };
             copy.reset();
+            // A queued present may be the title texture's last owner. A
+            // submit-ahead copy still refers to it after this call returns.
+            if slot.is_some() {
+                copy.keep(texture);
+            }
             let list = &copy.list;
             list.ResourceBarrier(&[
                 transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE),
@@ -8128,7 +8166,9 @@ impl Host {
                     let flown = self.execute_own(copy);
                     p.ahead[i].1 = flown;
                 }
-                None => self.execute(&[copy]),
+                None => {
+                    self.submit(&[copy], false);
+                }
             }
             #[cfg(feature = "diagnostics")]
             if let Some((buffer, footprint)) = capture {
diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs
index a924511..070f194 100644
--- a/crates/victory-gpu/src/queue.rs
+++ b/crates/victory-gpu/src/queue.rs
@@ -6,6 +6,8 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
 
 use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, QUEUE, S_OK, Table, This, guid};
 use crate::resource::PAGEABLE_IIDS;
+#[cfg(windows)]
+use crate::fence::FenceRef;
 
 const QUEUE_IIDS: [Iid; 4] = [
     guid(
@@ -37,31 +39,89 @@ struct Queue {
     /// What the queue was given after a wait for a fence that had not been
     /// reached, in order; it runs when the fence gets there.
     #[cfg(windows)]
-    held: std::sync::Mutex<Vec<Held>>,
+    held: std::sync::Mutex<QueueLine>,
 }
 const _: () = assert!(std::mem::offset_of!(Queue, kind) == 0x10);
 
+#[cfg(windows)]
+#[derive(Default)]
+struct QueueLine {
+    items: Vec<Held>,
+    // A pending remap commits this segment to real queue ordering. Keep the
+    // flag until the line drains, including after the remap has executed:
+    // a dependent run may still be waiting when its present is called.
+    ordered: bool,
+}
+
+#[cfg(windows)]
+impl std::ops::Deref for QueueLine {
+    type Target = Vec<Held>;
+
+    fn deref(&self) -> &Self::Target {
+        &self.items
+    }
+}
+
+#[cfg(windows)]
+impl std::ops::DerefMut for QueueLine {
+    fn deref_mut(&mut self) -> &mut Self::Target {
+        &mut self.items
+    }
+}
+
+#[cfg(windows)]
+impl QueueLine {
+    fn unregister_if_drained(&mut self, queue: usize) {
+        if self.is_empty() {
+            self.ordered = false;
+            lock(&WAITING).retain(|w| w.0 != queue);
+        }
+    }
+}
+
 /// One thing a waiting queue holds back.
 #[cfg(windows)]
 enum Held {
-    /// The queue waits for the fence (its address) to reach the value.
-    Wait(usize, u64),
+    /// The queue waits for the fence to reach the value.
+    Wait(FenceRef, u64),
     /// A list of the next submission waits for a memory value.
     Value(crate::list::ValueWait),
     /// A submission: the lists' host sides, taken from the title's lists
     /// (which it may reset meanwhile), and the order they run in.
     Run(Vec<crate::list::Detached>, Vec<usize>),
+    /// A page mapping change, after preceding submissions and their copy-back.
+    MapPages(QueuedPageMappings),
     /// A signal of the queue's, due after what it holds before it.
-    Signal(usize, u64),
+    Signal(FenceRef, u64),
     /// With [`behind`]: the submission at the head of the line is being
     /// prepared and sent by our thread, with the line unlocked, so the
     /// title can add to its end meanwhile; whatever is added stays behind
     /// this (the line is not empty), signals too.
     Running,
-    /// With [`present_behind`]: the title's present of a frame, due after
-    /// what the queue holds before it: the host texture shown, the state
-    /// the title's lists leave it in, and the frame's number.
-    Present(windows::Win32::Graphics::Direct3D12::ID3D12Resource, u32, u64),
+    /// A frame shown after the work already admitted to this queue.
+    Present(PresentSource),
+}
+
+#[cfg(windows)]
+enum PresentSource {
+    Texture(std::sync::Arc<crate::resource::HostTexture>, u32, u64),
+    #[cfg(test)]
+    Observe(Box<dyn FnOnce() + Send>),
+}
+
+#[cfg(windows)]
+impl PresentSource {
+    fn show(self) {
+        match self {
+            Self::Texture(texture, state, frame) => {
+                if let Some(host) = crate::host::host() {
+                    let _ = host.present(&texture.texture, state, frame);
+                }
+            }
+            #[cfg(test)]
+            Self::Observe(observe) => observe(),
+        }
+    }
 }
 
 /// Presents that are in a queue's line and have not run ([`Held::Present`]).
@@ -89,7 +149,8 @@ static PRESENTS_HELD: AtomicU64 = AtomicU64::new(0);
 /// before it still in a line runs the old way (the lines first, then
 /// itself), and so does a frame that is saved or listed, and a present
 /// that finds its queue's line empty. A wait nothing ever meets is
-/// therefore still forced, by the present after it.
+/// therefore still forced, by the present after it, except across ordered
+/// mappings. These presents must queue regardless of the experiment switch.
 ///
 /// What it assumes, beyond what [`behind`] does: title memory a submission
 /// reads stays as it was until the submission's fence is signalled, also
@@ -132,46 +193,74 @@ fn present_behind() -> bool {
     }
 }
 
-/// With [`present_behind`]: puts the present of the next frame behind what
-/// the queue `this` holds. False if it has to run the old way.
+/// Optional pipelining never overrides a mapping's ordering requirement.
+#[cfg(windows)]
+fn present_admission(line: &QueueLine, opportunistic: bool) -> Option<bool> {
+    if line.ordered {
+        Some(true)
+    } else if opportunistic && !line.is_empty() && PRESENTS_HELD.load(Ordering::Relaxed) == 0 {
+        Some(false)
+    } else {
+        None
+    }
+}
+
+#[cfg(windows)]
+fn enqueue_present(this: This, opportunistic: bool, source: impl FnOnce() -> Option<PresentSource>) -> bool {
+    let line = &queue(this).held;
+    if present_admission(&lock(line), opportunistic).is_none() {
+        return false;
+    }
+    // Resolving a host texture can allocate. Never do it under the line lock.
+    let Some(source) = source() else { return false };
+    let mut held = lock(line);
+    let Some(ordered) = present_admission(&held, opportunistic) else { return false };
+    PRESENTS_HELD.fetch_add(1, Ordering::Relaxed);
+    held.push(Held::Present(source));
+    mark_waiting(this);
+    drop(held);
+    if !ordered {
+        let behind = PRESENTS_BEHIND.fetch_add(1, Ordering::Relaxed) + 1;
+        if behind.is_multiple_of(512) {
+            tracing::info!(behind, "presents sent ahead of the caller by the optional async-present mode");
+        }
+        wake();
+    }
+    // In synchronous mode the operation ahead of an ordered present will
+    // resume the line on return or when its wait is satisfied.
+    true
+}
+
 #[cfg(windows)]
-fn send_behind(this: This, planes: u32, plane_parameters: *const Plane) -> bool {
-    if this.is_null() || planes == 0 || PRESENTS_HELD.load(Ordering::Relaxed) != 0 {
+fn send_behind(this: This, resource: This, frame: u64, opportunistic: bool) -> bool {
+    if this.is_null() || resource.is_null() {
         return false;
     }
-    let frame = FRAMES.load(Ordering::Relaxed) + 1;
-    // A frame that is saved or listed is read back at once.
+    // Optional presents avoid synchronous captures; required ordering applies
+    // to those frames too. Host::present still handles their readback.
     #[cfg(feature = "diagnostics")]
-    if crate::capture::wanted(frame) || crate::capture::listed(frame) {
-        return false;
+    let opportunistic = opportunistic && !crate::capture::wanted(frame) && !crate::capture::listed(frame);
+    enqueue_present(this, opportunistic, || {
+        let texture = crate::resource::host_copy(resource)?;
+        let state = texture.state.load(Ordering::Relaxed);
+        Some(PresentSource::Texture(texture, state, frame))
+    })
+}
+
+#[cfg(windows)]
+fn present_resource(planes: u32, plane_parameters: *const Plane) -> This {
+    if planes == 0 {
+        return std::ptr::null();
     }
     // SAFETY: the title passes `planes` plane descriptions.
     let Some(plane) = (unsafe { plane_parameters.as_ref() }) else {
-        return false;
+        return std::ptr::null();
     };
     if plane.count == 0 || plane.resources.is_null() {
-        return false;
+        return std::ptr::null();
     }
     // SAFETY: the plane lists `count` resources.
-    let resource = unsafe { *plane.resources };
-    let Some(texture) = crate::resource::host_resource(resource) else {
-        return false;
-    };
-    // The state the lists recorded so far leave the texture in: what our
-    // copy finds it in when it runs behind them (looked at, not changed).
-    const COPY_SOURCE: u32 = 0x800;
-    let state = crate::resource::host_transition(resource, COPY_SOURCE).map_or(COPY_SOURCE, |(_, before)| before);
-    crate::resource::host_transition(resource, state);
-    let texture = texture.clone();
-    let sent = hold(this, || {
-        PRESENTS_HELD.fetch_add(1, Ordering::Relaxed);
-        Held::Present(texture, state, frame)
-    });
-    if sent {
-        PRESENTS_BEHIND.fetch_add(1, Ordering::Relaxed);
-        wake();
-    }
-    sent
+    unsafe { *plane.resources }
 }
 
 /// Presents sent behind their queue's line since the start
@@ -179,9 +268,35 @@ fn send_behind(this: This, planes: u32, plane_parameters: *const Plane) -> bool
 #[cfg(windows)]
 static PRESENTS_BEHIND: AtomicU64 = AtomicU64::new(0);
 
-/// The queues that hold something (their addresses).
+/// The queues that hold something, with a reference held until their line
+/// is drained. The releaser also pins its snapshot before dropping the lock.
+#[cfg(windows)]
+static WAITING: std::sync::Mutex<Vec<QueueRef>> = std::sync::Mutex::new(Vec::new());
+
+#[cfg(windows)]
+struct QueueRef(usize);
+
+#[cfg(windows)]
+impl QueueRef {
+    fn new(this: This) -> Self {
+        object::add_ref(this);
+        Self(this as usize)
+    }
+}
+
+#[cfg(windows)]
+impl Clone for QueueRef {
+    fn clone(&self) -> Self {
+        Self::new(self.0 as This)
+    }
+}
+
 #[cfg(windows)]
-static WAITING: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new());
+impl Drop for QueueRef {
+    fn drop(&mut self) {
+        object::release_boxed::<Queue>(self.0 as This);
+    }
+}
 
 #[cfg(windows)]
 fn lock<T>(mutex: &std::sync::Mutex<T>) -> std::sync::MutexGuard<'_, T> {
@@ -325,10 +440,7 @@ fn submit_cut(this: This, lists: &[This]) {
                 held.extend(waits.into_iter().map(Held::Value));
                 held.push(Held::Run(taken, order));
             }
-        }
-        let mut waiting = lock(&WAITING);
-        if !waiting.contains(&(this as usize)) {
-            waiting.push(this as usize);
+            mark_waiting(this);
         }
     }
     // What ran may be what another queue waits for, and what was just
@@ -416,11 +528,9 @@ fn submit_split(this: This, lists: &[This]) {
             pieces.push(Held::Run(taken, order));
             from = to;
         }
-        lock(&queue(this).held).extend(pieces);
-        let mut waiting = lock(&WAITING);
-        if !waiting.contains(&(this as usize)) {
-            waiting.push(this as usize);
-        }
+        let mut held = lock(&queue(this).held);
+        held.extend(pieces);
+        mark_waiting(this);
     }
     // What ran may be what another queue waits for, and what was just held
     // may be free to run already.
@@ -630,14 +740,25 @@ struct Joined {
     order: Vec<usize>,
     parts: usize,
     /// Signals met behind those parts: delivered when the parts are sent.
-    signals: Vec<(usize, u64)>,
+    signals: Vec<(FenceRef, u64)>,
     /// The queues with a part here: each has [`Held::Running`] at the
     /// head of its line.
-    marked: Vec<usize>,
+    marked: Vec<QueueRef>,
 }
 
 #[cfg(windows)]
 impl Joined {
+    fn has_mark(&self, queue: usize) -> bool {
+        self.marked.iter().any(|owner| owner.0 == queue)
+    }
+
+    fn mark(&mut self, owner: &QueueRef, line: &mut Vec<Held>) {
+        if !self.has_mark(owner.0) {
+            line.insert(0, Held::Running);
+            self.marked.push(owner.clone());
+        }
+    }
+
     fn is_empty(&self) -> bool {
         self.parts == 0
     }
@@ -708,20 +829,19 @@ fn send_joined(joined: &mut Joined) {
     }
     // Behind what was just sent, in the order they were met.
     for (fence, value) in joined.signals.drain(..) {
-        if !crate::host::late_signal(fence, value) {
-            crate::fence::set(fence as This, value);
+        if !crate::host::late_signal(fence.as_ptr(), value) {
+            crate::fence::set(fence.as_ptr(), value);
         }
     }
-    for q in joined.marked.drain(..) {
-        // SAFETY: a live queue, as in the loop that marked it.
-        let line = unsafe { &(*(q as *const Queue)).held };
+    for owner in joined.marked.drain(..) {
+        // `owner` pins this queue independently of the waiting registry. In
+        // particular the mutex must outlive removal of its registry entry.
+        let line = &queue(owner.0 as This).held;
         let mut held = lock(line);
         if matches!(held.first(), Some(Held::Running)) {
             held.remove(0);
         }
-        if held.is_empty() {
-            lock(&WAITING).retain(|&w| w != q);
-        }
+        held.unregister_if_drained(owner.0);
     }
 }
 
@@ -758,18 +878,20 @@ fn release_held_now(all: bool) {
     loop {
         let queues = lock(&WAITING).clone();
         let mut moved = false;
-        for q in queues {
-            // SAFETY: a live queue: one released is taken off the list.
+        for owner in queues {
+            let q = owner.0;
+            // SAFETY: the snapshot holds an owned reference for this visit.
             let line = unsafe { &(*(q as *const Queue)).held };
             let mut held = lock(line);
             loop {
                 // A queue with a part in `joined` has our mark at the head
                 // of its line: what is looked at is behind the mark.
-                let base = usize::from(joined.marked.contains(&q));
+                let base = usize::from(joined.has_mark(q));
                 match held.get(base) {
                     None | Some(Held::Running) => break,
-                    Some(&Held::Wait(fence, value))
-                        if !all && crate::fence::completed(fence as This) < value =>
+                    Some(Held::Wait(fence, value))
+                        if crate::fence::completed(fence.as_ptr()) < *value
+                            && !may_force_queue(all, &held) =>
                     {
                         break;
                     }
@@ -784,18 +906,21 @@ fn release_held_now(all: bool) {
                             JOINED[4].fetch_add(1, Ordering::Relaxed);
                         }
                     }
-                    Some(Held::Value(wait)) if !all && !value_met(wait) => break,
-                    // The frame is shown behind the parts taken: they are
-                    // sent first.
-                    Some(Held::Present(..)) if !joined.is_empty() => break,
+                    Some(Held::Value(wait))
+                        if !may_force_queue(all, &held) && !value_met(wait) => break,
+                    // Both are boundaries for joined submissions. In
+                    // particular no list after a remap can prepare its
+                    // memory reads using the previous mapping.
+                    Some(Held::Present(..) | Held::MapPages(..)) if !joined.is_empty() => break,
                     Some(_) => {}
                 }
                 match held.remove(base) {
-                    Held::Wait(..) | Held::Running => {}
+                    Held::Wait(..) => {}
+                    Held::Running => unreachable!("in-flight queue work cannot be removed here"),
                     Held::Value(wait) => {
                         // Passed at a present without being met: what the
                         // queue stood at.
-                        if all && !value_met(&wait) {
+                        if may_force_queue(all, &held) && !value_met(&wait) {
                             static SEEN: AtomicU64 = AtomicU64::new(0);
                             if SEEN.fetch_add(1, Ordering::Relaxed) < 16 {
                                 tracing::warn!(
@@ -831,10 +956,7 @@ fn release_held_now(all: bool) {
                         if joining {
                             // Taken, to go with the parts that follow it.
                             // The line stays open behind our mark.
-                            if !joined.marked.contains(&q) {
-                                held.insert(0, Held::Running);
-                                joined.marked.push(q);
-                            }
+                            joined.mark(&owner, &mut held);
                             joined.add(lists, order);
                             if joined.full() {
                                 drop(held);
@@ -880,7 +1002,7 @@ fn release_held_now(all: bool) {
                                 crate::list::recycle(lists, &order);
                             }
                         }
-                        if all {
+                        if all && may_force_queue(all, &held) {
                             #[cfg(feature = "diagnostics")]
                             crate::copystat::add(crate::copystat::C::Forced, 1);
                             static ONCE: AtomicBool = AtomicBool::new(false);
@@ -891,25 +1013,24 @@ fn release_held_now(all: bool) {
                             }
                         }
                     }
-                    Held::Present(texture, state, frame) => {
-                        let show = || {
-                            if let Some(host) = crate::host::host() {
-                                let _ = host.present(&texture, state, frame);
-                            }
-                        };
-                        if all {
-                            show();
-                        } else {
-                            // The line is open while the frame is shown,
-                            // as it is while a submission is prepared.
-                            held.insert(0, Held::Running);
-                            drop(held);
-                            show();
-                            held = lock(line);
-                            if matches!(held.first(), Some(Held::Running)) {
-                                held.remove(0);
-                            }
-                        }
+                    Held::MapPages(work) => {
+                        held.insert(0, Held::Running);
+                        drop(held);
+                        // Host flights are a shared line, not split by title
+                        // queue. Finish prior copy-back before changing any
+                        // backing. Do not hold a queue mutex during the wait.
+                        crate::host::with_page_mapping(|| {
+                            work.pool.apply(work.batches.iter().map(|(at, ranges)| (*at, ranges.as_slice())));
+                        });
+                        held = lock(line);
+                        held.remove(0);
+                    }
+                    Held::Present(source) => {
+                        held.insert(0, Held::Running);
+                        drop(held);
+                        source.show();
+                        held = lock(line);
+                        held.remove(0);
                         PRESENTS_HELD.fetch_sub(1, Ordering::Relaxed);
                     }
                     // Behind what was sent to the card and not waited
@@ -918,16 +1039,14 @@ fn release_held_now(all: bool) {
                         if !joined.is_empty() {
                             // Behind parts not sent yet: with them.
                             joined.signals.push((fence, value));
-                        } else if !crate::host::late_signal(fence, value) {
-                            crate::fence::set(fence as This, value);
+                        } else if !crate::host::late_signal(fence.as_ptr(), value) {
+                            crate::fence::set(fence.as_ptr(), value);
                         }
                     }
                 }
                 moved = true;
             }
-            if held.is_empty() {
-                lock(&WAITING).retain(|&w| w != q);
-            }
+            held.unregister_if_drained(q);
         }
         if !moved {
             if joined.is_empty() {
@@ -940,6 +1059,13 @@ fn release_held_now(all: bool) {
     }
 }
 
+/// The legacy present-time escape hatch must not force commands through a
+/// real wait in front of a pending mapping change (or the remap itself).
+#[cfg(windows)]
+fn may_force_queue(all: bool, line: &QueueLine) -> bool {
+    all && !line.ordered
+}
+
 /// Whether a queue may pass `wait`: memory holds the value, or, with
 /// submissions sent to the card without a wait (`crate::host::late`), it
 /// will once those in the air have run.
@@ -1020,12 +1146,7 @@ extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT
     )
 }
 extern "system" fn release(this: This) -> u32 {
-    let left = object::release_boxed::<Queue>(this);
-    #[cfg(windows)]
-    if left == 0 {
-        lock(&WAITING).retain(|&q| q != this as usize);
-    }
-    left
+    object::release_boxed::<Queue>(this)
 }
 
 /// Runs the lists' host lists and waits for them (decision 0007). A queue
@@ -1067,11 +1188,9 @@ fn execute_now(this: This, count: u32, lists: *const This) {
                 if SEEN.fetch_add(1, Ordering::Relaxed) < 8 {
                     tracing::info!(kind = queue(this).kind, ?unmet, "a submission is held for a memory value");
                 }
-                lock(&queue(this).held).extend(unmet.into_iter().map(Held::Value));
-                let mut waiting = lock(&WAITING);
-                if !waiting.contains(&(this as usize)) {
-                    waiting.push(this as usize);
-                }
+                let mut held = lock(&queue(this).held);
+                held.extend(unmet.into_iter().map(Held::Value));
+                mark_waiting(this);
             }
         }
         let kept = hold(this, || {
@@ -1147,13 +1266,13 @@ extern "system" fn signal(this: This, fence: This, value: u64) -> HRESULT {
     crate::fence::pace::signal_called(fence as usize, value);
     // A queue that waits signals after what it holds.
     #[cfg(windows)]
-    if hold(this, || Held::Signal(fence as usize, value)) {
+    if hold(this, || Held::Signal(FenceRef::new(fence), value)) {
         return S_OK;
     }
     // Behind the submissions sent to the card and not waited for: the
     // fence is set when they are settled.
     #[cfg(windows)]
-    if crate::host::late_signal(fence as usize, value) {
+    if crate::host::late_signal(fence, value) {
         return S_OK;
     }
     let _ = this;
@@ -1186,7 +1305,8 @@ extern "system" fn wait(this: This, fence: This, value: u64) -> HRESULT {
             let mut held = lock(&queue(this).held);
             let behind = !held.is_empty() || now < value;
             if behind && waits() {
-                held.push(Held::Wait(fence as usize, value));
+                held.push(Held::Wait(FenceRef::new(fence), value));
+                mark_waiting(this);
             }
             behind
         };
@@ -1203,12 +1323,6 @@ extern "system" fn wait(this: This, fence: This, value: u64) -> HRESULT {
             }
         }
         if behind && waits() {
-            {
-                let mut waiting = lock(&WAITING);
-                if !waiting.contains(&(this as usize)) {
-                    waiting.push(this as usize);
-                }
-            }
             // The fence may have got there meanwhile.
             release_held(false);
         }
@@ -1311,10 +1425,14 @@ fn present_now(this: This, planes: u32, plane_parameters: *const Plane) -> HRESU
     crate::copystat::present_begins();
     #[cfg(all(windows, feature = "diagnostics"))]
     crate::profile::frame();
-    // With `present_behind`: the frame is shown by our thread, behind what
-    // the queue holds, and nothing is run or waited for here.
+
+    let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1;
+    // A mapping (even one running inline) and its dependent work are a
+    // required presentation boundary, independent of the async-present mode.
+    #[cfg(windows)]
+    let resource = present_resource(planes, plane_parameters);
     #[cfg(windows)]
-    let sent_behind = present_behind() && send_behind(this, planes, plane_parameters);
+    let sent_behind = send_behind(this, resource, frame, present_behind());
     #[cfg(not(windows))]
     let _ = this;
     // Submissions sent to the card and not waited for are settled first,
@@ -1335,23 +1453,17 @@ fn present_now(this: This, planes: u32, plane_parameters: *const Plane) -> HRESU
         // will write runs behind that flight, and nothing is settled here.
         release_held_now(false);
     }
-    // shortcut: what a queue still holds at a present runs now, whatever
-    // its fence: a wait is not kept across frames.
+    // The legacy force path may skip waits on other queue segments, but
+    // cannot do so on a segment that contains or has executed a remap.
     #[cfg(windows)]
     if !sent_behind {
         release_held(forces());
     }
+    // Check again if a remap arrived while the ordinary path drained queues.
     #[cfg(windows)]
-    crate::framelog::add(crate::framelog::T::PresentLineUs, presenting.elapsed().as_micros() as u64);
-    let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1;
+    let sent_behind = sent_behind || send_behind(this, resource, frame, false);
     #[cfg(windows)]
-    if sent_behind && PRESENTS_BEHIND.load(Ordering::Relaxed).is_multiple_of(512) {
-        tracing::info!(
-            frame,
-            behind = PRESENTS_BEHIND.load(Ordering::Relaxed),
-            "presents sent behind their queue's line so far (VICTORY_ASYNC_PRESENT=1); the others ran the old way"
-        );
-    }
+    crate::framelog::add(crate::framelog::T::PresentLineUs, presenting.elapsed().as_micros() as u64);
     if frame.is_power_of_two() {
         let (draws, dispatches) = crate::list::take_counts();
         #[cfg(windows)]
@@ -1391,13 +1503,6 @@ fn present_now(this: This, planes: u32, plane_parameters: *const Plane) -> HRESU
     }
     #[cfg(windows)]
     if !sent_behind
-        && planes > 0
-        // SAFETY: the title passes `planes` plane descriptions.
-        && let Some(plane) = unsafe { plane_parameters.as_ref() }
-        && plane.count > 0
-        && !plane.resources.is_null()
-        // SAFETY: the plane lists `count` resources.
-        && let resource = unsafe { *plane.resources }
         && let Some(texture) = crate::resource::host_resource(resource)
         && let Some(host) = crate::host::host()
     {
@@ -1453,6 +1558,7 @@ fn blinks(frame: u64, resource: This, state: u32, shown: Option<bool>) {
 /// `start` on, 1 pool page `start` each, 2 unmapped, 3 left as they are)
 /// and how many.
 #[repr(C)]
+#[derive(Clone, Copy)]
 pub(crate) struct PageRange {
     kind: u32,
     start: u32,
@@ -1470,14 +1576,80 @@ pub(crate) struct PageBatch {
 /// Bytes per mapped page.
 const PAGE: u64 = 64 << 10;
 
+#[derive(Clone, Copy)]
+struct PagePool {
+    map: crate::resource::PageMapper,
+    base: u64,
+    pages: u32,
+}
+
+impl PagePool {
+    fn apply<'a>(self, batches: impl Iterator<Item = (u64, &'a [PageRange])>) {
+        let mut ok = true;
+        for (mut at, ranges) in batches {
+            for r in ranges {
+                if r.count == 0 {
+                    continue;
+                }
+                let len = u64::from(r.count) * PAGE;
+                let Some(end) = at.checked_add(len) else {
+                    ok = false;
+                    break;
+                };
+                let source = |count: u32| {
+                    let end = r.start.checked_add(count).filter(|&e| e <= self.pages)?;
+                    self.base.checked_add(u64::from(end) * PAGE)?;
+                    self.base.checked_add(u64::from(r.start) * PAGE).filter(|&at| at != 0)
+                };
+                let map = self.map;
+                ok &= match r.kind {
+                    0 => source(r.count).is_some_and(|p| map(at, p, len)),
+                    1 => source(1).is_some_and(|p| (0..u64::from(r.count)).all(|k| map(at + k * PAGE, p, PAGE))),
+                    2 => map(at, 0, len),
+                    3 => true,
+                    _ => false,
+                };
+                at = end;
+            }
+        }
+        if !ok {
+            static ONCE: std::sync::Once = std::sync::Once::new();
+            ONCE.call_once(|| tracing::warn!(pool = format_args!("{:#x}", self.base), "a page mapping failed"));
+        }
+    }
+}
+
+#[cfg(windows)]
+struct QueuedPageMappings {
+    pool: PagePool,
+    batches: Vec<(u64, Vec<PageRange>)>,
+}
+
+fn page_ranges(batches: &[PageBatch]) -> impl Iterator<Item = (u64, &[PageRange])> {
+    batches.iter().filter_map(|b| {
+        if b.count == 0 || b.ranges.is_null() {
+            return None;
+        }
+        // SAFETY: only used during the call, which borrows the title's ranges.
+        let ranges = unsafe { std::slice::from_raw_parts(b.ranges, b.count as usize) };
+        Some((b.destination, ranges))
+    })
+}
+
+#[cfg(windows)]
+fn mark_waiting(this: This) {
+    let mut waiting = lock(&WAITING);
+    if !waiting.iter().any(|q| q.0 == this as usize) {
+        waiting.push(QueueRef::new(this));
+    }
+}
+
 /// `CopyPageMappingsBatchX(count, batches, pool, pool pages, flags)`: maps
 /// pages of a pool (memory the title mapped physical pages into) at the
-/// batches' addresses. The title streams textures into pool pages
-/// and maps them into its tiled heap this way (title+0xf2c470, ranges of
-/// one constant page or of unmapped pages). Done at once: every earlier
-/// submission has run.
+/// batches' addresses. This is a queue operation: earlier work, including
+/// copy-back into title addresses, must finish before the addresses change.
 extern "system" fn copy_page_mappings(
-    _: This,
+    this: This,
     count: u32,
     batches: *const PageBatch,
     pool: u64,
@@ -1487,39 +1659,52 @@ extern "system" fn copy_page_mappings(
     let Some(map) = crate::resource::page_mapper() else {
         return E_INVALIDARG;
     };
-    if batches.is_null() && count > 0 {
+    if count == 0 {
+        return S_OK;
+    }
+    if batches.is_null() {
         return E_INVALIDARG;
     }
-    let batches = (count > 0).then(|| {
-        // SAFETY: the title passes `count` batches.
-        unsafe { std::slice::from_raw_parts(batches, count as usize) }
-    });
-    let mut ok = true;
-    for b in batches.into_iter().flatten() {
-        if b.ranges.is_null() {
-            continue;
+    // SAFETY: the title passes `count` batches, valid for this call.
+    let batches = unsafe { std::slice::from_raw_parts(batches, count as usize) };
+    let pool = PagePool { map, base: pool, pages: pool_pages };
+    #[cfg(windows)]
+    if !this.is_null() {
+        let line = &queue(this).held;
+        let mut held = lock(line);
+        held.ordered = true;
+        if !held.is_empty() {
+            // The caller's batch and range arrays need not outlive this call.
+            held.push(Held::MapPages(QueuedPageMappings {
+                pool,
+                batches: page_ranges(batches).map(|(at, ranges)| (at, ranges.to_vec())).collect(),
+            }));
+            mark_waiting(this);
+            drop(held);
+            release_held(false);
+            return S_OK;
         }
-        // SAFETY: each batch holds `count` ranges.
-        let ranges = unsafe { std::slice::from_raw_parts(b.ranges, b.count as usize) };
-        let mut at = b.destination;
-        for r in ranges {
-            let len = u64::from(r.count) * PAGE;
-            let inside = |pages: u32| r.start.checked_add(pages).is_some_and(|e| e <= pool_pages);
-            let source = pool + u64::from(r.start) * PAGE;
-            ok &= match r.kind {
-                0 if inside(r.count) => map(at, source, len),
-                1 if inside(1) => (0..u64::from(r.count)).all(|k| map(at + k * PAGE, source, PAGE)),
-                2 => map(at, 0, len),
-                3 => true,
-                _ => false,
-            };
-            at += len;
+        // No older logical work is held. Run inline without copying the
+        // descriptions, but don't let a new submission or signal pass us.
+        held.push(Held::Running);
+        drop(held);
+        crate::host::with_page_mapping(|| pool.apply(page_ranges(batches)));
+        let mut held = lock(line);
+        held.remove(0);
+        let more = !held.is_empty();
+        if more {
+            mark_waiting(this);
+        } else {
+            held.unregister_if_drained(this as usize);
         }
+        drop(held);
+        if more {
+            release_held(false);
+        }
+        return S_OK;
     }
-    if !ok {
-        static ONCE: std::sync::Once = std::sync::Once::new();
-        ONCE.call_once(|| tracing::warn!(pool = format_args!("{pool:#x}"), "a page mapping failed"));
-    }
+    let _ = this;
+    pool.apply(page_ranges(batches));
     S_OK
 }
 
@@ -1580,6 +1765,127 @@ static NEWER_FUNCTIONS: Table<36> = Table(queue_table(true));
 mod tests {
     use super::*;
 
+    #[cfg(windows)]
+    fn new_test_queue() -> QueueRef {
+        let null = std::ptr::null();
+        let mut q = null;
+        let desc = QueueDesc { kind: 0, priority: 0, flags: 0, nodes: 0 };
+        assert_eq!(create(null, &desc, &QUEUE_IIDS[0], &mut q), S_OK);
+        QueueRef(q as usize)
+    }
+
+    #[cfg(windows)]
+    fn new_test_fence() -> (This, FenceRef) {
+        let null = std::ptr::null();
+        let mut fence = null;
+        assert_eq!(crate::fence::create(null, 0, 0, &crate::fence::FENCE_IIDS[0], &mut fence), S_OK);
+        let owner = FenceRef::new(fence);
+        let release = slot::<extern "system" fn(This) -> u32>(fence, 0x10);
+        assert_eq!(release(fence), 1);
+        (fence, owner)
+    }
+
+    #[cfg(windows)]
+    #[test]
+    fn remap_orders_presents_even_without_async_present() {
+        // Real emulated queue waits and dispatch loop; an observer in place
+        // of the window copy records when it is allowed to run.
+        static REACHED: AtomicU64 = AtomicU64::new(0);
+        fn map(to: u64, from: u64, len: u64) -> bool {
+            assert_eq!((to, from, len), (2 * PAGE, PAGE, PAGE));
+            assert_eq!(REACHED.swap(1, Ordering::SeqCst), 0);
+            true
+        }
+        let owner = new_test_queue();
+        let q = owner.0 as This;
+        let (before, _before_owner) = new_test_fence();
+        let (after, _after_owner) = new_test_fence();
+        let (producer, _producer_owner) = new_test_fence();
+        {
+            let mut line = lock(&queue(q).held);
+            line.ordered = true;
+            line.push(Held::Wait(FenceRef::new(before), 1));
+            line.push(Held::MapPages(QueuedPageMappings {
+                pool: PagePool { map, base: PAGE, pages: 1 },
+                batches: vec![(2 * PAGE, vec![PageRange { kind: 0, start: 0, count: 1 }])],
+            }));
+            line.push(Held::Wait(FenceRef::new(after), 1));
+            line.push(Held::Signal(FenceRef::new(producer), 1));
+            mark_waiting(q);
+        }
+        release_held_now(true);
+        assert_eq!(REACHED.load(Ordering::SeqCst), 0, "the first wait must not be forced");
+        crate::fence::set(before, 1);
+        release_held_now(true);
+        assert_eq!(REACHED.load(Ordering::SeqCst), 1, "only the remap has run");
+        let producer = FenceRef::new(producer);
+        // The first present arrives after the remap, while the dependent
+        // work is still blocked. A queued map marker alone is not enough.
+        assert!(enqueue_present(q, false, || Some(PresentSource::Observe(Box::new(move || {
+            assert_eq!(crate::fence::completed(producer.as_ptr()), 1);
+            assert_eq!(REACHED.fetch_add(1, Ordering::SeqCst), 1);
+        })))));
+        assert!(enqueue_present(q, false, || Some(PresentSource::Observe(Box::new(|| {
+            assert_eq!(REACHED.fetch_add(1, Ordering::SeqCst), 2);
+        })))));
+        release_held_now(true);
+        assert_eq!(REACHED.load(Ordering::SeqCst), 1, "neither present can force the second wait");
+        crate::fence::set(after, 1);
+        release_held_now(true);
+        assert_eq!(REACHED.load(Ordering::SeqCst), 3);
+        assert!(lock(&queue(q).held).is_empty());
+        assert!(!lock(&queue(q).held).ordered);
+    }
+
+    #[cfg(windows)]
+    #[test]
+    fn present_cannot_pass_an_inline_mapping_marker() {
+        let owner = new_test_queue();
+        let q = owner.0 as This;
+        let order = std::sync::Arc::new(AtomicU64::new(0));
+        {
+            let mut line = lock(&queue(q).held);
+            line.ordered = true;
+            line.push(Held::Running);
+        }
+        let observed = order.clone();
+        assert!(enqueue_present(q, false, || Some(PresentSource::Observe(Box::new(move || {
+            assert_eq!(observed.swap(2, Ordering::SeqCst), 1);
+        })))));
+        release_held_now(true);
+        assert_eq!(order.load(Ordering::SeqCst), 0);
+        {
+            let mut line = lock(&queue(q).held);
+            assert!(matches!(line.remove(0), Held::Running));
+            order.store(1, Ordering::SeqCst);
+        }
+        release_held_now(false);
+        assert_eq!(order.load(Ordering::SeqCst), 2);
+    }
+
+    #[cfg(windows)]
+    #[test]
+    fn joined_cleanup_pins_queue_after_client_and_snapshot_release() {
+        let client = new_test_queue();
+        let q = client.0 as This;
+        let mut joined = Joined::default();
+        {
+            let snapshot = QueueRef::new(q);
+            let mut line = lock(&queue(q).held);
+            mark_waiting(q);
+            joined.mark(&snapshot, &mut line);
+            joined.mark(&snapshot, &mut line);
+            assert_eq!(line.len(), 1, "one mark and owner per queue");
+        }
+        std::mem::forget(client);
+        // No test/client/snapshot reference is left when cleanup runs;
+        // WAITING and Joined must each have one and no more.
+        assert_eq!(release(q), 2);
+        send_joined(&mut joined);
+        assert!(!lock(&WAITING).iter().any(|w| w.0 == q as usize));
+        assert!(joined.marked.is_empty());
+    }
+
     #[cfg(windows)]
     #[test]
     fn joined_parts_keep_their_lists_and_their_order() {
**@⁠NotADonky43** on GitHub · 2026-11-25 21:21 UTC · [original](https://github.com/fxceless/victory-fork/issues/1131#issuecomment-7174976832) Follow-up: the source-only candidate now fixes the two issues identified in the first review. - A queue segment containing a page remap keeps its ordering until it drains. A resource-backed present waits behind that segment, even if the optional async-present mode is off or the remap ran inline. The legacy force-present path cannot skip either a wait before the remap or a dependent wait after it. - Joined submissions own their queue marks until after cleanup drops the queue mutex guard. A caller releasing its queue and fence references cannot free objects that the joined submission still needs. A deferred present retains its source through the GPU copy. First host initialization also cannot race a pre-device remap. The tests separate queue/presentation ordering from real GPU writes. The queue test uses an observer at the host-present boundary (not a desktop or game display check). The native D3D12 fixture releases both client queues and its copy fence with work still pending, then verifies the old backing, replacement backing, and later GPU read. This is a correctness patch, not a game visual, stability, or FPS claim. Remaps can still wait on the shared host submission lane, and existing partial-map error handling is unchanged. ### Applying the source patches Start from `085ee7c4c3d1dfaed41d683fa9f465a6f9dac8c3` or `c36971b213770e48f513f0d6e3ced3f1f65a32b2`. Apply the standalone [Windows placeholder-boundary patch from #824](https://git.gtahub.st/github/fxceless--victory-fork/pulls/824) first, then the runtime/queue diff below, then the fixture diff in the next comment. Both diffs are against that prerequisite; no game files or assets are needed. **Verification:** On `c36971b` the 8 queue tests, 14 XMem tests, and real D3D12 readback on the RTX 5070 Ti passed. The GPU fixture passed with synchronous and deferred execution and with joined submissions, both with and without relay copy-back. GPU-based validation was on. The optimized build succeeded. The same patch had 588 workspace tests pass on `085ee7c`, with the independently failing baseline WARP budget test excluded. No game launch or visual claim. <details><summary>Part 1 of 2 — runtime and queue regressions</summary> ```diff diff --git a/crates/victory-gpu/src/fence.rs b/crates/victory-gpu/src/fence.rs index b820335..4486b08 100644 --- a/crates/victory-gpu/src/fence.rs +++ b/crates/victory-gpu/src/fence.rs @@ -35,6 +35,29 @@ struct Fence { asked: Mutex<Vec<pace::Asked>>, } +/// Keep a console fence alive while a queue or a late host flight names it. +#[cfg(windows)] +pub(crate) struct FenceRef(usize); + +#[cfg(windows)] +impl FenceRef { + pub(crate) fn new(this: This) -> Self { + object::add_ref(this); + Self(this as usize) + } + + pub(crate) fn as_ptr(&self) -> This { + self.0 as This + } +} + +#[cfg(windows)] +impl Drop for FenceRef { + fn drop(&mut self) { + object::release_boxed::<Fence>(self.as_ptr()); + } +} + fn fence<'a>(this: This) -> &'a Fence { // SAFETY: called from fence methods only. unsafe { &*this.cast::<Fence>() } diff --git a/crates/victory-gpu/src/framelog.rs b/crates/victory-gpu/src/framelog.rs index 7806ab6..268fcc4 100644 --- a/crates/victory-gpu/src/framelog.rs +++ b/crates/victory-gpu/src/framelog.rs @@ -63,6 +63,8 @@ pub enum T { Remaps, RemapUs, RemapWaitUs, + /// Queue page maps waiting for host submission and deferred copy-back. + MapQueueWaitUs, /// Texture refreshes on every thread, and of them the wait for title /// memory to hold still; uploads recorded. RefreshUs, @@ -412,7 +414,7 @@ fn text(f: &Frame) -> String { send-and-hash lists {:.1} ms in {:.0}, our compare lists {:.1} ms in {:.0}, all other lists {:.1} ms in {:.0} | \ recording, all threads: {:.1} ms in {:.0} calls; all submit calls {:.1} ms | textures: refresh {:.1} ms ({:.1} waiting for memory to hold \ still), {:.0} uploads, staging {:.0} made {:.0} reused | remapping: {:.0} calls {:.1} ms ({:.1} waiting for \ - readers) | pipelines: {:.0} made, {:.0} loaded, {:.1} ms waited | disk: {:.0} reads {:.1} MB {:.1} worker ms | \ + readers), {:.1} ms queue/copy-back wait | pipelines: {:.0} made, {:.0} loaded, {:.1} ms waited | disk: {:.0} reads {:.1} MB {:.1} worker ms | \ faults: {:.0} page, {:.0} guard | process: {:.0} user {:.0} kernel ms | pacing, all threads {:.1} ms | {:.0} \ draws | {:.0} MB free | found on a slow core: the render thread {:.0} of {:.0} looks, the submit thread {:.0} of {:.0}, recording threads {:.0} of {:.0}", f.us / 1e3, @@ -454,6 +456,7 @@ fn text(f: &Frame) -> String { t(T::Remaps), ms(T::RemapUs), ms(T::RemapWaitUs), + ms(T::MapQueueWaitUs), s(S_PIPELINES_MADE), s(S_PIPELINES_LOADED), ms(T::PipelineWaitUs), diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index bc4a64a..f4c1b6e 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -577,10 +577,17 @@ pub(crate) fn fail(what: std::fmt::Arguments) -> ! { } } +static HOST: OnceLock<Option<Host>> = OnceLock::new(); +/// Serialize the first host publication with mappings made before it exists. +static HOST_INIT: Mutex<()> = Mutex::new(()); + /// The host GPU, created on first use; `None` without one (a run then /// behaves as before: nothing executes). pub(crate) fn host() -> Option<&'static Host> { - static HOST: OnceLock<Option<Host>> = OnceLock::new(); + if let Some(host) = HOST.get() { + return host.as_ref(); + } + let _initializing = HOST_INIT.lock().unwrap_or_else(|e| e.into_inner()); HOST.get_or_init(|| match create() { Ok(host) => Some(host), Err(e) => { @@ -2475,7 +2482,7 @@ enum Late { /// A bottom-of-pipe write of the flight before it: address, what, bytes. Write(usize, crate::queue::Written, usize), /// A fence (its address) signalled behind the flights before it. - Signal(usize, u64), + Signal(crate::fence::FenceRef, u64), } struct Line { @@ -3066,7 +3073,7 @@ fn stale_under_flights(runs: &[&HostList]) -> bool { /// A fence signal on a queue ([`late`]): goes behind the flights in the /// air, if there are any, and is set when they are settled. Whether it /// did; if not the caller sets the fence now. -pub(crate) fn late_signal(fence: usize, value: u64) -> bool { +pub(crate) fn late_signal(fence: crate::object::This, value: u64) -> bool { if !late() { return false; } @@ -3074,7 +3081,7 @@ pub(crate) fn late_signal(fence: usize, value: u64) -> bool { if line.line.is_empty() && !line.settling { return false; } - line.line.push(Late::Signal(fence, value)); + line.line.push(Late::Signal(crate::fence::FenceRef::new(fence), value)); LATE_STATS[14].fetch_add(1, Ordering::Relaxed); drop(line); // A signal alone (behind a settle under way) has no flight to wake @@ -3170,6 +3177,29 @@ pub(crate) fn settle_for_fence() { settle_now(WHY_FENCE); } +/// Change title memory after already submitted flights and their deferred +/// writes. There is one host flight line, shared by the emulated queues. +/// Keep another submission from preparing new reads between the settle +/// and the map. The closure may acquire title-memory locks, not submit. +pub(crate) fn with_page_mapping<T>(map: impl FnOnce() -> T) -> T { + let started = std::time::Instant::now(); + // If the host doesn't exist yet, keep it from being published until + // this map finishes. This doesn't trigger GPU initialization for a map. + let initializing = HOST.get().is_none().then(|| HOST_INIT.lock().unwrap_or_else(|e| e.into_inner())); + let host = HOST.get(); + let initializing = if host.is_some() { drop(initializing); None } else { initializing }; + let submitted = host.and_then(Option::as_ref).map(|host| { + let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + host.settle(&mut submitted, WHY_SYNC); + submitted + }); + crate::framelog::add(crate::framelog::T::MapQueueWaitUs, started.elapsed().as_micros() as u64); + let result = map(); + drop(submitted); + drop(initializing); + result +} + /// Resets the host lists of settled flights and keeps them for reuse, as /// a queue does for the lists it ran (`crate::list::recycle`). fn land() { @@ -4937,7 +4967,7 @@ impl Host { landed.push((flight.lists, flight.order)); } Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes), - Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value), + Late::Signal(fence, value) => crate::fence::set(fence.as_ptr(), value), } } if last > 0 { @@ -5363,7 +5393,7 @@ impl Host { landed.push((flight.lists, flight.order)); } Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes), - Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value), + Late::Signal(fence, value) => crate::fence::set(fence.as_ptr(), value), } } if last > 0 { @@ -8013,6 +8043,9 @@ impl Host { /// shown; else, in diagnostics builds, whether the frame was black. pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option<bool> { let showing = std::time::Instant::now(); + // Draining may itself present a queued frame. Do it before taking + // the presenter mutex, never from the synchronous copy below. + crate::queue::before_sync(); let shown = self.present_now(texture, state, frame); crate::framelog::add(crate::framelog::T::PresentShowUs, showing.elapsed().as_micros() as u64); shown @@ -8093,6 +8126,11 @@ impl Host { None => &p.copy, }; copy.reset(); + // A queued present may be the title texture's last owner. A + // submit-ahead copy still refers to it after this call returns. + if slot.is_some() { + copy.keep(texture); + } let list = &copy.list; list.ResourceBarrier(&[ transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE), @@ -8128,7 +8166,9 @@ impl Host { let flown = self.execute_own(copy); p.ahead[i].1 = flown; } - None => self.execute(&[copy]), + None => { + self.submit(&[copy], false); + } } #[cfg(feature = "diagnostics")] if let Some((buffer, footprint)) = capture { diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index a924511..070f194 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -6,6 +6,8 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, QUEUE, S_OK, Table, This, guid}; use crate::resource::PAGEABLE_IIDS; +#[cfg(windows)] +use crate::fence::FenceRef; const QUEUE_IIDS: [Iid; 4] = [ guid( @@ -37,31 +39,89 @@ struct Queue { /// What the queue was given after a wait for a fence that had not been /// reached, in order; it runs when the fence gets there. #[cfg(windows)] - held: std::sync::Mutex<Vec<Held>>, + held: std::sync::Mutex<QueueLine>, } const _: () = assert!(std::mem::offset_of!(Queue, kind) == 0x10); +#[cfg(windows)] +#[derive(Default)] +struct QueueLine { + items: Vec<Held>, + // A pending remap commits this segment to real queue ordering. Keep the + // flag until the line drains, including after the remap has executed: + // a dependent run may still be waiting when its present is called. + ordered: bool, +} + +#[cfg(windows)] +impl std::ops::Deref for QueueLine { + type Target = Vec<Held>; + + fn deref(&self) -> &Self::Target { + &self.items + } +} + +#[cfg(windows)] +impl std::ops::DerefMut for QueueLine { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.items + } +} + +#[cfg(windows)] +impl QueueLine { + fn unregister_if_drained(&mut self, queue: usize) { + if self.is_empty() { + self.ordered = false; + lock(&WAITING).retain(|w| w.0 != queue); + } + } +} + /// One thing a waiting queue holds back. #[cfg(windows)] enum Held { - /// The queue waits for the fence (its address) to reach the value. - Wait(usize, u64), + /// The queue waits for the fence to reach the value. + Wait(FenceRef, u64), /// A list of the next submission waits for a memory value. Value(crate::list::ValueWait), /// A submission: the lists' host sides, taken from the title's lists /// (which it may reset meanwhile), and the order they run in. Run(Vec<crate::list::Detached>, Vec<usize>), + /// A page mapping change, after preceding submissions and their copy-back. + MapPages(QueuedPageMappings), /// A signal of the queue's, due after what it holds before it. - Signal(usize, u64), + Signal(FenceRef, u64), /// With [`behind`]: the submission at the head of the line is being /// prepared and sent by our thread, with the line unlocked, so the /// title can add to its end meanwhile; whatever is added stays behind /// this (the line is not empty), signals too. Running, - /// With [`present_behind`]: the title's present of a frame, due after - /// what the queue holds before it: the host texture shown, the state - /// the title's lists leave it in, and the frame's number. - Present(windows::Win32::Graphics::Direct3D12::ID3D12Resource, u32, u64), + /// A frame shown after the work already admitted to this queue. + Present(PresentSource), +} + +#[cfg(windows)] +enum PresentSource { + Texture(std::sync::Arc<crate::resource::HostTexture>, u32, u64), + #[cfg(test)] + Observe(Box<dyn FnOnce() + Send>), +} + +#[cfg(windows)] +impl PresentSource { + fn show(self) { + match self { + Self::Texture(texture, state, frame) => { + if let Some(host) = crate::host::host() { + let _ = host.present(&texture.texture, state, frame); + } + } + #[cfg(test)] + Self::Observe(observe) => observe(), + } + } } /// Presents that are in a queue's line and have not run ([`Held::Present`]). @@ -89,7 +149,8 @@ static PRESENTS_HELD: AtomicU64 = AtomicU64::new(0); /// before it still in a line runs the old way (the lines first, then /// itself), and so does a frame that is saved or listed, and a present /// that finds its queue's line empty. A wait nothing ever meets is -/// therefore still forced, by the present after it. +/// therefore still forced, by the present after it, except across ordered +/// mappings. These presents must queue regardless of the experiment switch. /// /// What it assumes, beyond what [`behind`] does: title memory a submission /// reads stays as it was until the submission's fence is signalled, also @@ -132,46 +193,74 @@ fn present_behind() -> bool { } } -/// With [`present_behind`]: puts the present of the next frame behind what -/// the queue `this` holds. False if it has to run the old way. +/// Optional pipelining never overrides a mapping's ordering requirement. +#[cfg(windows)] +fn present_admission(line: &QueueLine, opportunistic: bool) -> Option<bool> { + if line.ordered { + Some(true) + } else if opportunistic && !line.is_empty() && PRESENTS_HELD.load(Ordering::Relaxed) == 0 { + Some(false) + } else { + None + } +} + +#[cfg(windows)] +fn enqueue_present(this: This, opportunistic: bool, source: impl FnOnce() -> Option<PresentSource>) -> bool { + let line = &queue(this).held; + if present_admission(&lock(line), opportunistic).is_none() { + return false; + } + // Resolving a host texture can allocate. Never do it under the line lock. + let Some(source) = source() else { return false }; + let mut held = lock(line); + let Some(ordered) = present_admission(&held, opportunistic) else { return false }; + PRESENTS_HELD.fetch_add(1, Ordering::Relaxed); + held.push(Held::Present(source)); + mark_waiting(this); + drop(held); + if !ordered { + let behind = PRESENTS_BEHIND.fetch_add(1, Ordering::Relaxed) + 1; + if behind.is_multiple_of(512) { + tracing::info!(behind, "presents sent ahead of the caller by the optional async-present mode"); + } + wake(); + } + // In synchronous mode the operation ahead of an ordered present will + // resume the line on return or when its wait is satisfied. + true +} + #[cfg(windows)] -fn send_behind(this: This, planes: u32, plane_parameters: *const Plane) -> bool { - if this.is_null() || planes == 0 || PRESENTS_HELD.load(Ordering::Relaxed) != 0 { +fn send_behind(this: This, resource: This, frame: u64, opportunistic: bool) -> bool { + if this.is_null() || resource.is_null() { return false; } - let frame = FRAMES.load(Ordering::Relaxed) + 1; - // A frame that is saved or listed is read back at once. + // Optional presents avoid synchronous captures; required ordering applies + // to those frames too. Host::present still handles their readback. #[cfg(feature = "diagnostics")] - if crate::capture::wanted(frame) || crate::capture::listed(frame) { - return false; + let opportunistic = opportunistic && !crate::capture::wanted(frame) && !crate::capture::listed(frame); + enqueue_present(this, opportunistic, || { + let texture = crate::resource::host_copy(resource)?; + let state = texture.state.load(Ordering::Relaxed); + Some(PresentSource::Texture(texture, state, frame)) + }) +} + +#[cfg(windows)] +fn present_resource(planes: u32, plane_parameters: *const Plane) -> This { + if planes == 0 { + return std::ptr::null(); } // SAFETY: the title passes `planes` plane descriptions. let Some(plane) = (unsafe { plane_parameters.as_ref() }) else { - return false; + return std::ptr::null(); }; if plane.count == 0 || plane.resources.is_null() { - return false; + return std::ptr::null(); } // SAFETY: the plane lists `count` resources. - let resource = unsafe { *plane.resources }; - let Some(texture) = crate::resource::host_resource(resource) else { - return false; - }; - // The state the lists recorded so far leave the texture in: what our - // copy finds it in when it runs behind them (looked at, not changed). - const COPY_SOURCE: u32 = 0x800; - let state = crate::resource::host_transition(resource, COPY_SOURCE).map_or(COPY_SOURCE, |(_, before)| before); - crate::resource::host_transition(resource, state); - let texture = texture.clone(); - let sent = hold(this, || { - PRESENTS_HELD.fetch_add(1, Ordering::Relaxed); - Held::Present(texture, state, frame) - }); - if sent { - PRESENTS_BEHIND.fetch_add(1, Ordering::Relaxed); - wake(); - } - sent + unsafe { *plane.resources } } /// Presents sent behind their queue's line since the start @@ -179,9 +268,35 @@ fn send_behind(this: This, planes: u32, plane_parameters: *const Plane) -> bool #[cfg(windows)] static PRESENTS_BEHIND: AtomicU64 = AtomicU64::new(0); -/// The queues that hold something (their addresses). +/// The queues that hold something, with a reference held until their line +/// is drained. The releaser also pins its snapshot before dropping the lock. +#[cfg(windows)] +static WAITING: std::sync::Mutex<Vec<QueueRef>> = std::sync::Mutex::new(Vec::new()); + +#[cfg(windows)] +struct QueueRef(usize); + +#[cfg(windows)] +impl QueueRef { + fn new(this: This) -> Self { + object::add_ref(this); + Self(this as usize) + } +} + +#[cfg(windows)] +impl Clone for QueueRef { + fn clone(&self) -> Self { + Self::new(self.0 as This) + } +} + #[cfg(windows)] -static WAITING: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new()); +impl Drop for QueueRef { + fn drop(&mut self) { + object::release_boxed::<Queue>(self.0 as This); + } +} #[cfg(windows)] fn lock<T>(mutex: &std::sync::Mutex<T>) -> std::sync::MutexGuard<'_, T> { @@ -325,10 +440,7 @@ fn submit_cut(this: This, lists: &[This]) { held.extend(waits.into_iter().map(Held::Value)); held.push(Held::Run(taken, order)); } - } - let mut waiting = lock(&WAITING); - if !waiting.contains(&(this as usize)) { - waiting.push(this as usize); + mark_waiting(this); } } // What ran may be what another queue waits for, and what was just @@ -416,11 +528,9 @@ fn submit_split(this: This, lists: &[This]) { pieces.push(Held::Run(taken, order)); from = to; } - lock(&queue(this).held).extend(pieces); - let mut waiting = lock(&WAITING); - if !waiting.contains(&(this as usize)) { - waiting.push(this as usize); - } + let mut held = lock(&queue(this).held); + held.extend(pieces); + mark_waiting(this); } // What ran may be what another queue waits for, and what was just held // may be free to run already. @@ -630,14 +740,25 @@ struct Joined { order: Vec<usize>, parts: usize, /// Signals met behind those parts: delivered when the parts are sent. - signals: Vec<(usize, u64)>, + signals: Vec<(FenceRef, u64)>, /// The queues with a part here: each has [`Held::Running`] at the /// head of its line. - marked: Vec<usize>, + marked: Vec<QueueRef>, } #[cfg(windows)] impl Joined { + fn has_mark(&self, queue: usize) -> bool { + self.marked.iter().any(|owner| owner.0 == queue) + } + + fn mark(&mut self, owner: &QueueRef, line: &mut Vec<Held>) { + if !self.has_mark(owner.0) { + line.insert(0, Held::Running); + self.marked.push(owner.clone()); + } + } + fn is_empty(&self) -> bool { self.parts == 0 } @@ -708,20 +829,19 @@ fn send_joined(joined: &mut Joined) { } // Behind what was just sent, in the order they were met. for (fence, value) in joined.signals.drain(..) { - if !crate::host::late_signal(fence, value) { - crate::fence::set(fence as This, value); + if !crate::host::late_signal(fence.as_ptr(), value) { + crate::fence::set(fence.as_ptr(), value); } } - for q in joined.marked.drain(..) { - // SAFETY: a live queue, as in the loop that marked it. - let line = unsafe { &(*(q as *const Queue)).held }; + for owner in joined.marked.drain(..) { + // `owner` pins this queue independently of the waiting registry. In + // particular the mutex must outlive removal of its registry entry. + let line = &queue(owner.0 as This).held; let mut held = lock(line); if matches!(held.first(), Some(Held::Running)) { held.remove(0); } - if held.is_empty() { - lock(&WAITING).retain(|&w| w != q); - } + held.unregister_if_drained(owner.0); } } @@ -758,18 +878,20 @@ fn release_held_now(all: bool) { loop { let queues = lock(&WAITING).clone(); let mut moved = false; - for q in queues { - // SAFETY: a live queue: one released is taken off the list. + for owner in queues { + let q = owner.0; + // SAFETY: the snapshot holds an owned reference for this visit. let line = unsafe { &(*(q as *const Queue)).held }; let mut held = lock(line); loop { // A queue with a part in `joined` has our mark at the head // of its line: what is looked at is behind the mark. - let base = usize::from(joined.marked.contains(&q)); + let base = usize::from(joined.has_mark(q)); match held.get(base) { None | Some(Held::Running) => break, - Some(&Held::Wait(fence, value)) - if !all && crate::fence::completed(fence as This) < value => + Some(Held::Wait(fence, value)) + if crate::fence::completed(fence.as_ptr()) < *value + && !may_force_queue(all, &held) => { break; } @@ -784,18 +906,21 @@ fn release_held_now(all: bool) { JOINED[4].fetch_add(1, Ordering::Relaxed); } } - Some(Held::Value(wait)) if !all && !value_met(wait) => break, - // The frame is shown behind the parts taken: they are - // sent first. - Some(Held::Present(..)) if !joined.is_empty() => break, + Some(Held::Value(wait)) + if !may_force_queue(all, &held) && !value_met(wait) => break, + // Both are boundaries for joined submissions. In + // particular no list after a remap can prepare its + // memory reads using the previous mapping. + Some(Held::Present(..) | Held::MapPages(..)) if !joined.is_empty() => break, Some(_) => {} } match held.remove(base) { - Held::Wait(..) | Held::Running => {} + Held::Wait(..) => {} + Held::Running => unreachable!("in-flight queue work cannot be removed here"), Held::Value(wait) => { // Passed at a present without being met: what the // queue stood at. - if all && !value_met(&wait) { + if may_force_queue(all, &held) && !value_met(&wait) { static SEEN: AtomicU64 = AtomicU64::new(0); if SEEN.fetch_add(1, Ordering::Relaxed) < 16 { tracing::warn!( @@ -831,10 +956,7 @@ fn release_held_now(all: bool) { if joining { // Taken, to go with the parts that follow it. // The line stays open behind our mark. - if !joined.marked.contains(&q) { - held.insert(0, Held::Running); - joined.marked.push(q); - } + joined.mark(&owner, &mut held); joined.add(lists, order); if joined.full() { drop(held); @@ -880,7 +1002,7 @@ fn release_held_now(all: bool) { crate::list::recycle(lists, &order); } } - if all { + if all && may_force_queue(all, &held) { #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::Forced, 1); static ONCE: AtomicBool = AtomicBool::new(false); @@ -891,25 +1013,24 @@ fn release_held_now(all: bool) { } } } - Held::Present(texture, state, frame) => { - let show = || { - if let Some(host) = crate::host::host() { - let _ = host.present(&texture, state, frame); - } - }; - if all { - show(); - } else { - // The line is open while the frame is shown, - // as it is while a submission is prepared. - held.insert(0, Held::Running); - drop(held); - show(); - held = lock(line); - if matches!(held.first(), Some(Held::Running)) { - held.remove(0); - } - } + Held::MapPages(work) => { + held.insert(0, Held::Running); + drop(held); + // Host flights are a shared line, not split by title + // queue. Finish prior copy-back before changing any + // backing. Do not hold a queue mutex during the wait. + crate::host::with_page_mapping(|| { + work.pool.apply(work.batches.iter().map(|(at, ranges)| (*at, ranges.as_slice()))); + }); + held = lock(line); + held.remove(0); + } + Held::Present(source) => { + held.insert(0, Held::Running); + drop(held); + source.show(); + held = lock(line); + held.remove(0); PRESENTS_HELD.fetch_sub(1, Ordering::Relaxed); } // Behind what was sent to the card and not waited @@ -918,16 +1039,14 @@ fn release_held_now(all: bool) { if !joined.is_empty() { // Behind parts not sent yet: with them. joined.signals.push((fence, value)); - } else if !crate::host::late_signal(fence, value) { - crate::fence::set(fence as This, value); + } else if !crate::host::late_signal(fence.as_ptr(), value) { + crate::fence::set(fence.as_ptr(), value); } } } moved = true; } - if held.is_empty() { - lock(&WAITING).retain(|&w| w != q); - } + held.unregister_if_drained(q); } if !moved { if joined.is_empty() { @@ -940,6 +1059,13 @@ fn release_held_now(all: bool) { } } +/// The legacy present-time escape hatch must not force commands through a +/// real wait in front of a pending mapping change (or the remap itself). +#[cfg(windows)] +fn may_force_queue(all: bool, line: &QueueLine) -> bool { + all && !line.ordered +} + /// Whether a queue may pass `wait`: memory holds the value, or, with /// submissions sent to the card without a wait (`crate::host::late`), it /// will once those in the air have run. @@ -1020,12 +1146,7 @@ extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT ) } extern "system" fn release(this: This) -> u32 { - let left = object::release_boxed::<Queue>(this); - #[cfg(windows)] - if left == 0 { - lock(&WAITING).retain(|&q| q != this as usize); - } - left + object::release_boxed::<Queue>(this) } /// Runs the lists' host lists and waits for them (decision 0007). A queue @@ -1067,11 +1188,9 @@ fn execute_now(this: This, count: u32, lists: *const This) { if SEEN.fetch_add(1, Ordering::Relaxed) < 8 { tracing::info!(kind = queue(this).kind, ?unmet, "a submission is held for a memory value"); } - lock(&queue(this).held).extend(unmet.into_iter().map(Held::Value)); - let mut waiting = lock(&WAITING); - if !waiting.contains(&(this as usize)) { - waiting.push(this as usize); - } + let mut held = lock(&queue(this).held); + held.extend(unmet.into_iter().map(Held::Value)); + mark_waiting(this); } } let kept = hold(this, || { @@ -1147,13 +1266,13 @@ extern "system" fn signal(this: This, fence: This, value: u64) -> HRESULT { crate::fence::pace::signal_called(fence as usize, value); // A queue that waits signals after what it holds. #[cfg(windows)] - if hold(this, || Held::Signal(fence as usize, value)) { + if hold(this, || Held::Signal(FenceRef::new(fence), value)) { return S_OK; } // Behind the submissions sent to the card and not waited for: the // fence is set when they are settled. #[cfg(windows)] - if crate::host::late_signal(fence as usize, value) { + if crate::host::late_signal(fence, value) { return S_OK; } let _ = this; @@ -1186,7 +1305,8 @@ extern "system" fn wait(this: This, fence: This, value: u64) -> HRESULT { let mut held = lock(&queue(this).held); let behind = !held.is_empty() || now < value; if behind && waits() { - held.push(Held::Wait(fence as usize, value)); + held.push(Held::Wait(FenceRef::new(fence), value)); + mark_waiting(this); } behind }; @@ -1203,12 +1323,6 @@ extern "system" fn wait(this: This, fence: This, value: u64) -> HRESULT { } } if behind && waits() { - { - let mut waiting = lock(&WAITING); - if !waiting.contains(&(this as usize)) { - waiting.push(this as usize); - } - } // The fence may have got there meanwhile. release_held(false); } @@ -1311,10 +1425,14 @@ fn present_now(this: This, planes: u32, plane_parameters: *const Plane) -> HRESU crate::copystat::present_begins(); #[cfg(all(windows, feature = "diagnostics"))] crate::profile::frame(); - // With `present_behind`: the frame is shown by our thread, behind what - // the queue holds, and nothing is run or waited for here. + + let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1; + // A mapping (even one running inline) and its dependent work are a + // required presentation boundary, independent of the async-present mode. + #[cfg(windows)] + let resource = present_resource(planes, plane_parameters); #[cfg(windows)] - let sent_behind = present_behind() && send_behind(this, planes, plane_parameters); + let sent_behind = send_behind(this, resource, frame, present_behind()); #[cfg(not(windows))] let _ = this; // Submissions sent to the card and not waited for are settled first, @@ -1335,23 +1453,17 @@ fn present_now(this: This, planes: u32, plane_parameters: *const Plane) -> HRESU // will write runs behind that flight, and nothing is settled here. release_held_now(false); } - // shortcut: what a queue still holds at a present runs now, whatever - // its fence: a wait is not kept across frames. + // The legacy force path may skip waits on other queue segments, but + // cannot do so on a segment that contains or has executed a remap. #[cfg(windows)] if !sent_behind { release_held(forces()); } + // Check again if a remap arrived while the ordinary path drained queues. #[cfg(windows)] - crate::framelog::add(crate::framelog::T::PresentLineUs, presenting.elapsed().as_micros() as u64); - let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1; + let sent_behind = sent_behind || send_behind(this, resource, frame, false); #[cfg(windows)] - if sent_behind && PRESENTS_BEHIND.load(Ordering::Relaxed).is_multiple_of(512) { - tracing::info!( - frame, - behind = PRESENTS_BEHIND.load(Ordering::Relaxed), - "presents sent behind their queue's line so far (VICTORY_ASYNC_PRESENT=1); the others ran the old way" - ); - } + crate::framelog::add(crate::framelog::T::PresentLineUs, presenting.elapsed().as_micros() as u64); if frame.is_power_of_two() { let (draws, dispatches) = crate::list::take_counts(); #[cfg(windows)] @@ -1391,13 +1503,6 @@ fn present_now(this: This, planes: u32, plane_parameters: *const Plane) -> HRESU } #[cfg(windows)] if !sent_behind - && planes > 0 - // SAFETY: the title passes `planes` plane descriptions. - && let Some(plane) = unsafe { plane_parameters.as_ref() } - && plane.count > 0 - && !plane.resources.is_null() - // SAFETY: the plane lists `count` resources. - && let resource = unsafe { *plane.resources } && let Some(texture) = crate::resource::host_resource(resource) && let Some(host) = crate::host::host() { @@ -1453,6 +1558,7 @@ fn blinks(frame: u64, resource: This, state: u32, shown: Option<bool>) { /// `start` on, 1 pool page `start` each, 2 unmapped, 3 left as they are) /// and how many. #[repr(C)] +#[derive(Clone, Copy)] pub(crate) struct PageRange { kind: u32, start: u32, @@ -1470,14 +1576,80 @@ pub(crate) struct PageBatch { /// Bytes per mapped page. const PAGE: u64 = 64 << 10; +#[derive(Clone, Copy)] +struct PagePool { + map: crate::resource::PageMapper, + base: u64, + pages: u32, +} + +impl PagePool { + fn apply<'a>(self, batches: impl Iterator<Item = (u64, &'a [PageRange])>) { + let mut ok = true; + for (mut at, ranges) in batches { + for r in ranges { + if r.count == 0 { + continue; + } + let len = u64::from(r.count) * PAGE; + let Some(end) = at.checked_add(len) else { + ok = false; + break; + }; + let source = |count: u32| { + let end = r.start.checked_add(count).filter(|&e| e <= self.pages)?; + self.base.checked_add(u64::from(end) * PAGE)?; + self.base.checked_add(u64::from(r.start) * PAGE).filter(|&at| at != 0) + }; + let map = self.map; + ok &= match r.kind { + 0 => source(r.count).is_some_and(|p| map(at, p, len)), + 1 => source(1).is_some_and(|p| (0..u64::from(r.count)).all(|k| map(at + k * PAGE, p, PAGE))), + 2 => map(at, 0, len), + 3 => true, + _ => false, + }; + at = end; + } + } + if !ok { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!(pool = format_args!("{:#x}", self.base), "a page mapping failed")); + } + } +} + +#[cfg(windows)] +struct QueuedPageMappings { + pool: PagePool, + batches: Vec<(u64, Vec<PageRange>)>, +} + +fn page_ranges(batches: &[PageBatch]) -> impl Iterator<Item = (u64, &[PageRange])> { + batches.iter().filter_map(|b| { + if b.count == 0 || b.ranges.is_null() { + return None; + } + // SAFETY: only used during the call, which borrows the title's ranges. + let ranges = unsafe { std::slice::from_raw_parts(b.ranges, b.count as usize) }; + Some((b.destination, ranges)) + }) +} + +#[cfg(windows)] +fn mark_waiting(this: This) { + let mut waiting = lock(&WAITING); + if !waiting.iter().any(|q| q.0 == this as usize) { + waiting.push(QueueRef::new(this)); + } +} + /// `CopyPageMappingsBatchX(count, batches, pool, pool pages, flags)`: maps /// pages of a pool (memory the title mapped physical pages into) at the -/// batches' addresses. The title streams textures into pool pages -/// and maps them into its tiled heap this way (title+0xf2c470, ranges of -/// one constant page or of unmapped pages). Done at once: every earlier -/// submission has run. +/// batches' addresses. This is a queue operation: earlier work, including +/// copy-back into title addresses, must finish before the addresses change. extern "system" fn copy_page_mappings( - _: This, + this: This, count: u32, batches: *const PageBatch, pool: u64, @@ -1487,39 +1659,52 @@ extern "system" fn copy_page_mappings( let Some(map) = crate::resource::page_mapper() else { return E_INVALIDARG; }; - if batches.is_null() && count > 0 { + if count == 0 { + return S_OK; + } + if batches.is_null() { return E_INVALIDARG; } - let batches = (count > 0).then(|| { - // SAFETY: the title passes `count` batches. - unsafe { std::slice::from_raw_parts(batches, count as usize) } - }); - let mut ok = true; - for b in batches.into_iter().flatten() { - if b.ranges.is_null() { - continue; + // SAFETY: the title passes `count` batches, valid for this call. + let batches = unsafe { std::slice::from_raw_parts(batches, count as usize) }; + let pool = PagePool { map, base: pool, pages: pool_pages }; + #[cfg(windows)] + if !this.is_null() { + let line = &queue(this).held; + let mut held = lock(line); + held.ordered = true; + if !held.is_empty() { + // The caller's batch and range arrays need not outlive this call. + held.push(Held::MapPages(QueuedPageMappings { + pool, + batches: page_ranges(batches).map(|(at, ranges)| (at, ranges.to_vec())).collect(), + })); + mark_waiting(this); + drop(held); + release_held(false); + return S_OK; } - // SAFETY: each batch holds `count` ranges. - let ranges = unsafe { std::slice::from_raw_parts(b.ranges, b.count as usize) }; - let mut at = b.destination; - for r in ranges { - let len = u64::from(r.count) * PAGE; - let inside = |pages: u32| r.start.checked_add(pages).is_some_and(|e| e <= pool_pages); - let source = pool + u64::from(r.start) * PAGE; - ok &= match r.kind { - 0 if inside(r.count) => map(at, source, len), - 1 if inside(1) => (0..u64::from(r.count)).all(|k| map(at + k * PAGE, source, PAGE)), - 2 => map(at, 0, len), - 3 => true, - _ => false, - }; - at += len; + // No older logical work is held. Run inline without copying the + // descriptions, but don't let a new submission or signal pass us. + held.push(Held::Running); + drop(held); + crate::host::with_page_mapping(|| pool.apply(page_ranges(batches))); + let mut held = lock(line); + held.remove(0); + let more = !held.is_empty(); + if more { + mark_waiting(this); + } else { + held.unregister_if_drained(this as usize); } + drop(held); + if more { + release_held(false); + } + return S_OK; } - if !ok { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| tracing::warn!(pool = format_args!("{pool:#x}"), "a page mapping failed")); - } + let _ = this; + pool.apply(page_ranges(batches)); S_OK } @@ -1580,6 +1765,127 @@ static NEWER_FUNCTIONS: Table<36> = Table(queue_table(true)); mod tests { use super::*; + #[cfg(windows)] + fn new_test_queue() -> QueueRef { + let null = std::ptr::null(); + let mut q = null; + let desc = QueueDesc { kind: 0, priority: 0, flags: 0, nodes: 0 }; + assert_eq!(create(null, &desc, &QUEUE_IIDS[0], &mut q), S_OK); + QueueRef(q as usize) + } + + #[cfg(windows)] + fn new_test_fence() -> (This, FenceRef) { + let null = std::ptr::null(); + let mut fence = null; + assert_eq!(crate::fence::create(null, 0, 0, &crate::fence::FENCE_IIDS[0], &mut fence), S_OK); + let owner = FenceRef::new(fence); + let release = slot::<extern "system" fn(This) -> u32>(fence, 0x10); + assert_eq!(release(fence), 1); + (fence, owner) + } + + #[cfg(windows)] + #[test] + fn remap_orders_presents_even_without_async_present() { + // Real emulated queue waits and dispatch loop; an observer in place + // of the window copy records when it is allowed to run. + static REACHED: AtomicU64 = AtomicU64::new(0); + fn map(to: u64, from: u64, len: u64) -> bool { + assert_eq!((to, from, len), (2 * PAGE, PAGE, PAGE)); + assert_eq!(REACHED.swap(1, Ordering::SeqCst), 0); + true + } + let owner = new_test_queue(); + let q = owner.0 as This; + let (before, _before_owner) = new_test_fence(); + let (after, _after_owner) = new_test_fence(); + let (producer, _producer_owner) = new_test_fence(); + { + let mut line = lock(&queue(q).held); + line.ordered = true; + line.push(Held::Wait(FenceRef::new(before), 1)); + line.push(Held::MapPages(QueuedPageMappings { + pool: PagePool { map, base: PAGE, pages: 1 }, + batches: vec![(2 * PAGE, vec![PageRange { kind: 0, start: 0, count: 1 }])], + })); + line.push(Held::Wait(FenceRef::new(after), 1)); + line.push(Held::Signal(FenceRef::new(producer), 1)); + mark_waiting(q); + } + release_held_now(true); + assert_eq!(REACHED.load(Ordering::SeqCst), 0, "the first wait must not be forced"); + crate::fence::set(before, 1); + release_held_now(true); + assert_eq!(REACHED.load(Ordering::SeqCst), 1, "only the remap has run"); + let producer = FenceRef::new(producer); + // The first present arrives after the remap, while the dependent + // work is still blocked. A queued map marker alone is not enough. + assert!(enqueue_present(q, false, || Some(PresentSource::Observe(Box::new(move || { + assert_eq!(crate::fence::completed(producer.as_ptr()), 1); + assert_eq!(REACHED.fetch_add(1, Ordering::SeqCst), 1); + }))))); + assert!(enqueue_present(q, false, || Some(PresentSource::Observe(Box::new(|| { + assert_eq!(REACHED.fetch_add(1, Ordering::SeqCst), 2); + }))))); + release_held_now(true); + assert_eq!(REACHED.load(Ordering::SeqCst), 1, "neither present can force the second wait"); + crate::fence::set(after, 1); + release_held_now(true); + assert_eq!(REACHED.load(Ordering::SeqCst), 3); + assert!(lock(&queue(q).held).is_empty()); + assert!(!lock(&queue(q).held).ordered); + } + + #[cfg(windows)] + #[test] + fn present_cannot_pass_an_inline_mapping_marker() { + let owner = new_test_queue(); + let q = owner.0 as This; + let order = std::sync::Arc::new(AtomicU64::new(0)); + { + let mut line = lock(&queue(q).held); + line.ordered = true; + line.push(Held::Running); + } + let observed = order.clone(); + assert!(enqueue_present(q, false, || Some(PresentSource::Observe(Box::new(move || { + assert_eq!(observed.swap(2, Ordering::SeqCst), 1); + }))))); + release_held_now(true); + assert_eq!(order.load(Ordering::SeqCst), 0); + { + let mut line = lock(&queue(q).held); + assert!(matches!(line.remove(0), Held::Running)); + order.store(1, Ordering::SeqCst); + } + release_held_now(false); + assert_eq!(order.load(Ordering::SeqCst), 2); + } + + #[cfg(windows)] + #[test] + fn joined_cleanup_pins_queue_after_client_and_snapshot_release() { + let client = new_test_queue(); + let q = client.0 as This; + let mut joined = Joined::default(); + { + let snapshot = QueueRef::new(q); + let mut line = lock(&queue(q).held); + mark_waiting(q); + joined.mark(&snapshot, &mut line); + joined.mark(&snapshot, &mut line); + assert_eq!(line.len(), 1, "one mark and owner per queue"); + } + std::mem::forget(client); + // No test/client/snapshot reference is left when cleanup runs; + // WAITING and Joined must each have one and no more. + assert_eq!(release(q), 2); + send_joined(&mut joined); + assert!(!lock(&WAITING).iter().any(|w| w.0 == q as usize)); + assert!(joined.marked.is_empty()); + } + #[cfg(windows)] #[test] fn joined_parts_keep_their_lists_and_their_order() { ``` </details>
Author
Owner

@⁠NotADonky43 on GitHub · 2026-11-25 21:22 UTC · original

Source patches for this issue, part 2 of 2: the synthetic D3D12 fixture and its test dependencies. Apply after the placeholder prerequisite and the runtime/queue patch.

On Windows with a real D3D12 adapter, set VICTORY_D3D12_DEBUG=1 and VICTORY_D3D12_GBV=1, then run:

cargo test --locked -p victory-hle --lib --features diagnostics modules::xmem::tests::gpu::regrouped_pages_refresh_a_placed_texture_on_the_gpu -- --exact --ignored --test-threads=1 --nocapture

The fixture does not load a game or save images.

Part 2 of 2 — synthetic GPU fixture
diff --git a/Cargo.lock b/Cargo.lock
index 29bab8c..16fd682 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -692,6 +692,7 @@ dependencies = [
  "opus-pure",
  "tempfile",
  "tracing",
+ "tracing-subscriber",
  "victory-formats",
  "victory-gpu",
  "victory-loader",
diff --git a/crates/victory-hle/Cargo.toml b/crates/victory-hle/Cargo.toml
index a2fa943..5fe7017 100644
--- a/crates/victory-hle/Cargo.toml
+++ b/crates/victory-hle/Cargo.toml
@@ -46,6 +46,7 @@ windows-core = { workspace = true, optional = true }
 
 [dev-dependencies]
 tempfile.workspace = true
+tracing-subscriber.workspace = true
 
 [features]
 # Debugging switches (scripted keys and the like).
diff --git a/crates/victory-hle/src/modules/xmem/tests/gpu.rs b/crates/victory-hle/src/modules/xmem/tests/gpu.rs
new file mode 100644
index 0000000..3e5b854
--- /dev/null
+++ b/crates/victory-hle/src/modules/xmem/tests/gpu.rs
@@ -0,0 +1,665 @@
+//! Exercise XMem through the console queue and the real host texture upload
+//! and read-back path. No title executable or assets are needed.
+
+use std::ptr::{null, null_mut};
+use victory_gpu::object::{HRESULT, Iid, Object, S_OK, guid};
+use windows_sys::Win32::Foundation::{WAIT_FAILED, WAIT_OBJECT_0};
+use windows_sys::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
+
+use super::*;
+
+type This = *const Object;
+const FENCE: Iid = guid(
+    0x0a753dcf,
+    0xc4d8,
+    0x4b91,
+    [0xad, 0xf6, 0xbe, 0x5a, 0x60, 0xd9, 0x5a, 0x76],
+);
+const RESOURCE: Iid = guid(
+    0x696442be,
+    0xa72e,
+    0x4059,
+    [0xbc, 0x79, 0x5b, 0x5c, 0x98, 4, 0xf, 0xad],
+);
+const QUEUE: Iid = guid(
+    0x0ec870a6,
+    0x5d7e,
+    0x4c22,
+    [0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed],
+);
+const ALLOCATOR: Iid = guid(
+    0x6102dee4,
+    0xaf59,
+    0x4b09,
+    [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24],
+);
+const LIST: Iid = guid(
+    0x5b160d0f,
+    0xac1b,
+    0x4185,
+    [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55],
+);
+
+/// An owned reference to a VIctory D3D12.X object, using the base (2.4) layout.
+struct Com(This);
+
+impl Com {
+    fn new(create: impl FnOnce(*mut This) -> HRESULT) -> Self {
+        let mut object = null();
+        assert_eq!(create(&mut object), S_OK);
+        assert!(!object.is_null());
+        Self(object)
+    }
+
+    /// SAFETY: `F` and `offset` must match this object's D3D12.X method.
+    unsafe fn slot<F: Copy>(&self, offset: usize) -> F {
+        assert_eq!(size_of::<F>(), size_of::<*const ()>());
+        // SAFETY: VIctory objects begin with their function table pointer.
+        let address = unsafe { *(*self.0.cast::<*const *const ()>()).add(offset / 8) };
+        unsafe { std::mem::transmute_copy(&address) }
+    }
+
+    /// SAFETY: this object is a VIctory fence. The event must stay alive
+    /// until it signals, even if the client's fence reference is released.
+    unsafe fn arm(&self, value: u64, event: &mut Event) {
+        assert!(!event.armed);
+        let arm = unsafe { self.slot::<extern "system" fn(This, u64, HANDLE) -> HRESULT>(0x48) };
+        let result = arm(self.0, value, event.handle);
+        if result != S_OK {
+            eprintln!("arm queue fence {value} failed: {result:#x}");
+            std::process::abort();
+        }
+        event.armed = true;
+    }
+
+    /// SAFETY: this object is a VIctory fence.
+    unsafe fn wait_for(&self, value: u64) {
+        let mut event = Event::new();
+        unsafe { self.arm(value, &mut event) };
+        event.wait(&format!("queue fence {value}"));
+    }
+}
+
+/// An event may be registered on a fence even after the client releases it.
+struct Event {
+    handle: HANDLE,
+    armed: bool,
+}
+
+impl Event {
+    fn new() -> Self {
+        // SAFETY: anonymous, initially reset event with the default security.
+        let handle = unsafe { CreateEventW(null(), 0, 0, null()) };
+        if handle.is_null() {
+            eprintln!("CreateEventW failed: {}", std::io::Error::last_os_error());
+            std::process::abort();
+        }
+        Self {
+            handle,
+            armed: false,
+        }
+    }
+
+    fn wait(&mut self, label: &str) {
+        assert!(self.armed);
+        tracing::debug!(label, "waiting for fixture fence");
+        // SAFETY: this event stays alive until the fence has signalled it.
+        let result = unsafe { WaitForSingleObject(self.handle, INFINITE) };
+        if result != WAIT_OBJECT_0 {
+            if result == WAIT_FAILED {
+                eprintln!(
+                    "{label}: WaitForSingleObject failed: {}",
+                    std::io::Error::last_os_error()
+                );
+            } else {
+                eprintln!("{label}: unexpected wait result {result:#x}");
+            }
+            // A fence or worker may still own the event and fixture memory.
+            std::process::abort();
+        }
+        self.armed = false;
+        tracing::debug!(label, "fixture fence reached");
+    }
+}
+
+impl Drop for Event {
+    fn drop(&mut self) {
+        if self.armed {
+            // Unwinding must not close an event a pending fence may signal.
+            eprintln!("dropping an event still registered on a queue fence");
+            std::process::abort();
+        }
+        // SAFETY: this fixture owns the event and its registration completed.
+        if unsafe { CloseHandle(self.handle) } == 0 {
+            eprintln!("CloseHandle failed: {}", std::io::Error::last_os_error());
+            std::process::abort();
+        }
+    }
+}
+
+impl Drop for Com {
+    fn drop(&mut self) {
+        // SAFETY: all these objects use IUnknown's Release in slot 2.
+        unsafe { (self.slot::<extern "system" fn(This) -> u32>(0x10))(self.0) };
+    }
+}
+
+#[repr(C)]
+struct CopyLocation {
+    resource: This,
+    kind: u32,
+    footprint: Footprint,
+}
+
+#[repr(C)]
+struct Footprint {
+    offset: u64,
+    format: u32,
+    width: u32,
+    height: u32,
+    depth: u32,
+    row_pitch: u32,
+}
+
+#[repr(C)]
+struct PageRange {
+    kind: u32,
+    start: u32,
+    count: u32,
+}
+
+#[repr(C)]
+struct PageBatch {
+    destination: u64,
+    count: u32,
+    ranges: *const PageRange,
+}
+
+const WIDTH: u32 = 256;
+const HEIGHT: u32 = 192;
+const PITCH: u32 = WIDTH * 4;
+const BYTES: usize = (PITCH * HEIGHT) as usize;
+const _: () = assert!(BYTES == 3 * PAGE);
+
+#[test]
+#[ignore = "requires a real D3D12 device; run separately with diagnostics and the debug layer"]
+fn regrouped_pages_refresh_a_placed_texture_on_the_gpu() {
+    let log = tracing_subscriber::fmt()
+        .with_test_writer()
+        .with_ansi(false)
+        .with_max_level(tracing::Level::DEBUG)
+        .finish();
+    // Async queue and host workers run on other threads. A thread-local
+    // subscriber would hide their diagnostics from this dedicated process.
+    if let Err(error) = tracing::subscriber::set_global_default(log) {
+        eprintln!("GPU fixture could not install its tracing subscriber: {error}");
+    }
+    let original = FixturePages(allocate(3));
+    let replacement = FixturePages(allocate(4));
+    let placed = AliasWindow::new(4);
+    // At frame zero, choose an address off the guard's one-in-eight hash
+    // turn, so a later write actually has to invalidate the guard.
+    let start = usize::from((placed.base / PAGE).is_multiple_of(8));
+    let destination = placed.at(start);
+    let pool = AliasWindow::new(4);
+    let alias = AliasWindow::new(3);
+    for (pages, start) in [(&original.0, 0x10), (&replacement.0, 0x20)] {
+        for (i, id) in pages.iter().enumerate() {
+            assert!(write_physical(
+                std::slice::from_ref(id),
+                0,
+                &vec![start + i as u8; PAGE]
+            ));
+        }
+    }
+    for (i, id) in original.0.iter().enumerate() {
+        let at = placed.at(start + i);
+        assert_eq!(XMemMapPhysicalPages(at, 1, id), at);
+    }
+    assert_eq!(
+        XMemMapPhysicalPages(pool.at(0), 4, replacement.0.as_ptr()),
+        pool.at(0)
+    );
+    victory_gpu::resource::use_page_mapper(map_alias);
+
+    let dev = Com::new(|out| {
+        victory_gpu::device::create(
+            null(),
+            &victory_gpu::device::CHECKED_VERSION,
+            &victory_gpu::device::IID,
+            out,
+        )
+    });
+    // SAFETY: the signatures and offsets below are for the VIctory base
+    // D3D12.X device/queue/list/resource vtables. All descriptions and output
+    // pointers are live for the calls; Com owns each returned reference.
+    unsafe {
+        let make_queue = dev
+            .slot::<extern "system" fn(This, *const u32, *const Iid, *mut This) -> HRESULT>(0x40);
+        let queue = Com::new(|out| make_queue(dev.0, [0u32; 4].as_ptr(), &QUEUE, out));
+        let make_allocator =
+            dev.slot::<extern "system" fn(This, u32, *const Iid, *mut This) -> HRESULT>(0x48);
+        let make_list = dev.slot::<extern "system" fn(
+            This,
+            u32,
+            u32,
+            This,
+            This,
+            *const Iid,
+            *mut This,
+        ) -> HRESULT>(0x60);
+        let place = dev.slot::<extern "system" fn(
+            This,
+            u64,
+            *const u64,
+            u32,
+            *const c_void,
+            *const Iid,
+            *mut This,
+        ) -> HRESULT>(0x428);
+        let commit = dev.slot::<extern "system" fn(
+            This,
+            *const u32,
+            u32,
+            *const u64,
+            u32,
+            *const c_void,
+            *const Iid,
+            *mut This,
+        ) -> HRESULT>(0xd8);
+        // Seven u64s give the console ResourceDesc its 8-byte alignment.
+        // 2D, RGBA8, linear, one mip/layer/sample; buffer with a linear row layout.
+        let desc = [
+            3,
+            0,
+            u64::from(WIDTH),
+            u64::from(HEIGHT) | (1 << 32) | (1 << 48),
+            28 | (1 << 32),
+            1 << 32,
+            0,
+        ];
+        let buffer = [
+            1,
+            0,
+            BYTES as u64,
+            1 | (1 << 32) | (1 << 48),
+            1 << 32,
+            1 << 32,
+            0,
+        ];
+        let image = Com::new(|out| {
+            place(
+                dev.0,
+                destination as u64,
+                desc.as_ptr(),
+                0,
+                null(),
+                &RESOURCE,
+                out,
+            )
+        });
+        let readback = Com::new(|out| {
+            commit(
+                dev.0,
+                [1, 0, 0, 1, 1].as_ptr(),
+                0,
+                buffer.as_ptr(),
+                0,
+                null(),
+                &RESOURCE,
+                out,
+            )
+        });
+        let map = readback
+            .slot::<extern "system" fn(This, u32, *const c_void, *mut *mut u8) -> HRESULT>(0x40);
+        let mut data = null_mut();
+        assert_eq!(map(readback.0, 0, null(), &mut data), S_OK);
+        assert!(!data.is_null());
+        let to = CopyLocation {
+            resource: readback.0,
+            kind: 1,
+            footprint: Footprint {
+                offset: 0,
+                format: 28,
+                width: WIDTH,
+                height: HEIGHT,
+                depth: 1,
+                row_pitch: PITCH,
+            },
+        };
+        let from = CopyLocation {
+            resource: image.0,
+            kind: 0,
+            footprint: Footprint {
+                offset: 0,
+                ..to.footprint
+            },
+        };
+        let make_fence =
+            dev.slot::<extern "system" fn(This, u64, u32, *const Iid, *mut This) -> HRESULT>(0x120);
+        let execute = queue.slot::<extern "system" fn(This, u32, *const This)>(0x50);
+        let signal = queue.slot::<extern "system" fn(This, This, u64) -> HRESULT>(0x70);
+        let check = |label: &str, values: [u8; 3], pending: Option<[u8; 3]>| {
+            let allocator = Com::new(|out| make_allocator(dev.0, 0, &ALLOCATOR, out));
+            let list = Com::new(|out| make_list(dev.0, 0, 0, allocator.0, null(), &LIST, out));
+            let fence = Com::new(|out| make_fence(dev.0, 0, 0, &FENCE, out));
+            let copy = list.slot::<extern "system" fn(
+                This,
+                *const CopyLocation,
+                u32,
+                u32,
+                u32,
+                *const CopyLocation,
+                *const c_void,
+            )>(0x80);
+            let close = list.slot::<extern "system" fn(This) -> HRESULT>(0x48);
+            data.write_bytes(0xd3, BYTES); // fail if no GPU copy reached the buffer
+            copy(list.0, &to, 0, 0, 0, &from, null());
+            assert_eq!(close(list.0), S_OK);
+            // The default queue may submit asynchronously. Wait for its
+            // signal, including the deferred readback, before checking bytes.
+            execute(queue.0, 1, &list.0);
+            assert_eq!(signal(queue.0, fence.0, 1), S_OK, "{label}: signal queued");
+            fence.wait_for(1);
+            let bytes = std::slice::from_raw_parts(data, BYTES);
+            if pending.is_some_and(|prior| {
+                bytes
+                    .chunks_exact(PAGE)
+                    .zip(prior)
+                    .all(|(page, value)| page.iter().all(|&b| b == value))
+            }) {
+                eprintln!("{label}: staging change will upload on the next list");
+                return;
+            }
+            for (i, (page, value)) in bytes.chunks_exact(PAGE).zip(values).enumerate() {
+                let wrong = page.iter().position(|&byte| byte != value);
+                assert_eq!(
+                    wrong,
+                    None,
+                    "{label}, page {i}; first wrong value {:?}, expected {value:#x}",
+                    wrong.map(|at| page[at])
+                );
+            }
+        };
+        check("initial", [0x10, 0x11, 0x12], None);
+        assert_eq!(
+            XMemMapPhysicalPages(destination, 3, replacement.0.as_ptr()),
+            destination
+        );
+        check("regrouped", [0x20, 0x21, 0x22], None);
+        let copy_mappings =
+            queue
+                .slot::<extern "system" fn(This, u32, *const PageBatch, u64, u32, u32) -> HRESULT>(
+                    0xe8,
+                );
+        let range = PageRange {
+            kind: 0,
+            start: 0,
+            count: 3,
+        };
+        let batch = PageBatch {
+            destination: alias.base as u64,
+            count: 1,
+            ranges: &range,
+        };
+        assert_eq!(
+            copy_mappings(queue.0, 1, &batch, pool.base as u64, 4, 0),
+            S_OK
+        );
+        alias.assert_bytes(1, 0x21);
+        assert_eq!(
+            XMemMapPhysicalPages(pool.at(1), 1, &replacement.0[3]),
+            pool.at(1)
+        );
+        pool.assert_bytes(1, 0x23);
+        check(
+            "pool remapped, copy remains on the old physical page",
+            [0x20, 0x21, 0x22],
+            None,
+        );
+        assert_eq!(
+            query(alias.at(1)).host.Protect,
+            windows_sys::Win32::System::Memory::PAGE_READONLY
+        );
+        alias.at(1).cast::<u8>().write_bytes(0x42, PAGE);
+        // When a clean texture skips the upload at record time, the
+        // submission still refreshes staging. The next list must upload it.
+        check(
+            "detect an alias write",
+            [0x20, 0x42, 0x22],
+            Some([0x20, 0x21, 0x22]),
+        );
+        check("write to the copied alias", [0x20, 0x42, 0x22], None);
+        // DirectStorage writes through its own view, then announces the
+        // completed write. Before the announcement the guard cannot see it.
+        let pages = &replacement.0[1..2];
+        let mut window = page_window(pages, 0, PAGE).expect("physical view");
+        window.bytes().fill(0x65);
+        drop(window);
+        placed.assert_bytes(start + 1, 0x65);
+        check("unannounced physical write", [0x20, 0x42, 0x22], None);
+        pages_written(pages, 0, PAGE);
+        check(
+            "detect a physical write",
+            [0x20, 0x65, 0x22],
+            Some([0x20, 0x42, 0x22]),
+        );
+        check("physical write after remap", [0x20, 0x65, 0x22], None);
+        pool.assert_bytes(1, 0x23);
+
+        // The queue must not change the backing of a pending GPU readback's
+        // destination. Observe both the live address and an alias of the old
+        // pages so that even a remap that leaves equal data cannot hide it.
+        let targets = FixturePages(allocate(3));
+        let target = AliasWindow::new(3);
+        let old_target = AliasWindow::new(3);
+        let pattern = [0x20, 0x65, 0x22];
+        for held in [true, false] {
+            for (i, id) in targets.0.iter().enumerate() {
+                assert!(write_physical(
+                    std::slice::from_ref(id),
+                    0,
+                    &vec![0x70 + i as u8; PAGE]
+                ));
+            }
+            for window in [&target, &old_target] {
+                assert_eq!(
+                    XMemMapPhysicalPages(window.at(0), 3, targets.0.as_ptr()),
+                    window.at(0)
+                );
+            }
+            let copy_target = Com::new(|out| {
+                place(
+                    dev.0,
+                    target.base as u64,
+                    buffer.as_ptr(),
+                    0,
+                    null(),
+                    &RESOURCE,
+                    out,
+                )
+            });
+            let next_image = Com::new(|out| {
+                place(
+                    dev.0,
+                    target.base as u64,
+                    desc.as_ptr(),
+                    0,
+                    null(),
+                    &RESOURCE,
+                    out,
+                )
+            });
+            let into = CopyLocation {
+                resource: copy_target.0,
+                kind: 1,
+                footprint: Footprint {
+                    offset: 0,
+                    ..to.footprint
+                },
+            };
+            let allocator = Com::new(|out| make_allocator(dev.0, 0, &ALLOCATOR, out));
+            let list = Com::new(|out| make_list(dev.0, 0, 0, allocator.0, null(), &LIST, out));
+            let next = Com::new(|out| make_list(dev.0, 0, 0, allocator.0, null(), &LIST, out));
+            let gate = Com::new(|out| make_fence(dev.0, 0, 0, &FENCE, out));
+            let done = Com::new(|out| make_fence(dev.0, 0, 0, &FENCE, out));
+            let producer = Com::new(|out| make_queue(dev.0, [0u32; 4].as_ptr(), &QUEUE, out));
+            let copy = list.slot::<extern "system" fn(
+                This,
+                *const CopyLocation,
+                u32,
+                u32,
+                u32,
+                *const CopyLocation,
+                *const c_void,
+            )>(0x80);
+            let close = list.slot::<extern "system" fn(This) -> HRESULT>(0x48);
+            copy(list.0, &into, 0, 0, 0, &from, null());
+            assert_eq!(close(list.0), S_OK);
+            if held {
+                let wait = queue.slot::<extern "system" fn(This, This, u64) -> HRESULT>(0x78);
+                assert_eq!(wait(queue.0, gate.0, 1), S_OK);
+            }
+            execute(queue.0, 1, &list.0);
+            // Borrowed descriptors are deliberately overwritten before the
+            // fence opens. The queue must own them if it delays the remap.
+            let mut range = PageRange {
+                kind: 0,
+                start: 0,
+                count: 3,
+            };
+            let mut batch = PageBatch {
+                destination: target.base as u64,
+                count: 1,
+                ranges: &raw const range,
+            };
+            let queued = copy_mappings(queue.0, 1, &raw const batch, pool.base as u64, 4, 0);
+            std::ptr::write_volatile(&raw mut range.kind, 3);
+            std::ptr::write_volatile(&raw mut batch.count, 0);
+            let source = CopyLocation {
+                resource: next_image.0,
+                kind: 0,
+                footprint: Footprint {
+                    offset: 0,
+                    ..from.footprint
+                },
+            };
+            data.write_bytes(0xd3, BYTES);
+            copy(next.0, &to, 0, 0, 0, &source, null());
+            assert_eq!(close(next.0), S_OK);
+            execute(queue.0, 1, &next.0);
+            if held {
+                // A zero-plane Present exercises the legacy wait-forcing
+                // path without opening a window or presenting an image.
+                let present = queue.slot::<extern "system" fn(
+                    This,
+                    u32,
+                    *const c_void,
+                    *const c_void,
+                ) -> HRESULT>(0xf0);
+                assert_eq!(present(queue.0, 0, null(), null()), S_OK);
+            }
+            let before = held.then(|| target.at(1).cast::<u8>().read());
+            assert_eq!(signal(queue.0, done.0, 1), S_OK);
+            if held {
+                assert_eq!(signal(producer.0, gate.0, 1), S_OK);
+            }
+            done.wait_for(1);
+            assert_eq!(queued, S_OK);
+            let old = old_target.at(1).cast::<u8>().read();
+            let new = target.at(1).cast::<u8>().read();
+            assert_eq!(
+                (before, old, new),
+                (held.then_some(0x71), 0x65, 0x23),
+                "remap overtook earlier GPU readback (held={held}): before, old backing, new backing"
+            );
+            for (page, value) in pattern.into_iter().enumerate() {
+                old_target.assert_bytes(page, value);
+            }
+            for (page, value) in [0x20, 0x23, 0x22].into_iter().enumerate() {
+                target.assert_bytes(page, value);
+                let bytes = std::slice::from_raw_parts(data.add(page * PAGE), PAGE);
+                assert!(
+                    bytes.iter().all(|&actual| actual == value),
+                    "later GPU read used old backing, page {page} (held={held})"
+                );
+            }
+        }
+
+        // Register the retired queue first, then a mapping queue behind the
+        // same closed gate. With joining enabled, the latter's remap is a
+        // boundary: the former's list and signal go through Joined, and its
+        // now-empty queue mark is cleaned up before the remap can run.
+        let retired = Com::new(|out| make_queue(dev.0, [0u32; 4].as_ptr(), &QUEUE, out));
+        let mapped = Com::new(|out| make_queue(dev.0, [0u32; 4].as_ptr(), &QUEUE, out));
+        let producer = Com::new(|out| make_queue(dev.0, [0u32; 4].as_ptr(), &QUEUE, out));
+        let gate = Com::new(|out| make_fence(dev.0, 0, 0, &FENCE, out));
+        let copied = Com::new(|out| make_fence(dev.0, 0, 0, &FENCE, out));
+        let done = Com::new(|out| make_fence(dev.0, 0, 0, &FENCE, out));
+        let mut copied_event = Event::new();
+        copied.arm(1, &mut copied_event);
+        let retired_target = AliasWindow::new(1);
+        assert_eq!(
+            XMemMapPhysicalPages(retired_target.at(0), 1, &targets.0[1]),
+            retired_target.at(0)
+        );
+        retired_target.assert_bytes(0, 0x65);
+        let allocator = Com::new(|out| make_allocator(dev.0, 0, &ALLOCATOR, out));
+        let list = Com::new(|out| make_list(dev.0, 0, 0, allocator.0, null(), &LIST, out));
+        let copy = list.slot::<extern "system" fn(
+            This,
+            *const CopyLocation,
+            u32,
+            u32,
+            u32,
+            *const CopyLocation,
+            *const c_void,
+        )>(0x80);
+        let close = list.slot::<extern "system" fn(This) -> HRESULT>(0x48);
+        data.write_bytes(0xd3, BYTES);
+        copy(list.0, &to, 0, 0, 0, &from, null());
+        assert_eq!(close(list.0), S_OK);
+        let range = PageRange {
+            kind: 0,
+            start: 1,
+            count: 1,
+        };
+        let batch = PageBatch {
+            destination: retired_target.base as u64,
+            count: 1,
+            ranges: &range,
+        };
+        let wait = retired.slot::<extern "system" fn(This, This, u64) -> HRESULT>(0x78);
+        assert_eq!(wait(retired.0, gate.0, 1), S_OK);
+        execute(retired.0, 1, &list.0);
+        assert_eq!(signal(retired.0, copied.0, 1), S_OK);
+        assert_eq!(wait(mapped.0, gate.0, 1), S_OK);
+        assert_eq!(
+            copy_mappings(mapped.0, 1, &batch, pool.base as u64, 4, 0),
+            S_OK
+        );
+        assert_eq!(signal(mapped.0, done.0, 1), S_OK);
+        let completed = done.slot::<extern "system" fn(This) -> u64>(0x40);
+        assert_eq!(completed(copied.0), 0, "GPU signal passed its closed gate");
+        assert_eq!(completed(done.0), 0, "mapping queue passed its closed gate");
+        retired_target.assert_bytes(0, 0x65);
+        // No client owns either queue or the copied fence when the gate
+        // opens. Keep the event, source, destination and lists alive instead.
+        drop(copied);
+        drop(retired);
+        drop(mapped);
+        assert_eq!(signal(producer.0, gate.0, 1), S_OK);
+        drop(gate);
+        copied_event.wait("retired queue GPU copy");
+        done.wait_for(1);
+        for (page, value) in pattern.into_iter().enumerate() {
+            let bytes = std::slice::from_raw_parts(data.add(page * PAGE), PAGE);
+            assert!(
+                bytes.iter().all(|&actual| actual == value),
+                "retired queue GPU copy, page {page}, expected {value:#x}"
+            );
+        }
+        old_target.assert_bytes(1, 0x65);
+        retired_target.assert_bytes(0, 0x23);
+    }
+}
**@⁠NotADonky43** on GitHub · 2026-11-25 21:22 UTC · [original](https://github.com/fxceless/victory-fork/issues/1131#issuecomment-7174990065) Source patches for this issue, part 2 of 2: the synthetic D3D12 fixture and its test dependencies. Apply after the placeholder prerequisite and the [runtime/queue patch](https://git.gtahub.st/github/fxceless--victory-fork/issues/1131). On Windows with a real D3D12 adapter, set `VICTORY_D3D12_DEBUG=1` and `VICTORY_D3D12_GBV=1`, then run: ``` cargo test --locked -p victory-hle --lib --features diagnostics modules::xmem::tests::gpu::regrouped_pages_refresh_a_placed_texture_on_the_gpu -- --exact --ignored --test-threads=1 --nocapture ``` The fixture does not load a game or save images. <details><summary>Part 2 of 2 — synthetic GPU fixture</summary> ```diff diff --git a/Cargo.lock b/Cargo.lock index 29bab8c..16fd682 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -692,6 +692,7 @@ dependencies = [ "opus-pure", "tempfile", "tracing", + "tracing-subscriber", "victory-formats", "victory-gpu", "victory-loader", diff --git a/crates/victory-hle/Cargo.toml b/crates/victory-hle/Cargo.toml index a2fa943..5fe7017 100644 --- a/crates/victory-hle/Cargo.toml +++ b/crates/victory-hle/Cargo.toml @@ -46,6 +46,7 @@ windows-core = { workspace = true, optional = true } [dev-dependencies] tempfile.workspace = true +tracing-subscriber.workspace = true [features] # Debugging switches (scripted keys and the like). diff --git a/crates/victory-hle/src/modules/xmem/tests/gpu.rs b/crates/victory-hle/src/modules/xmem/tests/gpu.rs new file mode 100644 index 0000000..3e5b854 --- /dev/null +++ b/crates/victory-hle/src/modules/xmem/tests/gpu.rs @@ -0,0 +1,665 @@ +//! Exercise XMem through the console queue and the real host texture upload +//! and read-back path. No title executable or assets are needed. + +use std::ptr::{null, null_mut}; +use victory_gpu::object::{HRESULT, Iid, Object, S_OK, guid}; +use windows_sys::Win32::Foundation::{WAIT_FAILED, WAIT_OBJECT_0}; +use windows_sys::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; + +use super::*; + +type This = *const Object; +const FENCE: Iid = guid( + 0x0a753dcf, + 0xc4d8, + 0x4b91, + [0xad, 0xf6, 0xbe, 0x5a, 0x60, 0xd9, 0x5a, 0x76], +); +const RESOURCE: Iid = guid( + 0x696442be, + 0xa72e, + 0x4059, + [0xbc, 0x79, 0x5b, 0x5c, 0x98, 4, 0xf, 0xad], +); +const QUEUE: Iid = guid( + 0x0ec870a6, + 0x5d7e, + 0x4c22, + [0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed], +); +const ALLOCATOR: Iid = guid( + 0x6102dee4, + 0xaf59, + 0x4b09, + [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24], +); +const LIST: Iid = guid( + 0x5b160d0f, + 0xac1b, + 0x4185, + [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55], +); + +/// An owned reference to a VIctory D3D12.X object, using the base (2.4) layout. +struct Com(This); + +impl Com { + fn new(create: impl FnOnce(*mut This) -> HRESULT) -> Self { + let mut object = null(); + assert_eq!(create(&mut object), S_OK); + assert!(!object.is_null()); + Self(object) + } + + /// SAFETY: `F` and `offset` must match this object's D3D12.X method. + unsafe fn slot<F: Copy>(&self, offset: usize) -> F { + assert_eq!(size_of::<F>(), size_of::<*const ()>()); + // SAFETY: VIctory objects begin with their function table pointer. + let address = unsafe { *(*self.0.cast::<*const *const ()>()).add(offset / 8) }; + unsafe { std::mem::transmute_copy(&address) } + } + + /// SAFETY: this object is a VIctory fence. The event must stay alive + /// until it signals, even if the client's fence reference is released. + unsafe fn arm(&self, value: u64, event: &mut Event) { + assert!(!event.armed); + let arm = unsafe { self.slot::<extern "system" fn(This, u64, HANDLE) -> HRESULT>(0x48) }; + let result = arm(self.0, value, event.handle); + if result != S_OK { + eprintln!("arm queue fence {value} failed: {result:#x}"); + std::process::abort(); + } + event.armed = true; + } + + /// SAFETY: this object is a VIctory fence. + unsafe fn wait_for(&self, value: u64) { + let mut event = Event::new(); + unsafe { self.arm(value, &mut event) }; + event.wait(&format!("queue fence {value}")); + } +} + +/// An event may be registered on a fence even after the client releases it. +struct Event { + handle: HANDLE, + armed: bool, +} + +impl Event { + fn new() -> Self { + // SAFETY: anonymous, initially reset event with the default security. + let handle = unsafe { CreateEventW(null(), 0, 0, null()) }; + if handle.is_null() { + eprintln!("CreateEventW failed: {}", std::io::Error::last_os_error()); + std::process::abort(); + } + Self { + handle, + armed: false, + } + } + + fn wait(&mut self, label: &str) { + assert!(self.armed); + tracing::debug!(label, "waiting for fixture fence"); + // SAFETY: this event stays alive until the fence has signalled it. + let result = unsafe { WaitForSingleObject(self.handle, INFINITE) }; + if result != WAIT_OBJECT_0 { + if result == WAIT_FAILED { + eprintln!( + "{label}: WaitForSingleObject failed: {}", + std::io::Error::last_os_error() + ); + } else { + eprintln!("{label}: unexpected wait result {result:#x}"); + } + // A fence or worker may still own the event and fixture memory. + std::process::abort(); + } + self.armed = false; + tracing::debug!(label, "fixture fence reached"); + } +} + +impl Drop for Event { + fn drop(&mut self) { + if self.armed { + // Unwinding must not close an event a pending fence may signal. + eprintln!("dropping an event still registered on a queue fence"); + std::process::abort(); + } + // SAFETY: this fixture owns the event and its registration completed. + if unsafe { CloseHandle(self.handle) } == 0 { + eprintln!("CloseHandle failed: {}", std::io::Error::last_os_error()); + std::process::abort(); + } + } +} + +impl Drop for Com { + fn drop(&mut self) { + // SAFETY: all these objects use IUnknown's Release in slot 2. + unsafe { (self.slot::<extern "system" fn(This) -> u32>(0x10))(self.0) }; + } +} + +#[repr(C)] +struct CopyLocation { + resource: This, + kind: u32, + footprint: Footprint, +} + +#[repr(C)] +struct Footprint { + offset: u64, + format: u32, + width: u32, + height: u32, + depth: u32, + row_pitch: u32, +} + +#[repr(C)] +struct PageRange { + kind: u32, + start: u32, + count: u32, +} + +#[repr(C)] +struct PageBatch { + destination: u64, + count: u32, + ranges: *const PageRange, +} + +const WIDTH: u32 = 256; +const HEIGHT: u32 = 192; +const PITCH: u32 = WIDTH * 4; +const BYTES: usize = (PITCH * HEIGHT) as usize; +const _: () = assert!(BYTES == 3 * PAGE); + +#[test] +#[ignore = "requires a real D3D12 device; run separately with diagnostics and the debug layer"] +fn regrouped_pages_refresh_a_placed_texture_on_the_gpu() { + let log = tracing_subscriber::fmt() + .with_test_writer() + .with_ansi(false) + .with_max_level(tracing::Level::DEBUG) + .finish(); + // Async queue and host workers run on other threads. A thread-local + // subscriber would hide their diagnostics from this dedicated process. + if let Err(error) = tracing::subscriber::set_global_default(log) { + eprintln!("GPU fixture could not install its tracing subscriber: {error}"); + } + let original = FixturePages(allocate(3)); + let replacement = FixturePages(allocate(4)); + let placed = AliasWindow::new(4); + // At frame zero, choose an address off the guard's one-in-eight hash + // turn, so a later write actually has to invalidate the guard. + let start = usize::from((placed.base / PAGE).is_multiple_of(8)); + let destination = placed.at(start); + let pool = AliasWindow::new(4); + let alias = AliasWindow::new(3); + for (pages, start) in [(&original.0, 0x10), (&replacement.0, 0x20)] { + for (i, id) in pages.iter().enumerate() { + assert!(write_physical( + std::slice::from_ref(id), + 0, + &vec![start + i as u8; PAGE] + )); + } + } + for (i, id) in original.0.iter().enumerate() { + let at = placed.at(start + i); + assert_eq!(XMemMapPhysicalPages(at, 1, id), at); + } + assert_eq!( + XMemMapPhysicalPages(pool.at(0), 4, replacement.0.as_ptr()), + pool.at(0) + ); + victory_gpu::resource::use_page_mapper(map_alias); + + let dev = Com::new(|out| { + victory_gpu::device::create( + null(), + &victory_gpu::device::CHECKED_VERSION, + &victory_gpu::device::IID, + out, + ) + }); + // SAFETY: the signatures and offsets below are for the VIctory base + // D3D12.X device/queue/list/resource vtables. All descriptions and output + // pointers are live for the calls; Com owns each returned reference. + unsafe { + let make_queue = dev + .slot::<extern "system" fn(This, *const u32, *const Iid, *mut This) -> HRESULT>(0x40); + let queue = Com::new(|out| make_queue(dev.0, [0u32; 4].as_ptr(), &QUEUE, out)); + let make_allocator = + dev.slot::<extern "system" fn(This, u32, *const Iid, *mut This) -> HRESULT>(0x48); + let make_list = dev.slot::<extern "system" fn( + This, + u32, + u32, + This, + This, + *const Iid, + *mut This, + ) -> HRESULT>(0x60); + let place = dev.slot::<extern "system" fn( + This, + u64, + *const u64, + u32, + *const c_void, + *const Iid, + *mut This, + ) -> HRESULT>(0x428); + let commit = dev.slot::<extern "system" fn( + This, + *const u32, + u32, + *const u64, + u32, + *const c_void, + *const Iid, + *mut This, + ) -> HRESULT>(0xd8); + // Seven u64s give the console ResourceDesc its 8-byte alignment. + // 2D, RGBA8, linear, one mip/layer/sample; buffer with a linear row layout. + let desc = [ + 3, + 0, + u64::from(WIDTH), + u64::from(HEIGHT) | (1 << 32) | (1 << 48), + 28 | (1 << 32), + 1 << 32, + 0, + ]; + let buffer = [ + 1, + 0, + BYTES as u64, + 1 | (1 << 32) | (1 << 48), + 1 << 32, + 1 << 32, + 0, + ]; + let image = Com::new(|out| { + place( + dev.0, + destination as u64, + desc.as_ptr(), + 0, + null(), + &RESOURCE, + out, + ) + }); + let readback = Com::new(|out| { + commit( + dev.0, + [1, 0, 0, 1, 1].as_ptr(), + 0, + buffer.as_ptr(), + 0, + null(), + &RESOURCE, + out, + ) + }); + let map = readback + .slot::<extern "system" fn(This, u32, *const c_void, *mut *mut u8) -> HRESULT>(0x40); + let mut data = null_mut(); + assert_eq!(map(readback.0, 0, null(), &mut data), S_OK); + assert!(!data.is_null()); + let to = CopyLocation { + resource: readback.0, + kind: 1, + footprint: Footprint { + offset: 0, + format: 28, + width: WIDTH, + height: HEIGHT, + depth: 1, + row_pitch: PITCH, + }, + }; + let from = CopyLocation { + resource: image.0, + kind: 0, + footprint: Footprint { + offset: 0, + ..to.footprint + }, + }; + let make_fence = + dev.slot::<extern "system" fn(This, u64, u32, *const Iid, *mut This) -> HRESULT>(0x120); + let execute = queue.slot::<extern "system" fn(This, u32, *const This)>(0x50); + let signal = queue.slot::<extern "system" fn(This, This, u64) -> HRESULT>(0x70); + let check = |label: &str, values: [u8; 3], pending: Option<[u8; 3]>| { + let allocator = Com::new(|out| make_allocator(dev.0, 0, &ALLOCATOR, out)); + let list = Com::new(|out| make_list(dev.0, 0, 0, allocator.0, null(), &LIST, out)); + let fence = Com::new(|out| make_fence(dev.0, 0, 0, &FENCE, out)); + let copy = list.slot::<extern "system" fn( + This, + *const CopyLocation, + u32, + u32, + u32, + *const CopyLocation, + *const c_void, + )>(0x80); + let close = list.slot::<extern "system" fn(This) -> HRESULT>(0x48); + data.write_bytes(0xd3, BYTES); // fail if no GPU copy reached the buffer + copy(list.0, &to, 0, 0, 0, &from, null()); + assert_eq!(close(list.0), S_OK); + // The default queue may submit asynchronously. Wait for its + // signal, including the deferred readback, before checking bytes. + execute(queue.0, 1, &list.0); + assert_eq!(signal(queue.0, fence.0, 1), S_OK, "{label}: signal queued"); + fence.wait_for(1); + let bytes = std::slice::from_raw_parts(data, BYTES); + if pending.is_some_and(|prior| { + bytes + .chunks_exact(PAGE) + .zip(prior) + .all(|(page, value)| page.iter().all(|&b| b == value)) + }) { + eprintln!("{label}: staging change will upload on the next list"); + return; + } + for (i, (page, value)) in bytes.chunks_exact(PAGE).zip(values).enumerate() { + let wrong = page.iter().position(|&byte| byte != value); + assert_eq!( + wrong, + None, + "{label}, page {i}; first wrong value {:?}, expected {value:#x}", + wrong.map(|at| page[at]) + ); + } + }; + check("initial", [0x10, 0x11, 0x12], None); + assert_eq!( + XMemMapPhysicalPages(destination, 3, replacement.0.as_ptr()), + destination + ); + check("regrouped", [0x20, 0x21, 0x22], None); + let copy_mappings = + queue + .slot::<extern "system" fn(This, u32, *const PageBatch, u64, u32, u32) -> HRESULT>( + 0xe8, + ); + let range = PageRange { + kind: 0, + start: 0, + count: 3, + }; + let batch = PageBatch { + destination: alias.base as u64, + count: 1, + ranges: &range, + }; + assert_eq!( + copy_mappings(queue.0, 1, &batch, pool.base as u64, 4, 0), + S_OK + ); + alias.assert_bytes(1, 0x21); + assert_eq!( + XMemMapPhysicalPages(pool.at(1), 1, &replacement.0[3]), + pool.at(1) + ); + pool.assert_bytes(1, 0x23); + check( + "pool remapped, copy remains on the old physical page", + [0x20, 0x21, 0x22], + None, + ); + assert_eq!( + query(alias.at(1)).host.Protect, + windows_sys::Win32::System::Memory::PAGE_READONLY + ); + alias.at(1).cast::<u8>().write_bytes(0x42, PAGE); + // When a clean texture skips the upload at record time, the + // submission still refreshes staging. The next list must upload it. + check( + "detect an alias write", + [0x20, 0x42, 0x22], + Some([0x20, 0x21, 0x22]), + ); + check("write to the copied alias", [0x20, 0x42, 0x22], None); + // DirectStorage writes through its own view, then announces the + // completed write. Before the announcement the guard cannot see it. + let pages = &replacement.0[1..2]; + let mut window = page_window(pages, 0, PAGE).expect("physical view"); + window.bytes().fill(0x65); + drop(window); + placed.assert_bytes(start + 1, 0x65); + check("unannounced physical write", [0x20, 0x42, 0x22], None); + pages_written(pages, 0, PAGE); + check( + "detect a physical write", + [0x20, 0x65, 0x22], + Some([0x20, 0x42, 0x22]), + ); + check("physical write after remap", [0x20, 0x65, 0x22], None); + pool.assert_bytes(1, 0x23); + + // The queue must not change the backing of a pending GPU readback's + // destination. Observe both the live address and an alias of the old + // pages so that even a remap that leaves equal data cannot hide it. + let targets = FixturePages(allocate(3)); + let target = AliasWindow::new(3); + let old_target = AliasWindow::new(3); + let pattern = [0x20, 0x65, 0x22]; + for held in [true, false] { + for (i, id) in targets.0.iter().enumerate() { + assert!(write_physical( + std::slice::from_ref(id), + 0, + &vec![0x70 + i as u8; PAGE] + )); + } + for window in [&target, &old_target] { + assert_eq!( + XMemMapPhysicalPages(window.at(0), 3, targets.0.as_ptr()), + window.at(0) + ); + } + let copy_target = Com::new(|out| { + place( + dev.0, + target.base as u64, + buffer.as_ptr(), + 0, + null(), + &RESOURCE, + out, + ) + }); + let next_image = Com::new(|out| { + place( + dev.0, + target.base as u64, + desc.as_ptr(), + 0, + null(), + &RESOURCE, + out, + ) + }); + let into = CopyLocation { + resource: copy_target.0, + kind: 1, + footprint: Footprint { + offset: 0, + ..to.footprint + }, + }; + let allocator = Com::new(|out| make_allocator(dev.0, 0, &ALLOCATOR, out)); + let list = Com::new(|out| make_list(dev.0, 0, 0, allocator.0, null(), &LIST, out)); + let next = Com::new(|out| make_list(dev.0, 0, 0, allocator.0, null(), &LIST, out)); + let gate = Com::new(|out| make_fence(dev.0, 0, 0, &FENCE, out)); + let done = Com::new(|out| make_fence(dev.0, 0, 0, &FENCE, out)); + let producer = Com::new(|out| make_queue(dev.0, [0u32; 4].as_ptr(), &QUEUE, out)); + let copy = list.slot::<extern "system" fn( + This, + *const CopyLocation, + u32, + u32, + u32, + *const CopyLocation, + *const c_void, + )>(0x80); + let close = list.slot::<extern "system" fn(This) -> HRESULT>(0x48); + copy(list.0, &into, 0, 0, 0, &from, null()); + assert_eq!(close(list.0), S_OK); + if held { + let wait = queue.slot::<extern "system" fn(This, This, u64) -> HRESULT>(0x78); + assert_eq!(wait(queue.0, gate.0, 1), S_OK); + } + execute(queue.0, 1, &list.0); + // Borrowed descriptors are deliberately overwritten before the + // fence opens. The queue must own them if it delays the remap. + let mut range = PageRange { + kind: 0, + start: 0, + count: 3, + }; + let mut batch = PageBatch { + destination: target.base as u64, + count: 1, + ranges: &raw const range, + }; + let queued = copy_mappings(queue.0, 1, &raw const batch, pool.base as u64, 4, 0); + std::ptr::write_volatile(&raw mut range.kind, 3); + std::ptr::write_volatile(&raw mut batch.count, 0); + let source = CopyLocation { + resource: next_image.0, + kind: 0, + footprint: Footprint { + offset: 0, + ..from.footprint + }, + }; + data.write_bytes(0xd3, BYTES); + copy(next.0, &to, 0, 0, 0, &source, null()); + assert_eq!(close(next.0), S_OK); + execute(queue.0, 1, &next.0); + if held { + // A zero-plane Present exercises the legacy wait-forcing + // path without opening a window or presenting an image. + let present = queue.slot::<extern "system" fn( + This, + u32, + *const c_void, + *const c_void, + ) -> HRESULT>(0xf0); + assert_eq!(present(queue.0, 0, null(), null()), S_OK); + } + let before = held.then(|| target.at(1).cast::<u8>().read()); + assert_eq!(signal(queue.0, done.0, 1), S_OK); + if held { + assert_eq!(signal(producer.0, gate.0, 1), S_OK); + } + done.wait_for(1); + assert_eq!(queued, S_OK); + let old = old_target.at(1).cast::<u8>().read(); + let new = target.at(1).cast::<u8>().read(); + assert_eq!( + (before, old, new), + (held.then_some(0x71), 0x65, 0x23), + "remap overtook earlier GPU readback (held={held}): before, old backing, new backing" + ); + for (page, value) in pattern.into_iter().enumerate() { + old_target.assert_bytes(page, value); + } + for (page, value) in [0x20, 0x23, 0x22].into_iter().enumerate() { + target.assert_bytes(page, value); + let bytes = std::slice::from_raw_parts(data.add(page * PAGE), PAGE); + assert!( + bytes.iter().all(|&actual| actual == value), + "later GPU read used old backing, page {page} (held={held})" + ); + } + } + + // Register the retired queue first, then a mapping queue behind the + // same closed gate. With joining enabled, the latter's remap is a + // boundary: the former's list and signal go through Joined, and its + // now-empty queue mark is cleaned up before the remap can run. + let retired = Com::new(|out| make_queue(dev.0, [0u32; 4].as_ptr(), &QUEUE, out)); + let mapped = Com::new(|out| make_queue(dev.0, [0u32; 4].as_ptr(), &QUEUE, out)); + let producer = Com::new(|out| make_queue(dev.0, [0u32; 4].as_ptr(), &QUEUE, out)); + let gate = Com::new(|out| make_fence(dev.0, 0, 0, &FENCE, out)); + let copied = Com::new(|out| make_fence(dev.0, 0, 0, &FENCE, out)); + let done = Com::new(|out| make_fence(dev.0, 0, 0, &FENCE, out)); + let mut copied_event = Event::new(); + copied.arm(1, &mut copied_event); + let retired_target = AliasWindow::new(1); + assert_eq!( + XMemMapPhysicalPages(retired_target.at(0), 1, &targets.0[1]), + retired_target.at(0) + ); + retired_target.assert_bytes(0, 0x65); + let allocator = Com::new(|out| make_allocator(dev.0, 0, &ALLOCATOR, out)); + let list = Com::new(|out| make_list(dev.0, 0, 0, allocator.0, null(), &LIST, out)); + let copy = list.slot::<extern "system" fn( + This, + *const CopyLocation, + u32, + u32, + u32, + *const CopyLocation, + *const c_void, + )>(0x80); + let close = list.slot::<extern "system" fn(This) -> HRESULT>(0x48); + data.write_bytes(0xd3, BYTES); + copy(list.0, &to, 0, 0, 0, &from, null()); + assert_eq!(close(list.0), S_OK); + let range = PageRange { + kind: 0, + start: 1, + count: 1, + }; + let batch = PageBatch { + destination: retired_target.base as u64, + count: 1, + ranges: &range, + }; + let wait = retired.slot::<extern "system" fn(This, This, u64) -> HRESULT>(0x78); + assert_eq!(wait(retired.0, gate.0, 1), S_OK); + execute(retired.0, 1, &list.0); + assert_eq!(signal(retired.0, copied.0, 1), S_OK); + assert_eq!(wait(mapped.0, gate.0, 1), S_OK); + assert_eq!( + copy_mappings(mapped.0, 1, &batch, pool.base as u64, 4, 0), + S_OK + ); + assert_eq!(signal(mapped.0, done.0, 1), S_OK); + let completed = done.slot::<extern "system" fn(This) -> u64>(0x40); + assert_eq!(completed(copied.0), 0, "GPU signal passed its closed gate"); + assert_eq!(completed(done.0), 0, "mapping queue passed its closed gate"); + retired_target.assert_bytes(0, 0x65); + // No client owns either queue or the copied fence when the gate + // opens. Keep the event, source, destination and lists alive instead. + drop(copied); + drop(retired); + drop(mapped); + assert_eq!(signal(producer.0, gate.0, 1), S_OK); + drop(gate); + copied_event.wait("retired queue GPU copy"); + done.wait_for(1); + for (page, value) in pattern.into_iter().enumerate() { + let bytes = std::slice::from_raw_parts(data.add(page * PAGE), PAGE); + assert!( + bytes.iter().all(|&actual| actual == value), + "retired queue GPU copy, page {page}, expected {value:#x}" + ); + } + old_target.assert_bytes(1, 0x65); + retired_target.assert_bytes(0, 0x23); + } +} ``` </details>
This discussion has been locked. Commenting is limited to contributors.
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
github/fxceless--victory-fork#1131
No description provided.