Keep independent D3D12 allocations out of the global title buffer lock #196

Open
opened 2026-11-27 08:32:31 +00:00 by github-bot · 1 comment
Owner

@⁠NotADonky43 on GitHub · 2026-11-27 08:31 UTC · original

Keep independent D3D12 allocation out of the title buffer table lock

A first lookup of a registered title buffer takes the global BUFFERS writer through title_shared_buffer(). Independent recording threads then wait to read even unrelated, already-published entries while the new resource is allocated, made resident, and mapped. This is separate from #178's stock of 64 KiB buffers and #192's dirty-page work inside an individual shadow.

Change: move only the independent backing allocation out of the table writer. A per-registration ticket serializes creators of that entry. Rerun the range lookup under the writer and check ticket identity before publishing; an unregister/re-register or a new more-specific range cannot inherit the earlier candidate. The imported/in-place paths and final card-copy bookkeeping remain under the existing lock; the residency fence is unchanged. The patch does not require enabling prewarm or importing the diagnostic counters.

Diagnostic A/B: Series X on Windows, RTX 5070 Ti, same e939566c-based executable and settings, 25,692 precompiled shader entries and the same native pipeline library, prewarm disabled both times. From startup through the first accepted present with at least 500 recorded draws since the preceding accepted present:

Metric Global writer held Independent allocation outside writer
Buffer-table read acquisition time, summed across threads 21.945 s 0.202 s
Buffer-table write acquisition time, summed 0.588 s 0.298 s
Per-entry constructor wait, summed n/a 0.024 s
Largest recent accepted-present gap 4.210 s 3.040 s

Acquisitions below 2 µs are omitted from the sums. The table times overlap across threads and are not seconds of wall-clock delay. The present marker had 1,393 vs. 1,145 draws, so this single pair shows a shorter observed gap, not a matched visual benchmark or sustained FPS gain. Summed small-allocation time increased (about 1.78 to 4.21 s through the first heavy telemetry sample) as allocations overlapped. Both runs ended cleanly without logged device removal or pipeline refusal.

Clean upstream port: tested on fdcfc2e9 with #192's shadow refresh changes intact. The included title-free RTX regressions use real D3D12 buffers, debug layer and GPU validation. They check independent readers, one result for concurrent creation, retry after failure, and byte-exact GPU readback after re-registering the same key or inserting a narrower overlapping registration during allocation. Validation command:

$env:VICTORY_D3D12_DEBUG='1'; $env:VICTORY_D3D12_GBV='1'
cargo test --locked --profile diag -p victory-gpu --features diagnostics --lib title_allocation_tests -- --test-threads=1

The optimized diagnostics build and the full workspace suite also passed. A separate boot of the clean port with precompiled shaders and the compatible native pipeline library reached the first heavy render sample (1,178 draws/frame) and closed normally on the requested milestone, under the 180 s game-only deadline. No device loss or pipeline refusal was logged. This is a runtime smoke check, not a claim of visual parity, steady frame rate, or lower memory use.

The diff below applies to both fdcfc2e9 (tested source base) and current main 4ee1a47b (git apply --check; only launcher logging and documentation changed between those two upstream revisions). It contains only engine source and synthetic tests.

diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs
index b8f908b9..bc45340a 100644
--- a/crates/victory-gpu/src/shadow.rs
+++ b/crates/victory-gpu/src/shadow.rs
@@ -5924,15 +5924,17 @@ mod land_tests {
 struct Entry {
     end: u64,
     shadow: Option<Arc<Shadow>>,
+    // A pending constructor and the identity of this registration until it publishes.
+    building: Option<Arc<Mutex<()>>>,
 }
 
 /// Title buffers by (start address, resource), with their copy once made.
 ///
 /// Read by every view a draw names, on all recording threads at once, and
 /// written when a buffer comes, goes or gets its copy: readers share it.
-static BUFFERS: std::sync::RwLock<BTreeMap<(u64, usize), Entry>> = std::sync::RwLock::new(BTreeMap::new());
+static BUFFERS: std::sync::RwLock<BufferTable> = std::sync::RwLock::new(BTreeMap::new());
 
-fn buffers() -> std::sync::RwLockWriteGuard<'static, BTreeMap<(u64, usize), Entry>> {
+fn buffers() -> std::sync::RwLockWriteGuard<'static, BufferTable> {
     let map = BUFFERS.write().unwrap_or_else(|e| e.into_inner());
     // What threads remember of it ([`FOUND`]) is of before.
     BUFFERS_CHANGED.fetch_add(1, Ordering::SeqCst);
@@ -5992,7 +5994,7 @@ fn remember(address: u64, len: u64, changed: u64, shadow: &Arc<Shadow>) {
     });
 }
 
-fn buffers_read() -> std::sync::RwLockReadGuard<'static, BTreeMap<(u64, usize), Entry>> {
+fn buffers_read() -> std::sync::RwLockReadGuard<'static, BufferTable> {
     BUFFERS.read().unwrap_or_else(|e| e.into_inner())
 }
 
@@ -6003,6 +6005,7 @@ pub(crate) fn register(resource: usize, start: u64, len: u64) {
         Entry {
             end: start + len,
             shadow: None,
+            building: None,
         },
     );
 }
@@ -6104,113 +6107,159 @@ pub(crate) fn peek(address: u64, len: u64) -> Option<Arc<Shadow>> {
     buffers_read().range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end).and_then(|(_, e)| e.shadow.clone())
 }
 
+/// Select the same registration after locking, before and after a slow allocation.
+type BufferTable = BTreeMap<(u64, usize), Entry>;
+
+fn buffer_key(map: &BufferTable, address: u64, end: u64) -> Option<(u64, usize)> {
+    map.range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end).map(|(k, _)| *k)
+}
+
+fn still_building(entry: &Entry, ticket: &Arc<Mutex<()>>) -> bool {
+    entry.building.as_ref().is_some_and(|id| Arc::ptr_eq(id, ticket))
+}
+
 fn lookup(address: u64, len: u64, any: bool) -> Option<Arc<Shadow>> {
+    lookup_with(address, len, any, |size| host()?.title_shared_buffer(size))
+}
+
+fn lookup_with(
+    address: u64,
+    len: u64,
+    any: bool,
+    make: impl Fn(u64) -> Option<(ID3D12Resource, *mut u8)>,
+) -> Option<Arc<Shadow>> {
     let quick = quick_find();
     if quick && let Some(shadow) = found(address, len) {
         return Some(shadow);
     }
     let end = address.checked_add(len.max(1))?;
-    {
-        let map = buffers_read();
-        match map.range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end) {
-            // The copy is made already (nearly always).
-            Some((_, Entry { shadow: Some(shadow), .. })) => {
-                if quick {
-                    // (Nobody changes the map while this lock is held.)
-                    remember(address, len, BUFFERS_CHANGED.load(Ordering::SeqCst), shadow);
+    loop {
+        {
+            let map = buffers_read();
+            match map.range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end) {
+                Some((_, Entry { shadow: Some(shadow), .. })) => {
+                    if quick {
+                        remember(address, len, BUFFERS_CHANGED.load(Ordering::SeqCst), shadow);
+                    }
+                    return Some(shadow.clone());
+                }
+                Some(_) => {}
+                None => {
+                    drop(map);
+                    return loose(address, end, len <= 1, any);
                 }
-                return Some(shadow.clone());
-            }
-            Some(_) => {}
-            None => {
-                drop(map);
-                return loose(address, end, len <= 1, any);
             }
         }
-    }
-    let mut map = buffers();
-    let key = map
-        .range(..=(address, usize::MAX))
-        .rev()
-        .take(64)
-        .find(|(_, e)| e.end >= end)
-        .map(|(k, _)| *k);
-    let Some(key) = key else {
-        drop(map);
-        return loose(address, end, len <= 1, any);
-    };
-    let entry = map.get_mut(&key)?;
-    if entry.shadow.is_none() {
+        let mut map = buffers();
+        let Some(key) = buffer_key(&map, address, end) else {
+            drop(map);
+            return loose(address, end, len <= 1, any);
+        };
+        let entry = map.get_mut(&key)?;
+        if let Some(shadow) = &entry.shadow {
+            return Some(shadow.clone());
+        }
         let len = entry.end - key.0;
         // Rounded up so that views ending in the buffer's last 256 bytes fit.
-        // Shaders write some buffers (unordered access), so not upload memory.
         let size = len.next_multiple_of(1 << 16);
-        // In place, if asked for and the memory can be opened
-        // (`crate::inplace::place_for`): the buffer is the title's own
-        // memory. Not the big ones `cards` puts in the card's memory: those
-        // are read too often to stay in the PC's.
         let big = cards() && (size >= card_limits().0 || card_all());
-        // Renderer port 1 (`crate::port`, `VICTORY_PORT_CONSTANTS=1`): the
-        // title's 32-bit graphics heap in place, big or not.
-        if let Some(placed) = crate::port::place_for(key.0, len, false) {
-            entry.shadow = Some(Arc::new(Shadow::placed(placed, key.0, len, false)));
-            return entry.shadow.clone();
-        }
-        if !big && let Some(placed) = crate::inplace::place_for(key.0, len, false) {
-            entry.shadow = Some(Arc::new(Shadow::placed(placed, key.0, len, false)));
-            return entry.shadow.clone();
-        }
-        let (buffer, data) = host()?.title_shared_buffer(size)?;
-        crate::host::name(&buffer, || format!("title buffer {:#x}+{len:#x}", key.0));
-        // A big one, with `cards`: shaders get a buffer in the card's own
-        // memory, and the one just made is the CPU's side.
-        let (buffer, card) = match card_for(size) {
-            Some(on_card) => {
-                crate::host::name(&on_card, || format!("title buffer {:#x}+{len:#x} on the card", key.0));
-                tracing::info!(
-                    start = format_args!("{:#x}", key.0),
-                    len,
-                    "a buffer's host copy is in the card's memory"
-                );
-                let card = Card {
-                    staging: buffer,
-                    before: Mutex::default(),
-                    dirty: Mutex::default(),
-                    has_dirty: AtomicBool::new(false),
-                    sent: Mutex::default(),
-                    has_sent: AtomicBool::new(false),
-                    size,
-                };
-                (on_card, Some(card))
+        if let Some(placed) = crate::port::place_for(key.0, len, false)
+            .or_else(|| if big { None } else { crate::inplace::place_for(key.0, len, false) })
+        {
+            let shadow = Arc::new(Shadow::placed(placed, key.0, len, false));
+            entry.shadow = Some(shadow.clone());
+            return Some(shadow);
+        }
+        // Keep the original transaction for optional imported/placed memory.
+        // The change below can only manufacture independent, untouched backing.
+        if crate::port::on() || crate::inplace::level() >= 2 {
+            let (buffer, data) = make(size)?;
+            let shadow = copied_buffer(key.0, len, size, buffer, data);
+            entry.shadow = Some(shadow.clone());
+            return Some(shadow);
+        }
+        let ticket = entry.building.get_or_insert_with(Default::default).clone();
+        drop(map);
+        // Never wait for an entry while holding the global table. Other
+        // lookups can proceed; followers of this entry cannot allocate twins.
+        let _only = ticket.lock().unwrap_or_else(|e| e.into_inner());
+        {
+            let map = buffers_read();
+            if buffer_key(&map, address, end) != Some(key) || !map.get(&key).is_some_and(|e| still_building(e, &ticket)) {
+                continue;
             }
-            None => (buffer, None),
-        };
-        // SAFETY: a live buffer.
-        let gpu = unsafe { buffer.GetGPUVirtualAddress() };
-        if len >= 16 << 20 {
+        }
+        let backing = make(size);
+        let mut map = buffers();
+        if buffer_key(&map, address, end) != Some(key) || !map.get(&key).is_some_and(|e| still_building(e, &ticket)) {
+            // Registration was replaced or an overlapping buffer now wins.
+            // Drop an unpublished buffer without blocking table readers.
+            drop(map);
+            drop(backing);
+            continue;
+        }
+        let (buffer, data) = backing?;
+        let entry = map.get_mut(&key)?;
+        let shadow = copied_buffer(key.0, len, size, buffer, data);
+        entry.shadow = Some(shadow.clone());
+        entry.building = None;
+        return Some(shadow);
+    }
+}
+
+/// Publish card bookkeeping before attaching the completed copy to its entry.
+fn copied_buffer(start: u64, len: u64, size: u64, buffer: ID3D12Resource, data: *mut u8) -> Arc<Shadow> {
+    crate::host::name(&buffer, || format!("title buffer {:#x}+{len:#x}", start));
+    // A big one, with `cards`: shaders get a buffer in the card's own
+    // memory, and the one just made is the CPU's side.
+    let (buffer, card) = match card_for(size) {
+        Some(on_card) => {
+            crate::host::name(&on_card, || format!("title buffer {:#x}+{len:#x} on the card", start));
             tracing::info!(
-                start = format_args!("{:#x}", key.0),
+                start = format_args!("{:#x}", start),
                 len,
-                "large buffer copied to the host"
+                "a buffer's host copy is in the card's memory"
             );
-        } else {
-            tracing::debug!(
-                start = format_args!("{:#x}", key.0),
-                len,
-                "buffer copied to the host"
-            );
-        }
-        let mut shadow = Shadow::new(buffer, data, gpu, key.0, len);
-        shadow.card = card;
-        let shadow = Arc::new(shadow);
-        if shadow.card.is_some() {
-            CARDED.lock().unwrap_or_else(|e| e.into_inner()).push(Arc::downgrade(&shadow));
+            let card = Card {
+                staging: buffer,
+                before: Mutex::default(),
+                dirty: Mutex::default(),
+                has_dirty: AtomicBool::new(false),
+                sent: Mutex::default(),
+                has_sent: AtomicBool::new(false),
+                size,
+            };
+            (on_card, Some(card))
         }
-        entry.shadow = Some(shadow);
+        None => (buffer, None),
+    };
+    // SAFETY: a live buffer.
+    let gpu = unsafe { buffer.GetGPUVirtualAddress() };
+    if len >= 16 << 20 {
+        tracing::info!(
+            start = format_args!("{:#x}", start),
+            len,
+            "large buffer copied to the host"
+        );
+    } else {
+        tracing::debug!(
+            start = format_args!("{:#x}", start),
+            len,
+            "buffer copied to the host"
+        );
     }
-    entry.shadow.clone()
+    let mut shadow = Shadow::new(buffer, data, gpu, start, len);
+    shadow.card = card;
+    let shadow = Arc::new(shadow);
+    if shadow.card.is_some() {
+        CARDED.lock().unwrap_or_else(|e| e.into_inner()).push(Arc::downgrade(&shadow));
+    }
+    shadow
 }
 
+#[cfg(test)]
+mod title_allocation_tests;
+
 /// Titles also use memory outside any buffer object as GPU memory (
 /// the title's interface vertices, from its own allocator). Such memory
 /// gets copies of the aligned windows it touches.
diff --git a/crates/victory-gpu/src/shadow/title_allocation_tests.rs b/crates/victory-gpu/src/shadow/title_allocation_tests.rs
new file mode 100644
index 00000000..72e40530
--- /dev/null
+++ b/crates/victory-gpu/src/shadow/title_allocation_tests.rs
@@ -0,0 +1,160 @@
+use super::*;
+use std::sync::atomic::AtomicUsize;
+use std::sync::mpsc::{Receiver, Sender, channel};
+use windows::Win32::Graphics::Direct3D12::D3D12_RANGE;
+use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree};
+
+const K64: usize = 64 << 10;
+
+struct Title(u64);
+impl Title {
+    fn new() -> Self {
+        // SAFETY: private committed synthetic memory of two pages.
+        let p = unsafe { VirtualAlloc(std::ptr::null(), 2 * K64, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) };
+        assert!(!p.is_null());
+        Self(p as u64)
+    }
+
+    fn fill(&self, value: u8) {
+        // SAFETY: fixture owns the full committed allocation.
+        unsafe { (self.0 as *mut u8).write_bytes(value, 2 * K64) };
+    }
+}
+
+impl Drop for Title {
+    fn drop(&mut self) {
+        unregister(1, self.0);
+        unregister(2, self.0 + K64 as u64);
+        // SAFETY: the fixture's private allocation, after workers joined.
+        unsafe { VirtualFree(self.0 as *mut _, 0, MEM_RELEASE) };
+    }
+}
+
+fn allocate(size: u64) -> Option<(ID3D12Resource, *mut u8)> {
+    host().expect("allocation fixture needs a D3D12 adapter").title_shared_buffer(size)
+}
+
+fn delayed(ready: &Sender<()>, go: &Receiver<()>, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
+    let made = allocate(size);
+    ready.send(()).unwrap();
+    go.recv().unwrap();
+    made
+}
+
+#[test]
+fn an_unrelated_lookup_runs_while_a_fresh_shadow_is_pending() {
+    assert!(!crate::port::on() && crate::inplace::level() < 2);
+    let title = Title::new();
+    let addr = title.0;
+    let other = addr + K64 as u64;
+    register(1, addr, K64 as u64);
+    register(2, other, K64 as u64);
+    let existing = lookup_with(other, 1, false, allocate).unwrap();
+    let made = AtomicUsize::new(0);
+    std::thread::scope(|scope| {
+        let (ready, waiting) = channel();
+        let (go, resume) = channel();
+        let first = scope.spawn(move || {
+            lookup_with(addr, 1, false, |size| delayed(&ready, &resume, size)).unwrap()
+        });
+        waiting.recv().unwrap();
+        // Do not block in a negative control that keeps the global writer.
+        let unrelated = BUFFERS.try_read().ok().and_then(|map| map.get(&(other, 2))?.shadow.clone());
+        let maker = &made;
+        let follower = scope.spawn(move || {
+            lookup_with(addr, 1, false, |size| {
+                maker.fetch_add(1, Ordering::Relaxed);
+                allocate(size)
+            }).unwrap()
+        });
+        go.send(()).unwrap();
+        let winner = first.join().unwrap();
+        assert!(Arc::ptr_eq(&winner, &follower.join().unwrap()));
+        assert!(Arc::ptr_eq(&existing, &unrelated.expect("other entry must remain readable")));
+        assert_eq!(made.load(Ordering::Relaxed), 0);
+    });
+}
+
+#[test]
+fn a_pending_allocation_reselects_the_live_registration_and_refreshes_its_bytes() {
+    assert!(!crate::port::on() && crate::inplace::level() < 2);
+    for overlap in [false, true] {
+        let title = Title::new();
+        title.fill(0x11);
+        let addr = title.0;
+        let ask = addr + K64 as u64 + 13;
+        register(1, addr, (2 * K64) as u64);
+        let made = AtomicUsize::new(0);
+        std::thread::scope(|scope| {
+            let (ready, waiting) = channel();
+            let (go, resume) = channel();
+            let count = &made;
+            let worker = scope.spawn(move || {
+                lookup_with(ask, 1, false, |size| {
+                    if count.fetch_add(1, Ordering::Relaxed) == 0 {
+                        delayed(&ready, &resume, size)
+                    } else {
+                        allocate(size)
+                    }
+                }).unwrap()
+            });
+            waiting.recv().unwrap();
+            // Fail without leaving the worker waiting if allocation accidentally
+            // regains the global writer.
+            if BUFFERS.try_write().is_err() {
+                go.send(()).unwrap();
+                worker.join().unwrap();
+                panic!("registration must be able to change during allocation");
+            }
+            if overlap {
+                register(2, addr + K64 as u64, K64 as u64);
+            } else {
+                unregister(1, addr);
+                register(1, addr, (2 * K64) as u64);
+            }
+            title.fill(0x65);
+            go.send(()).unwrap();
+            let winner = worker.join().unwrap();
+            assert_eq!(made.load(Ordering::Relaxed), 2, "obsolete backing must not be published");
+            assert_eq!(winner.start, if overlap { addr + K64 as u64 } else { addr });
+            // Exercise the submit-time refresh and read the GPU's view, not just
+            // the CPU mapping of the shadow.
+            let host = host().unwrap();
+            let readback = host.read_back_buffer(K64 as u64).unwrap();
+            let list = host.new_list().unwrap();
+            let from = addr + K64 as u64;
+            winner.refresh(&list, from, K64 as u64);
+            // SAFETY: the requested page is inside the refreshed shadow. The
+            // destination is a live readback buffer in COPY_DEST.
+            unsafe { list.list.CopyBufferRegion(&readback, 0, &winner.buffer, from - winner.start, K64 as u64) };
+            list.close();
+            host.execute_sync_internal(&list);
+            let mut bytes = std::ptr::null_mut();
+            let read = D3D12_RANGE { Begin: 0, End: K64 };
+            let written = D3D12_RANGE { Begin: 0, End: 0 };
+            // SAFETY: the submitting call waited for the copy. We read only
+            // the mapped allocation and do not write it.
+            let good = unsafe {
+                readback.Map(0, Some(&read), Some(&mut bytes)).unwrap();
+                assert!(!bytes.is_null());
+                let good = std::slice::from_raw_parts(bytes.cast::<u8>(), K64).iter().all(|&b| b == 0x65);
+                readback.Unmap(0, Some(&written));
+                good
+            };
+            assert!(good, "GPU readback did not see the live registration's bytes");
+            assert!(host.log_messages().is_none(), "D3D12 reported validation errors");
+            if overlap {
+                assert!(buffers_read().get(&(addr, 1)).unwrap().shadow.is_none());
+            }
+        });
+    }
+}
+
+#[test]
+fn an_allocation_failure_leaves_the_registration_open_to_retry() {
+    let title = Title::new();
+    let addr = title.0;
+    register(1, addr, K64 as u64);
+    assert!(lookup_with(addr, 1, false, |_| None).is_none());
+    assert!(lookup_with(addr, 1, false, allocate).is_some());
+}
**@⁠NotADonky43** on GitHub · 2026-11-27 08:31 UTC · [original](https://github.com/TaynanGT/Vice-Tay/issues/196) ### Keep independent D3D12 allocation out of the title buffer table lock A first lookup of a registered title buffer takes the global `BUFFERS` writer through `title_shared_buffer()`. Independent recording threads then wait to read even unrelated, already-published entries while the new resource is allocated, made resident, and mapped. This is separate from #178's stock of 64 KiB buffers and #192's dirty-page work inside an individual shadow. **Change:** move only the independent backing allocation out of the table writer. A per-registration ticket serializes creators of that entry. Rerun the range lookup under the writer and check ticket identity before publishing; an unregister/re-register or a new more-specific range cannot inherit the earlier candidate. The imported/in-place paths and final card-copy bookkeeping remain under the existing lock; the residency fence is unchanged. The patch does not require enabling prewarm or importing the diagnostic counters. **Diagnostic A/B:** Series X on Windows, RTX 5070 Ti, same `e939566c`-based executable and settings, 25,692 precompiled shader entries and the same native pipeline library, prewarm disabled both times. From startup through the first accepted present with at least 500 recorded draws since the preceding accepted present: | Metric | Global writer held | Independent allocation outside writer | | --- | ---: | ---: | | Buffer-table read acquisition time, summed across threads | 21.945 s | 0.202 s | | Buffer-table write acquisition time, summed | 0.588 s | 0.298 s | | Per-entry constructor wait, summed | n/a | 0.024 s | | Largest recent accepted-present gap | 4.210 s | 3.040 s | Acquisitions below 2 µs are omitted from the sums. The table times overlap across threads and are **not** seconds of wall-clock delay. The present marker had 1,393 vs. 1,145 draws, so this single pair shows a shorter observed gap, not a matched visual benchmark or sustained FPS gain. Summed small-allocation time increased (about 1.78 to 4.21 s through the first heavy telemetry sample) as allocations overlapped. Both runs ended cleanly without logged device removal or pipeline refusal. **Clean upstream port:** tested on `fdcfc2e9` with #192's shadow refresh changes intact. The included title-free RTX regressions use real D3D12 buffers, debug layer and GPU validation. They check independent readers, one result for concurrent creation, retry after failure, and byte-exact GPU readback after re-registering the same key or inserting a narrower overlapping registration during allocation. Validation command: ```powershell $env:VICTORY_D3D12_DEBUG='1'; $env:VICTORY_D3D12_GBV='1' cargo test --locked --profile diag -p victory-gpu --features diagnostics --lib title_allocation_tests -- --test-threads=1 ``` The optimized diagnostics build and the full workspace suite also passed. A separate boot of the clean port with precompiled shaders and the compatible native pipeline library reached the first heavy render sample (1,178 draws/frame) and closed normally on the requested milestone, under the 180 s game-only deadline. No device loss or pipeline refusal was logged. This is a runtime smoke check, not a claim of visual parity, steady frame rate, or lower memory use. The diff below applies to both `fdcfc2e9` (tested source base) and current main `4ee1a47b` (`git apply --check`; only launcher logging and documentation changed between those two upstream revisions). It contains only engine source and synthetic tests. ```diff diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index b8f908b9..bc45340a 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -5924,15 +5924,17 @@ mod land_tests { struct Entry { end: u64, shadow: Option<Arc<Shadow>>, + // A pending constructor and the identity of this registration until it publishes. + building: Option<Arc<Mutex<()>>>, } /// Title buffers by (start address, resource), with their copy once made. /// /// Read by every view a draw names, on all recording threads at once, and /// written when a buffer comes, goes or gets its copy: readers share it. -static BUFFERS: std::sync::RwLock<BTreeMap<(u64, usize), Entry>> = std::sync::RwLock::new(BTreeMap::new()); +static BUFFERS: std::sync::RwLock<BufferTable> = std::sync::RwLock::new(BTreeMap::new()); -fn buffers() -> std::sync::RwLockWriteGuard<'static, BTreeMap<(u64, usize), Entry>> { +fn buffers() -> std::sync::RwLockWriteGuard<'static, BufferTable> { let map = BUFFERS.write().unwrap_or_else(|e| e.into_inner()); // What threads remember of it ([`FOUND`]) is of before. BUFFERS_CHANGED.fetch_add(1, Ordering::SeqCst); @@ -5992,7 +5994,7 @@ fn remember(address: u64, len: u64, changed: u64, shadow: &Arc<Shadow>) { }); } -fn buffers_read() -> std::sync::RwLockReadGuard<'static, BTreeMap<(u64, usize), Entry>> { +fn buffers_read() -> std::sync::RwLockReadGuard<'static, BufferTable> { BUFFERS.read().unwrap_or_else(|e| e.into_inner()) } @@ -6003,6 +6005,7 @@ pub(crate) fn register(resource: usize, start: u64, len: u64) { Entry { end: start + len, shadow: None, + building: None, }, ); } @@ -6104,113 +6107,159 @@ pub(crate) fn peek(address: u64, len: u64) -> Option<Arc<Shadow>> { buffers_read().range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end).and_then(|(_, e)| e.shadow.clone()) } +/// Select the same registration after locking, before and after a slow allocation. +type BufferTable = BTreeMap<(u64, usize), Entry>; + +fn buffer_key(map: &BufferTable, address: u64, end: u64) -> Option<(u64, usize)> { + map.range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end).map(|(k, _)| *k) +} + +fn still_building(entry: &Entry, ticket: &Arc<Mutex<()>>) -> bool { + entry.building.as_ref().is_some_and(|id| Arc::ptr_eq(id, ticket)) +} + fn lookup(address: u64, len: u64, any: bool) -> Option<Arc<Shadow>> { + lookup_with(address, len, any, |size| host()?.title_shared_buffer(size)) +} + +fn lookup_with( + address: u64, + len: u64, + any: bool, + make: impl Fn(u64) -> Option<(ID3D12Resource, *mut u8)>, +) -> Option<Arc<Shadow>> { let quick = quick_find(); if quick && let Some(shadow) = found(address, len) { return Some(shadow); } let end = address.checked_add(len.max(1))?; - { - let map = buffers_read(); - match map.range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end) { - // The copy is made already (nearly always). - Some((_, Entry { shadow: Some(shadow), .. })) => { - if quick { - // (Nobody changes the map while this lock is held.) - remember(address, len, BUFFERS_CHANGED.load(Ordering::SeqCst), shadow); + loop { + { + let map = buffers_read(); + match map.range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end) { + Some((_, Entry { shadow: Some(shadow), .. })) => { + if quick { + remember(address, len, BUFFERS_CHANGED.load(Ordering::SeqCst), shadow); + } + return Some(shadow.clone()); + } + Some(_) => {} + None => { + drop(map); + return loose(address, end, len <= 1, any); } - return Some(shadow.clone()); - } - Some(_) => {} - None => { - drop(map); - return loose(address, end, len <= 1, any); } } - } - let mut map = buffers(); - let key = map - .range(..=(address, usize::MAX)) - .rev() - .take(64) - .find(|(_, e)| e.end >= end) - .map(|(k, _)| *k); - let Some(key) = key else { - drop(map); - return loose(address, end, len <= 1, any); - }; - let entry = map.get_mut(&key)?; - if entry.shadow.is_none() { + let mut map = buffers(); + let Some(key) = buffer_key(&map, address, end) else { + drop(map); + return loose(address, end, len <= 1, any); + }; + let entry = map.get_mut(&key)?; + if let Some(shadow) = &entry.shadow { + return Some(shadow.clone()); + } let len = entry.end - key.0; // Rounded up so that views ending in the buffer's last 256 bytes fit. - // Shaders write some buffers (unordered access), so not upload memory. let size = len.next_multiple_of(1 << 16); - // In place, if asked for and the memory can be opened - // (`crate::inplace::place_for`): the buffer is the title's own - // memory. Not the big ones `cards` puts in the card's memory: those - // are read too often to stay in the PC's. let big = cards() && (size >= card_limits().0 || card_all()); - // Renderer port 1 (`crate::port`, `VICTORY_PORT_CONSTANTS=1`): the - // title's 32-bit graphics heap in place, big or not. - if let Some(placed) = crate::port::place_for(key.0, len, false) { - entry.shadow = Some(Arc::new(Shadow::placed(placed, key.0, len, false))); - return entry.shadow.clone(); - } - if !big && let Some(placed) = crate::inplace::place_for(key.0, len, false) { - entry.shadow = Some(Arc::new(Shadow::placed(placed, key.0, len, false))); - return entry.shadow.clone(); - } - let (buffer, data) = host()?.title_shared_buffer(size)?; - crate::host::name(&buffer, || format!("title buffer {:#x}+{len:#x}", key.0)); - // A big one, with `cards`: shaders get a buffer in the card's own - // memory, and the one just made is the CPU's side. - let (buffer, card) = match card_for(size) { - Some(on_card) => { - crate::host::name(&on_card, || format!("title buffer {:#x}+{len:#x} on the card", key.0)); - tracing::info!( - start = format_args!("{:#x}", key.0), - len, - "a buffer's host copy is in the card's memory" - ); - let card = Card { - staging: buffer, - before: Mutex::default(), - dirty: Mutex::default(), - has_dirty: AtomicBool::new(false), - sent: Mutex::default(), - has_sent: AtomicBool::new(false), - size, - }; - (on_card, Some(card)) + if let Some(placed) = crate::port::place_for(key.0, len, false) + .or_else(|| if big { None } else { crate::inplace::place_for(key.0, len, false) }) + { + let shadow = Arc::new(Shadow::placed(placed, key.0, len, false)); + entry.shadow = Some(shadow.clone()); + return Some(shadow); + } + // Keep the original transaction for optional imported/placed memory. + // The change below can only manufacture independent, untouched backing. + if crate::port::on() || crate::inplace::level() >= 2 { + let (buffer, data) = make(size)?; + let shadow = copied_buffer(key.0, len, size, buffer, data); + entry.shadow = Some(shadow.clone()); + return Some(shadow); + } + let ticket = entry.building.get_or_insert_with(Default::default).clone(); + drop(map); + // Never wait for an entry while holding the global table. Other + // lookups can proceed; followers of this entry cannot allocate twins. + let _only = ticket.lock().unwrap_or_else(|e| e.into_inner()); + { + let map = buffers_read(); + if buffer_key(&map, address, end) != Some(key) || !map.get(&key).is_some_and(|e| still_building(e, &ticket)) { + continue; } - None => (buffer, None), - }; - // SAFETY: a live buffer. - let gpu = unsafe { buffer.GetGPUVirtualAddress() }; - if len >= 16 << 20 { + } + let backing = make(size); + let mut map = buffers(); + if buffer_key(&map, address, end) != Some(key) || !map.get(&key).is_some_and(|e| still_building(e, &ticket)) { + // Registration was replaced or an overlapping buffer now wins. + // Drop an unpublished buffer without blocking table readers. + drop(map); + drop(backing); + continue; + } + let (buffer, data) = backing?; + let entry = map.get_mut(&key)?; + let shadow = copied_buffer(key.0, len, size, buffer, data); + entry.shadow = Some(shadow.clone()); + entry.building = None; + return Some(shadow); + } +} + +/// Publish card bookkeeping before attaching the completed copy to its entry. +fn copied_buffer(start: u64, len: u64, size: u64, buffer: ID3D12Resource, data: *mut u8) -> Arc<Shadow> { + crate::host::name(&buffer, || format!("title buffer {:#x}+{len:#x}", start)); + // A big one, with `cards`: shaders get a buffer in the card's own + // memory, and the one just made is the CPU's side. + let (buffer, card) = match card_for(size) { + Some(on_card) => { + crate::host::name(&on_card, || format!("title buffer {:#x}+{len:#x} on the card", start)); tracing::info!( - start = format_args!("{:#x}", key.0), + start = format_args!("{:#x}", start), len, - "large buffer copied to the host" + "a buffer's host copy is in the card's memory" ); - } else { - tracing::debug!( - start = format_args!("{:#x}", key.0), - len, - "buffer copied to the host" - ); - } - let mut shadow = Shadow::new(buffer, data, gpu, key.0, len); - shadow.card = card; - let shadow = Arc::new(shadow); - if shadow.card.is_some() { - CARDED.lock().unwrap_or_else(|e| e.into_inner()).push(Arc::downgrade(&shadow)); + let card = Card { + staging: buffer, + before: Mutex::default(), + dirty: Mutex::default(), + has_dirty: AtomicBool::new(false), + sent: Mutex::default(), + has_sent: AtomicBool::new(false), + size, + }; + (on_card, Some(card)) } - entry.shadow = Some(shadow); + None => (buffer, None), + }; + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + if len >= 16 << 20 { + tracing::info!( + start = format_args!("{:#x}", start), + len, + "large buffer copied to the host" + ); + } else { + tracing::debug!( + start = format_args!("{:#x}", start), + len, + "buffer copied to the host" + ); } - entry.shadow.clone() + let mut shadow = Shadow::new(buffer, data, gpu, start, len); + shadow.card = card; + let shadow = Arc::new(shadow); + if shadow.card.is_some() { + CARDED.lock().unwrap_or_else(|e| e.into_inner()).push(Arc::downgrade(&shadow)); + } + shadow } +#[cfg(test)] +mod title_allocation_tests; + /// Titles also use memory outside any buffer object as GPU memory ( /// the title's interface vertices, from its own allocator). Such memory /// gets copies of the aligned windows it touches. diff --git a/crates/victory-gpu/src/shadow/title_allocation_tests.rs b/crates/victory-gpu/src/shadow/title_allocation_tests.rs new file mode 100644 index 00000000..72e40530 --- /dev/null +++ b/crates/victory-gpu/src/shadow/title_allocation_tests.rs @@ -0,0 +1,160 @@ +use super::*; +use std::sync::atomic::AtomicUsize; +use std::sync::mpsc::{Receiver, Sender, channel}; +use windows::Win32::Graphics::Direct3D12::D3D12_RANGE; +use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree}; + +const K64: usize = 64 << 10; + +struct Title(u64); +impl Title { + fn new() -> Self { + // SAFETY: private committed synthetic memory of two pages. + let p = unsafe { VirtualAlloc(std::ptr::null(), 2 * K64, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) }; + assert!(!p.is_null()); + Self(p as u64) + } + + fn fill(&self, value: u8) { + // SAFETY: fixture owns the full committed allocation. + unsafe { (self.0 as *mut u8).write_bytes(value, 2 * K64) }; + } +} + +impl Drop for Title { + fn drop(&mut self) { + unregister(1, self.0); + unregister(2, self.0 + K64 as u64); + // SAFETY: the fixture's private allocation, after workers joined. + unsafe { VirtualFree(self.0 as *mut _, 0, MEM_RELEASE) }; + } +} + +fn allocate(size: u64) -> Option<(ID3D12Resource, *mut u8)> { + host().expect("allocation fixture needs a D3D12 adapter").title_shared_buffer(size) +} + +fn delayed(ready: &Sender<()>, go: &Receiver<()>, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + let made = allocate(size); + ready.send(()).unwrap(); + go.recv().unwrap(); + made +} + +#[test] +fn an_unrelated_lookup_runs_while_a_fresh_shadow_is_pending() { + assert!(!crate::port::on() && crate::inplace::level() < 2); + let title = Title::new(); + let addr = title.0; + let other = addr + K64 as u64; + register(1, addr, K64 as u64); + register(2, other, K64 as u64); + let existing = lookup_with(other, 1, false, allocate).unwrap(); + let made = AtomicUsize::new(0); + std::thread::scope(|scope| { + let (ready, waiting) = channel(); + let (go, resume) = channel(); + let first = scope.spawn(move || { + lookup_with(addr, 1, false, |size| delayed(&ready, &resume, size)).unwrap() + }); + waiting.recv().unwrap(); + // Do not block in a negative control that keeps the global writer. + let unrelated = BUFFERS.try_read().ok().and_then(|map| map.get(&(other, 2))?.shadow.clone()); + let maker = &made; + let follower = scope.spawn(move || { + lookup_with(addr, 1, false, |size| { + maker.fetch_add(1, Ordering::Relaxed); + allocate(size) + }).unwrap() + }); + go.send(()).unwrap(); + let winner = first.join().unwrap(); + assert!(Arc::ptr_eq(&winner, &follower.join().unwrap())); + assert!(Arc::ptr_eq(&existing, &unrelated.expect("other entry must remain readable"))); + assert_eq!(made.load(Ordering::Relaxed), 0); + }); +} + +#[test] +fn a_pending_allocation_reselects_the_live_registration_and_refreshes_its_bytes() { + assert!(!crate::port::on() && crate::inplace::level() < 2); + for overlap in [false, true] { + let title = Title::new(); + title.fill(0x11); + let addr = title.0; + let ask = addr + K64 as u64 + 13; + register(1, addr, (2 * K64) as u64); + let made = AtomicUsize::new(0); + std::thread::scope(|scope| { + let (ready, waiting) = channel(); + let (go, resume) = channel(); + let count = &made; + let worker = scope.spawn(move || { + lookup_with(ask, 1, false, |size| { + if count.fetch_add(1, Ordering::Relaxed) == 0 { + delayed(&ready, &resume, size) + } else { + allocate(size) + } + }).unwrap() + }); + waiting.recv().unwrap(); + // Fail without leaving the worker waiting if allocation accidentally + // regains the global writer. + if BUFFERS.try_write().is_err() { + go.send(()).unwrap(); + worker.join().unwrap(); + panic!("registration must be able to change during allocation"); + } + if overlap { + register(2, addr + K64 as u64, K64 as u64); + } else { + unregister(1, addr); + register(1, addr, (2 * K64) as u64); + } + title.fill(0x65); + go.send(()).unwrap(); + let winner = worker.join().unwrap(); + assert_eq!(made.load(Ordering::Relaxed), 2, "obsolete backing must not be published"); + assert_eq!(winner.start, if overlap { addr + K64 as u64 } else { addr }); + // Exercise the submit-time refresh and read the GPU's view, not just + // the CPU mapping of the shadow. + let host = host().unwrap(); + let readback = host.read_back_buffer(K64 as u64).unwrap(); + let list = host.new_list().unwrap(); + let from = addr + K64 as u64; + winner.refresh(&list, from, K64 as u64); + // SAFETY: the requested page is inside the refreshed shadow. The + // destination is a live readback buffer in COPY_DEST. + unsafe { list.list.CopyBufferRegion(&readback, 0, &winner.buffer, from - winner.start, K64 as u64) }; + list.close(); + host.execute_sync_internal(&list); + let mut bytes = std::ptr::null_mut(); + let read = D3D12_RANGE { Begin: 0, End: K64 }; + let written = D3D12_RANGE { Begin: 0, End: 0 }; + // SAFETY: the submitting call waited for the copy. We read only + // the mapped allocation and do not write it. + let good = unsafe { + readback.Map(0, Some(&read), Some(&mut bytes)).unwrap(); + assert!(!bytes.is_null()); + let good = std::slice::from_raw_parts(bytes.cast::<u8>(), K64).iter().all(|&b| b == 0x65); + readback.Unmap(0, Some(&written)); + good + }; + assert!(good, "GPU readback did not see the live registration's bytes"); + assert!(host.log_messages().is_none(), "D3D12 reported validation errors"); + if overlap { + assert!(buffers_read().get(&(addr, 1)).unwrap().shadow.is_none()); + } + }); + } +} + +#[test] +fn an_allocation_failure_leaves_the_registration_open_to_retry() { + let title = Title::new(); + let addr = title.0; + register(1, addr, K64 as u64); + assert!(lookup_with(addr, 1, false, |_| None).is_none()); + assert!(lookup_with(addr, 1, false, allocate).is_some()); +} ```
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-27 08:32:31 +00:00
Author
Owner

@⁠TaynanGT on GitHub · 2026-11-27 09:03 UTC · original

@⁠NotADonky43 I’ve put your patch and readback tests in #199 and credited you on the commit. The range and ticket checks cover the case where a narrower registration wins during allocation. I gave the lock probes a short retry window so a parallel test briefly taking the table can’t trip them.

The drop in summed read-lock wait is worth following up. I’ll check the port’s readback and compare matched presents before drawing an FPS conclusion.

**@⁠TaynanGT** on GitHub · 2026-11-27 09:03 UTC · [original](https://github.com/TaynanGT/Vice-Tay/issues/196#issuecomment-7214230692) @⁠NotADonky43 I’ve put your patch and readback tests in #199 and credited you on the commit. The range and ticket checks cover the case where a narrower registration wins during allocation. I gave the lock probes a short retry window so a parallel test briefly taking the table can’t trip them. The drop in summed read-lock wait is worth following up. I’ll check the port’s readback and compare matched presents before drawing an FPS conclusion.
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/TaynanGT--Vice-Tay#196
No description provided.