Fresh VRAM heaps shorten the 64 KiB title-buffer allocation burst #404

Open
opened 2026-11-28 10:15:48 +00:00 by NotADonky43 · 3 comments
NotADonky43 commented 2026-11-28 10:15:48 +00:00 (Migrated from github.com)
Contributor

Imported from TaynanGT/Vice-Tay. Originally posted by NotADonky43 on 2026-11-28T10:15:48Z.


Experimental follow-up to #196/#199, tested separately on Vice-Tay fe7c6e52198f2070805ffafc4e55a7163291bad0. #199 reduces time holding the global buffer-table lock. This experiment reduces the number of D3D12 heap creation and residency calls instead. It applies only to the device-local side of registered title buffers, not the shared backing prepared by #178.

On an RTX 5070 Ti, the Series X opening allocated thousands of registered device-local buffers smaller than or equal to 64 KiB. In a title-free D3D12 benchmark (3,246 × 64 KiB buffers; six interleaved trials per path), median creation/residency/mapping time was 1,079 ms with one committed heap per buffer, 518 ms with committed residency in groups of 32, and 24 ms with 26 placed heaps. These figures describe allocation and mapping in the fixture, not the cost of the production allocator's additional initialization or the game's loading time.

The production prototype (b446069e) only issues never-used slots. It activates and zeros every slot, confirms the direct-queue fence before publication, and ties whole-heap ownership and budget charge to resource/heap lifetimes. It keeps the original committed allocator as a fallback and never returns an issued slot to the allocator. The native registered-path test passed byte-exact cross-queue readback before and after a 256-byte update and checked the budget charge while an independent resource reference outlived buffer unregister.

Game A/B: Same release executable, RTX 5070 Ti, Series X, 64 KiB registered-buffer placement profile and 4 GiB BAR, same precompiled shaders and initial D3D12 pipeline library. Only the fresh-heap switch changed. Enabled: 3,282 buffers issued from 31 heaps. The elapsed time between logged creation of the 500th and 3,200th small card copies fell from 4.24 s to 1.75 s. Both runs reached heavy rendering and exited normally with no logged device loss. This is one allocation-burst comparison, not a matched cutscene, steady FPS result, or claim of lower memory use. Both runs still had pipelines pending during heavy rendering. Long-run heap retention and visually matched load times remain unverified.

The source-only diff includes the native regression; no game files or game-derived artifacts are needed for that test. I’m sharing this as an experiment for review, not proposing it as a default yet.

Source-only patch against fe7c6e52 (includes native regression)
diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs
index f4fb7c95..c0247131 100644
--- a/crates/victory-gpu/src/host.rs
+++ b/crates/victory-gpu/src/host.rs
@@ -55,6 +55,7 @@ pub(crate) struct Host {
     next_rtv: AtomicU32,
     presenter: Mutex<Option<Presenter>>,
     title_stock: title_stock::Stock,
+    title_card_heaps: title_card_heap::Stock,
     /// The adapter the device is on, for its memory budget
     /// ([`Host::video_memory`]); `None` if the system does not name it.
     adapter: Option<IDXGIAdapter3>,
@@ -561,7 +562,13 @@ fn sweep() {
     }
     let host = host();
     let memory = host.and_then(|h| h.video_memory());
-    if let Some(host) = host { host.trim_title_stock(memory); }
+    if let Some(host) = host {
+        host.trim_title_stock(memory);
+        if title_card_heap::on() && (crate::residency::pressured()
+            || memory.is_some_and(|[budget, used, ..]| used >= budget / 100 * 97)) {
+            host.title_card_heaps.trim_unused();
+        }
+    }
     crate::pool::room(memory);
     crate::pipeline::trim_library();
     crate::shadow::let_go_idle();
@@ -1553,6 +1560,7 @@ fn create() -> windows::core::Result<Host> {
             next_rtv: AtomicU32::new(0),
             presenter: Mutex::new(None),
             title_stock: Default::default(),
+            title_card_heaps: Default::default(),
             adapter,
             fallback_view: OnceLock::new(),
             fallback_sampler: OnceLock::new(),
@@ -5276,6 +5284,7 @@ pub(crate) mod awake;
 mod mapping_fence;
 mod prelude_pool;
 mod title_stock;
+pub(crate) mod title_card_heap;
 mod card_steps;
 pub(crate) mod indirects;
 #[cfg(feature = "diagnostics")]
@@ -11348,6 +11357,7 @@ impl Meter {
                         per_frame(6) / 1e3
                     );
                 }
+                title_card_heap::report();
                 tracing::info!(
                     "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \
                      {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \
@@ -12200,6 +12210,13 @@ impl Host {
         }
     }
 
+    pub(crate) fn fresh_title_card_buffer(&self, size: u64, committed: u64, most: u64, hundredths: u64)
+        -> Option<ID3D12Resource>
+    {
+        if size != title_card_heap::SLOT || !title_card_heap::on() { return None; }
+        self.title_card_heaps.take(self, committed, most, hundredths)
+    }
+
     /// A device-local buffer shaders may write (unordered access) and indirect
     /// execution may read, starting in the common state.
     pub(crate) fn uav_buffer(&self, size: u64) -> Option<ID3D12Resource> {
diff --git a/crates/victory-gpu/src/host/mapping_fence.rs b/crates/victory-gpu/src/host/mapping_fence.rs
index 47283fe3..746f4151 100644
--- a/crates/victory-gpu/src/host/mapping_fence.rs
+++ b/crates/victory-gpu/src/host/mapping_fence.rs
@@ -25,15 +25,20 @@ pub(super) struct Progress {
 }
 
 impl Progress {
+    pub(super) fn finish(&mut self, mut confirm: impl FnMut(u64, Attempt) -> Result<()>) -> Result<()> {
+        if let Some(attempt) = self.pending {
+            self.check(attempt, &mut confirm)?;
+        }
+        Ok(())
+    }
+
     pub(super) fn run(
         &mut self,
         submit: impl FnOnce(),
         mut confirm: impl FnMut(u64, Attempt) -> Result<()>,
     ) -> Result<()> {
-        if let Some(attempt) = self.pending {
-            // Confirm the previous marker before using the reusable list again.
-            self.check(attempt, &mut confirm)?;
-        }
+        // Confirm the previous marker before using the reusable list again.
+        self.finish(&mut confirm)?;
         self.value = self
             .value
             .checked_add(1)
diff --git a/crates/victory-gpu/src/host/title_card_heap.rs b/crates/victory-gpu/src/host/title_card_heap.rs
new file mode 100644
index 00000000..ef021d86
--- /dev/null
+++ b/crates/victory-gpu/src/host/title_card_heap.rs
@@ -0,0 +1,336 @@
+//! Fresh-only device-local title buffers. Only the registered 64 KiB path
+//! uses this allocator; a declined allocation falls back to the committed path.
+use super::*;
+use std::sync::atomic::AtomicU64;
+use windows::Win32::Graphics::Direct3D::ID3DDestructionNotifier;
+use windows::core::GUID;
+
+pub(super) const SLOT: u64 = 64 << 10;
+const BLOCK: u64 = 128 * SLOT;
+static BYTES: AtomicU64 = AtomicU64::new(0);
+static BLOCKS: AtomicU64 = AtomicU64::new(0);
+static ISSUED: AtomicU64 = AtomicU64::new(0);
+
+pub(crate) fn bytes() -> u64 { BYTES.load(Ordering::Relaxed) }
+
+pub(super) fn on() -> bool {
+    static ON: OnceLock<bool> = OnceLock::new();
+    *ON.get_or_init(|| std::env::var_os("VICTORY_TITLE_CARD_HEAPS").is_some_and(|value| value == "1"))
+}
+
+fn block_size(cap_available: u64, local_available: u64) -> u64 {
+    BLOCK.min(cap_available).min(local_available) / SLOT * SLOT
+}
+
+/// Charge the physical allocation, including unused or retired slots. The
+/// notification cannot take a lock: it may run inside any COM release.
+struct Charge(u64);
+impl Drop for Charge {
+    fn drop(&mut self) { BYTES.fetch_sub(self.0, Ordering::Relaxed); }
+}
+
+unsafe extern "system" fn release_charge(data: *mut std::ffi::c_void) {
+    // SAFETY: one Charge is transferred to the notifier by track().
+    drop(unsafe { Box::from_raw(data.cast::<Charge>()) });
+}
+
+fn track(heap: &ID3D12Heap, charge: Charge) -> windows::core::Result<()> {
+    let notifier: ID3DDestructionNotifier = heap.cast()?;
+    let data = Box::into_raw(Box::new(charge));
+    // SAFETY: one owned charge, reclaimed here if registration fails.
+    if let Err(error) = unsafe { notifier.RegisterDestructionCallback(Some(release_charge), data.cast()) } {
+        // SAFETY: the callback was not registered.
+        drop(unsafe { Box::from_raw(data) });
+        return Err(error);
+    }
+    Ok(())
+}
+
+struct Init {
+    queue: ID3D12CommandQueue,
+    fence: ID3D12Fence,
+    event: HANDLE,
+    progress: mapping_fence::Progress,
+    // A failed confirmation is not proof that it is safe to release objects.
+    pending: Option<Recorded>,
+}
+
+// SAFETY: D3D12 objects are free-threaded and the event is used under Stock's mutex.
+unsafe impl Send for Init {}
+
+impl Drop for Init {
+    fn drop(&mut self) {
+        if self.pending.is_none() {
+            // SAFETY: no armed pending wait; Init owns this event.
+            let _ = unsafe { windows::Win32::Foundation::CloseHandle(self.event) };
+        } else if let Some(pending) = self.pending.take() {
+            // The singleton is process-owned. Even if dropped after an API
+            // failure, never destroy objects whose work remains unconfirmed.
+            std::mem::forget(pending);
+        }
+    }
+}
+
+struct Recorded {
+    list: ID3D12CommandList,
+    _allocator: ID3D12CommandAllocator,
+    _zero: ID3D12Resource,
+    buffers: Vec<ID3D12Resource>,
+}
+
+impl Init {
+    fn new(host: &Host) -> windows::core::Result<Self> {
+        // SAFETY: plain private direct queue, fence and event creation.
+        unsafe {
+            Ok(Self {
+                queue: host.device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
+                    Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default()
+                })?,
+                fence: host.device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?,
+                event: CreateEventW(None, false, false, None)?,
+                progress: Default::default(),
+                pending: None,
+            })
+        }
+    }
+
+    fn retire_pending(&mut self, host: &Host) -> windows::core::Result<()> {
+        if self.pending.is_some() {
+            self.progress.finish(|value, attempt| {
+                mapping_fence::confirm(&host.device, &self.queue, &self.fence, self.event, value, attempt)
+            })?;
+            self.pending = None;
+        }
+        Ok(())
+    }
+
+    fn initialize(&mut self, host: &Host, recorded: Recorded) -> windows::core::Result<Vec<ID3D12Resource>> {
+        debug_assert!(self.pending.is_none());
+        self.pending = Some(recorded);
+        let list = &self.pending.as_ref().expect("new initialization").list;
+        self.progress.run(
+            // SAFETY: a closed list, retained with all referenced objects.
+            || unsafe { self.queue.ExecuteCommandLists(&[Some(list.clone())]) },
+            |value, attempt| mapping_fence::confirm(&host.device, &self.queue, &self.fence, self.event, value, attempt),
+        )?;
+        Ok(self.pending.take().expect("completed initialization").buffers)
+    }
+}
+
+#[derive(Default)]
+pub(super) struct Stock(Mutex<State>);
+
+#[derive(Default)]
+struct State {
+    initialized: Vec<ID3D12Resource>,
+    init: Option<Init>,
+}
+
+fn fresh(host: &Host, size: u64) -> windows::core::Result<Recorded> {
+    const HEAP_KEY: GUID = GUID::from_u128(0x519dc19e_aa81_4cd8_a150_01d4b992c1bc);
+    let device = &host.device;
+    let properties = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() };
+    let desc = D3D12_RESOURCE_DESC {
+        Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
+        Width: SLOT, Height: 1, DepthOrArraySize: 1, MipLevels: 1,
+        SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+        Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
+        Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
+        ..Default::default()
+    };
+    let no_resource = windows::core::Error::empty;
+    // SAFETY: valid descriptor and a live host device.
+    let info = unsafe { device.GetResourceAllocationInfo(0, &[desc]) };
+    if info.SizeInBytes != SLOT || info.Alignment != SLOT { return Err(no_resource()); }
+    let heap_desc = D3D12_HEAP_DESC {
+        SizeInBytes: size, Properties: properties, Alignment: 0,
+        Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS | not_resident(),
+    };
+    BYTES.fetch_add(size, Ordering::Relaxed);
+    let charge = Charge(size);
+    let mut heap: Option<ID3D12Heap> = None;
+    // SAFETY: buffer-only heap, fully charged before allocation.
+    unsafe { device.CreateHeap(&heap_desc, &mut heap) }?;
+    let heap = heap.ok_or_else(no_resource)?;
+    track(&heap, charge)?;
+    resident(device, &heap)?;
+    mapped(device)?;
+
+    let (zero, pointer) = host.upload_buffer(SLOT).ok_or_else(no_resource)?;
+    if pointer.is_null() { return Err(no_resource()); }
+    // SAFETY: one entire mapped 64 KiB upload slot, not yet exposed to the GPU.
+    unsafe { pointer.write_bytes(0, SLOT as usize) };
+    // SAFETY: a private direct command list using a dedicated allocator.
+    let (allocator, list): (ID3D12CommandAllocator, ID3D12GraphicsCommandList) = unsafe {
+        let allocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
+        let list = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?;
+        (allocator, list)
+    };
+    let mut buffers = Vec::with_capacity((size / SLOT) as usize);
+    for offset in (0..size).step_by(SLOT as usize) {
+        let mut buffer: Option<ID3D12Resource> = None;
+        // SAFETY: distinct aligned slots within an owned DEFAULT heap.
+        unsafe { device.CreatePlacedResource(&heap, offset, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buffer) }?;
+        let buffer = buffer.ok_or_else(no_resource)?;
+        // SAFETY: keep the heap alive with the resource, not just its Shadow.
+        // Descriptors and retired/in-flight lists can own independent COM refs.
+        unsafe { buffer.SetPrivateDataInterface(&HEAP_KEY, &heap) }?;
+        // SAFETY: borrowed pointer, as in host::transition(); the buffer and
+        // heap remain alive through the confirmed activation submission.
+        let after = unsafe { std::mem::transmute_copy(&buffer) };
+        // SAFETY: private list and live pageables. Explicit initialization
+        // covers rounded bytes, and returns the buffer to COMMON before use.
+        unsafe {
+            list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER {
+                Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING,
+                Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
+                Anonymous: D3D12_RESOURCE_BARRIER_0 {
+                    Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER {
+                        pResourceBefore: std::mem::ManuallyDrop::new(None), pResourceAfter: after,
+                    }),
+                },
+            }, transition(&buffer, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST)]);
+            list.CopyBufferRegion(&buffer, 0, &zero, 0, SLOT);
+            list.ResourceBarrier(&[transition(&buffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON)]);
+        }
+        buffers.push(buffer);
+    }
+    // SAFETY: the list was created open. It is not submitted here.
+    unsafe { list.Close() }?;
+    Ok(Recorded { list: list.cast()?, _allocator: allocator, _zero: zero, buffers })
+}
+
+impl Stock {
+    /// All registered buffer allocators are serialized by the title table
+    /// writer. `committed` excludes already charged heap memory.
+    pub(super) fn take(&self, host: &Host, committed: u64, most: u64, hundredths: u64) -> Option<ID3D12Resource> {
+        let mut state = self.0.lock().unwrap_or_else(|e| e.into_inner());
+        if let Some(buffer) = state.initialized.pop() {
+            ISSUED.fetch_add(1, Ordering::Relaxed);
+            return Some(buffer);
+        }
+        let [budget, used, ..] = host.video_memory()?;
+        let available = (budget / 100 * hundredths).saturating_sub(used);
+        let size = block_size(most.saturating_sub(committed.saturating_add(bytes())), available);
+        // A block must save at least one physical allocation.
+        if size <= SLOT { return None; }
+        let fill = (|| -> windows::core::Result<_> {
+            if state.init.is_none() { state.init = Some(Init::new(host)?); }
+            let init = state.init.as_mut().expect("initialization queue");
+            init.retire_pending(host)?;
+            init.initialize(host, fresh(host, size)?)
+        })();
+        match fill {
+            Ok(mut initialized) => {
+                let next = initialized.pop();
+                state.initialized = initialized;
+                BLOCKS.fetch_add(1, Ordering::Relaxed);
+                ISSUED.fetch_add(1, Ordering::Relaxed);
+                next
+            }
+            Err(error) => {
+                tracing::warn!(%error, "fresh title card heap not ready; using committed allocation");
+                None
+            }
+        }
+    }
+
+    pub(super) fn trim_unused(&self) {
+        if let Ok(mut state) = self.0.try_lock() {
+            // Do not return an issued range to the stock. If any issued
+            // resource still exists the heap stays charged and alive.
+            let unused = std::mem::take(&mut state.initialized);
+            drop(state);
+            drop(unused);
+        }
+    }
+}
+
+pub(super) fn report() {
+    if on() {
+        tracing::info!(heaps = BLOCKS.load(Ordering::Relaxed), issued = ISSUED.load(Ordering::Relaxed),
+            bytes = bytes(), "fresh registered card heaps");
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn block_size_obeys_the_existing_limits() {
+        assert_eq!(block_size(BLOCK * 2, BLOCK * 3), BLOCK);
+        assert_eq!(block_size(5 * SLOT - 1, BLOCK), 4 * SLOT);
+        assert_eq!(block_size(BLOCK, 3 * SLOT + 2), 3 * SLOT);
+        assert_eq!(block_size(SLOT - 1, BLOCK), 0);
+    }
+
+    #[test]
+    #[ignore = "run in isolation with the RTX hardware and the 64 KiB buffer profile"]
+    fn registered_shadow_is_initialized_before_publication_and_heap_tracks_last_reference() {
+        use crate::shadow;
+        use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree};
+
+        assert!(cfg!(feature = "diagnostics") && on() && crate::switch::on("VICTORY_D3D12_GBV"));
+        let host = host().expect("native D3D12 host");
+        assert!(host.messages.is_some());
+        assert_eq!(host.adapter_vendor_id(), Some(0x10de));
+        assert_eq!(bytes(), 0);
+        // SAFETY: one synthetic private page with no guest dependencies.
+        let title = unsafe { VirtualAlloc(std::ptr::null(), SLOT as usize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) };
+        assert!(!title.is_null());
+        const AT: usize = 4096;
+        const LEN: usize = 256;
+        // SAFETY: the fixture owns at least AT+LEN bytes in this mapping.
+        unsafe { title.cast::<u8>().add(AT).write_bytes(0x52, LEN) };
+        shadow::register(1, title as u64, SLOT);
+        let shadow = shadow::find(title as u64, SLOT).expect("registered shadow");
+        assert_eq!(ISSUED.load(Ordering::Relaxed), 1, "must not silently use the committed fallback");
+        assert_eq!(bytes(), BLOCK, "unissued capacity is charged as well");
+
+        let (upload, data) = host.upload_buffer(LEN as u64).expect("partial upload");
+        let readback = host.read_back_buffer(2 * SLOT).expect("readback");
+        let list = host.new_list().expect("direct list");
+        let buffer = &shadow.buffer;
+        assert!(!data.is_null());
+        // SAFETY: initialized input and disjoint output spans. The real
+        // published resource is accessed by a different queue than the
+        // initializer: first a read of the entire slot, then a partial write.
+        unsafe {
+            std::ptr::copy_nonoverlapping(title.cast::<u8>().add(AT), data, LEN);
+            list.list.ResourceBarrier(&[transition(buffer, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
+            list.list.CopyBufferRegion(&readback, 0, buffer, 0, SLOT);
+            list.list.ResourceBarrier(&[transition(buffer, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COPY_DEST)]);
+            list.list.CopyBufferRegion(buffer, AT as u64, &upload, 0, LEN as u64);
+            list.list.ResourceBarrier(&[transition(buffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
+            list.list.CopyBufferRegion(&readback, SLOT, buffer, 0, SLOT);
+        }
+        list.close();
+        host.execute_sync_internal(&list);
+        assert!(host.log_messages().is_none());
+        // SAFETY: the native copy completed. Only read the exact mapped output.
+        unsafe {
+            host.device.GetDeviceRemovedReason().unwrap();
+            let mut data = std::ptr::null_mut();
+            readback.Map(0, Some(&D3D12_RANGE { Begin: 0, End: (2 * SLOT) as usize }), Some(&mut data)).unwrap();
+            assert!(!data.is_null());
+            let output = std::slice::from_raw_parts(data.cast::<u8>(), (2 * SLOT) as usize);
+            let initial = output[..SLOT as usize].iter().all(|&b| b == 0);
+            let partial = output[SLOT as usize..].iter().enumerate().all(|(i, &b)| b == if (AT..AT+LEN).contains(&i) { 0x52 } else { 0 });
+            readback.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 0 }));
+            assert!(initial && partial, "fresh registered data must match the committed path");
+        }
+
+        let slot_owner = shadow.buffer.clone();
+        shadow::unregister(1, title as u64);
+        drop(shadow);
+        drop(list);
+        host.title_card_heaps.trim_unused();
+        assert_eq!(bytes(), BLOCK, "a descriptor's resource still retains its heap");
+        drop(slot_owner);
+        assert_eq!(bytes(), 0, "physical charge returns when the last resource goes");
+        // SAFETY: this was the private synthetic mapping and it is no longer tracked.
+        assert_ne!(unsafe { VirtualFree(title, 0, MEM_RELEASE) }, 0);
+        println!("FRESH_HEAP_GPU_PASS initial=65536 partial=65536 lifetime=exact");
+    }
+}
diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs
index 0a785f0e..5b9c8984 100644
--- a/crates/victory-gpu/src/shadow.rs
+++ b/crates/victory-gpu/src/shadow.rs
@@ -498,6 +498,8 @@ struct Card {
     has_sent: AtomicBool,
     /// The buffers' bytes (the title buffer's, rounded up to 64 KiB).
     size: u64,
+    /// A fresh placed slot contributes via its entire physical heap instead.
+    heap_backed: bool,
 }
 
 /// Whether the host copies of big title buffers are in the card's own
@@ -629,6 +631,10 @@ fn parse_mib(value: &str) -> Option<u64> {
 /// Bytes alive of copies' card sides, and of their "before" twins.
 static CARD_BYTES: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
 
+fn card_buffer_bytes() -> u64 {
+    CARD_BYTES[0].load(Ordering::Relaxed) + crate::host::title_card_heap::bytes()
+}
+
 /// Bytes of title-memory-by-address (RT BVH) arenas placed in local VRAM.
 static BY_ADDRESS_CARD_BYTES: AtomicU64 = AtomicU64::new(0);
 
@@ -637,7 +643,7 @@ static BY_ADDRESS_CARD_BYTES: AtomicU64 = AtomicU64::new(0);
 pub(crate) fn vram_breakdown() -> [u64; 2] {
     let bvh = BY_ADDRESS_CARD_BYTES.load(Ordering::Relaxed);
     let win = WINDOW_CARD_BYTES.load(Ordering::Relaxed).saturating_sub(bvh);
-    let buf = CARD_BYTES[0].load(Ordering::Relaxed)
+    let buf = card_buffer_bytes()
         + CARD_BYTES[1].load(Ordering::Relaxed)
         + win
         + WINDOW_MAPPED_BYTES.load(Ordering::Relaxed);
@@ -706,7 +712,7 @@ pub(crate) fn card_room_kept() -> u64 {
     );
     remaining_card_room(
         buffers,
-        CARD_BYTES[0].load(Ordering::Relaxed),
+        card_buffer_bytes(),
         CARD_REFUSED[1].load(Ordering::Relaxed),
         windows,
         WINDOW_CARD_BYTES.load(Ordering::Relaxed),
@@ -736,7 +742,7 @@ static CARDED: Mutex<Vec<std::sync::Weak<Shadow>>> = Mutex::new(Vec::new());
 pub(crate) static CARD_STATS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7];
 
 pub(crate) fn live_span_bytes() -> u64 {
-    CARD_BYTES[0].load(Ordering::Relaxed)
+    card_buffer_bytes()
         + WINDOW_CARD_BYTES.load(Ordering::Relaxed)
         + WINDOW_MAPPED_BYTES.load(Ordering::Relaxed)
 }
@@ -749,7 +755,7 @@ pub(crate) fn card_stats() -> [u64; 10] {
         out[i] = stat.swap(0, Ordering::Relaxed);
     }
     out[7] = CARDED.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|w| w.strong_count() > 0).count() as u64;
-    out[8] = CARD_BYTES[0].load(Ordering::Relaxed)
+    out[8] = card_buffer_bytes()
         + WINDOW_CARD_BYTES.load(Ordering::Relaxed)
         + WINDOW_MAPPED_BYTES.load(Ordering::Relaxed);
     out[9] = CARD_BYTES[1].load(Ordering::Relaxed);
@@ -767,7 +773,7 @@ pub(crate) fn card_hash_bytes(size: u64) -> u64 {
 /// copy, if the copy is to be there: [`cards`] is on, the size is within
 /// [`card_limits`] and below 1 GiB (the compare counts in 32 bits), and the
 /// host has what it takes (`Host::card_ready`).
-fn card_for(size: u64) -> Option<ID3D12Resource> {
+fn card_for(size: u64) -> Option<(ID3D12Resource, bool)> {
     let there = card_room_for(size);
     if there.is_some() || !card_all() || size >= 1 << 30 {
         return there;
@@ -779,7 +785,7 @@ fn card_for(size: u64) -> Option<ID3D12Resource> {
     }
     let (buffer, _) = host.shared_buffer(size)?;
     CARD_BYTES[0].fetch_add(size, Ordering::Relaxed);
-    Some(buffer)
+    Some((buffer, false))
 }
 
 /// Whether every title buffer's copy has two sides, however small
@@ -797,7 +803,7 @@ fn card_all() -> bool {
 }
 
 /// [`card_for`] in the card's own memory.
-fn card_room_for(size: u64) -> Option<ID3D12Resource> {
+fn card_room_for(size: u64) -> Option<(ID3D12Resource, bool)> {
     if !cards() {
         return None;
     }
@@ -816,6 +822,10 @@ fn card_room_for(size: u64) -> Option<ID3D12Resource> {
     // With room reserved for buffers, local usage including the new copy
     // may reach 97% of the reported budget. Disabling the reservation uses 80%.
     let hundredths = if card_room_kept_on() { 97 } else { 80 };
+    if let Some(fresh) = host.fresh_title_card_buffer(size, CARD_BYTES[0].load(Ordering::Relaxed), most, hundredths) {
+        // Already admitted, fully charged, initialized, and confirmed.
+        return Some((fresh, true));
+    }
     if let Some([budget, used, ..]) = host.video_memory()
         && used + size > budget / 100 * hundredths
     {
@@ -832,7 +842,7 @@ fn card_room_for(size: u64) -> Option<ID3D12Resource> {
                 used >> 20,
                 budget >> 20,
                 (budget / 100 * hundredths) >> 20,
-                CARD_BYTES[0].load(Ordering::Relaxed) >> 20,
+                card_buffer_bytes() >> 20,
                 most >> 20,
                 n,
                 bytes >> 20,
@@ -841,7 +851,7 @@ fn card_room_for(size: u64) -> Option<ID3D12Resource> {
         }
         return None;
     }
-    if CARD_BYTES[0].fetch_add(size, Ordering::Relaxed) + size > most {
+    if CARD_BYTES[0].fetch_add(size, Ordering::Relaxed) + crate::host::title_card_heap::bytes() + size > most {
         CARD_BYTES[0].fetch_sub(size, Ordering::Relaxed);
         return None;
     }
@@ -849,7 +859,7 @@ fn card_room_for(size: u64) -> Option<ID3D12Resource> {
     if buffer.is_none() {
         CARD_BYTES[0].fetch_sub(size, Ordering::Relaxed);
     }
-    buffer
+    buffer.map(|buffer| (buffer, false))
 }
 
 /// The most bytes of windows outside buffers whose copies go to the card's
@@ -3478,7 +3488,7 @@ impl Drop for Shadow {
         if let Some(card) = &mut self.card {
             if window {
                 WINDOW_CARD_BYTES.fetch_sub(card.size, Ordering::Relaxed);
-            } else {
+            } else if !card.heap_backed {
                 CARD_BYTES[0].fetch_sub(card.size, Ordering::Relaxed);
             }
             if card.before.get_mut().unwrap_or_else(|e| e.into_inner()).is_some() {
@@ -5569,6 +5579,7 @@ impl Shadow {
                 sent: Mutex::default(),
                 has_sent: AtomicBool::new(false),
                 size: len.next_multiple_of(PIECE as u64),
+                heap_backed: false,
             });
         }
         let shadow = Arc::new(shadow);
@@ -5766,6 +5777,7 @@ mod land_tests {
             sent: Mutex::default(),
             has_sent: AtomicBool::new(false),
             size: len as u64,
+            heap_backed: false,
         });
         Some(shadow)
     }
@@ -6179,7 +6191,7 @@ fn lookup(address: u64, len: u64, any: bool) -> Option<Arc<Shadow>> {
         // 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) => {
+            Some((on_card, heap_backed)) => {
                 crate::host::name(&on_card, || format!("title buffer {:#x}+{len:#x} on the card", key.0));
                 tracing::info!(
                     start = format_args!("{:#x}", key.0),
@@ -6194,6 +6206,7 @@ fn lookup(address: u64, len: u64, any: bool) -> Option<Arc<Shadow>> {
                     sent: Mutex::default(),
                     has_sent: AtomicBool::new(false),
                     size,
+                    heap_backed,
                 };
                 (on_card, Some(card))
             }
@@ -6426,6 +6439,7 @@ pub(crate) fn by_address(start: u64, len: u64) -> Option<Arc<Shadow>> {
         sent: Mutex::default(),
         has_sent: AtomicBool::new(false),
         size: len,
+        heap_backed: false,
     });
     let shadow = Arc::new(shadow);
     CARDED.lock().unwrap_or_else(|e| e.into_inner()).push(Arc::downgrade(&shadow));
@@ -6504,6 +6518,7 @@ fn build_loose_shadow(start: u64, len: u64, backing: LooseBacking) -> Arc<Shadow
                         sent: Mutex::default(),
                         has_sent: AtomicBool::new(false),
                         size: len,
+                        heap_backed: false,
                     };
                     (on_card, Some(card))
                 }
<!-- greyfinch-sync:TaynanGT/Vice-Tay:issue:6663263261 --> Imported from [TaynanGT/Vice-Tay](https://github.com/TaynanGT/Vice-Tay/issues/404). Originally posted by [NotADonky43](https://github.com/NotADonky43) on 2026-11-28T10:15:48Z. --- Experimental follow-up to #196/#199, tested separately on Vice-Tay `fe7c6e52198f2070805ffafc4e55a7163291bad0`. #199 reduces time holding the global buffer-table lock. This experiment reduces the number of D3D12 heap creation and residency calls instead. It applies only to the device-local side of registered title buffers, not the shared backing prepared by #178. On an RTX 5070 Ti, the Series X opening allocated thousands of registered device-local buffers smaller than or equal to 64 KiB. In a title-free D3D12 benchmark (3,246 × 64 KiB buffers; six interleaved trials per path), median creation/residency/mapping time was 1,079 ms with one committed heap per buffer, 518 ms with committed residency in groups of 32, and 24 ms with 26 placed heaps. These figures describe allocation and mapping in the fixture, not the cost of the production allocator's additional initialization or the game's loading time. The production prototype (`b446069e`) only issues never-used slots. It activates and zeros every slot, confirms the direct-queue fence before publication, and ties whole-heap ownership and budget charge to resource/heap lifetimes. It keeps the original committed allocator as a fallback and never returns an issued slot to the allocator. The native registered-path test passed byte-exact cross-queue readback before and after a 256-byte update and checked the budget charge while an independent resource reference outlived buffer unregister. **Game A/B:** Same release executable, RTX 5070 Ti, Series X, 64 KiB registered-buffer placement profile and 4 GiB BAR, same precompiled shaders and initial D3D12 pipeline library. Only the fresh-heap switch changed. Enabled: 3,282 buffers issued from 31 heaps. The elapsed time between logged creation of the 500th and 3,200th small card copies fell from **4.24 s to 1.75 s**. Both runs reached heavy rendering and exited normally with no logged device loss. This is one allocation-burst comparison, not a matched cutscene, steady FPS result, or claim of lower memory use. Both runs still had pipelines pending during heavy rendering. Long-run heap retention and visually matched load times remain unverified. The source-only diff includes the native regression; no game files or game-derived artifacts are needed for that test. I’m sharing this as an experiment for review, not proposing it as a default yet. <details> <summary>Source-only patch against fe7c6e52 (includes native regression)</summary> ```diff diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index f4fb7c95..c0247131 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -55,6 +55,7 @@ pub(crate) struct Host { next_rtv: AtomicU32, presenter: Mutex<Option<Presenter>>, title_stock: title_stock::Stock, + title_card_heaps: title_card_heap::Stock, /// The adapter the device is on, for its memory budget /// ([`Host::video_memory`]); `None` if the system does not name it. adapter: Option<IDXGIAdapter3>, @@ -561,7 +562,13 @@ fn sweep() { } let host = host(); let memory = host.and_then(|h| h.video_memory()); - if let Some(host) = host { host.trim_title_stock(memory); } + if let Some(host) = host { + host.trim_title_stock(memory); + if title_card_heap::on() && (crate::residency::pressured() + || memory.is_some_and(|[budget, used, ..]| used >= budget / 100 * 97)) { + host.title_card_heaps.trim_unused(); + } + } crate::pool::room(memory); crate::pipeline::trim_library(); crate::shadow::let_go_idle(); @@ -1553,6 +1560,7 @@ fn create() -> windows::core::Result<Host> { next_rtv: AtomicU32::new(0), presenter: Mutex::new(None), title_stock: Default::default(), + title_card_heaps: Default::default(), adapter, fallback_view: OnceLock::new(), fallback_sampler: OnceLock::new(), @@ -5276,6 +5284,7 @@ pub(crate) mod awake; mod mapping_fence; mod prelude_pool; mod title_stock; +pub(crate) mod title_card_heap; mod card_steps; pub(crate) mod indirects; #[cfg(feature = "diagnostics")] @@ -11348,6 +11357,7 @@ impl Meter { per_frame(6) / 1e3 ); } + title_card_heap::report(); tracing::info!( "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \ {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \ @@ -12200,6 +12210,13 @@ impl Host { } } + pub(crate) fn fresh_title_card_buffer(&self, size: u64, committed: u64, most: u64, hundredths: u64) + -> Option<ID3D12Resource> + { + if size != title_card_heap::SLOT || !title_card_heap::on() { return None; } + self.title_card_heaps.take(self, committed, most, hundredths) + } + /// A device-local buffer shaders may write (unordered access) and indirect /// execution may read, starting in the common state. pub(crate) fn uav_buffer(&self, size: u64) -> Option<ID3D12Resource> { diff --git a/crates/victory-gpu/src/host/mapping_fence.rs b/crates/victory-gpu/src/host/mapping_fence.rs index 47283fe3..746f4151 100644 --- a/crates/victory-gpu/src/host/mapping_fence.rs +++ b/crates/victory-gpu/src/host/mapping_fence.rs @@ -25,15 +25,20 @@ pub(super) struct Progress { } impl Progress { + pub(super) fn finish(&mut self, mut confirm: impl FnMut(u64, Attempt) -> Result<()>) -> Result<()> { + if let Some(attempt) = self.pending { + self.check(attempt, &mut confirm)?; + } + Ok(()) + } + pub(super) fn run( &mut self, submit: impl FnOnce(), mut confirm: impl FnMut(u64, Attempt) -> Result<()>, ) -> Result<()> { - if let Some(attempt) = self.pending { - // Confirm the previous marker before using the reusable list again. - self.check(attempt, &mut confirm)?; - } + // Confirm the previous marker before using the reusable list again. + self.finish(&mut confirm)?; self.value = self .value .checked_add(1) diff --git a/crates/victory-gpu/src/host/title_card_heap.rs b/crates/victory-gpu/src/host/title_card_heap.rs new file mode 100644 index 00000000..ef021d86 --- /dev/null +++ b/crates/victory-gpu/src/host/title_card_heap.rs @@ -0,0 +1,336 @@ +//! Fresh-only device-local title buffers. Only the registered 64 KiB path +//! uses this allocator; a declined allocation falls back to the committed path. +use super::*; +use std::sync::atomic::AtomicU64; +use windows::Win32::Graphics::Direct3D::ID3DDestructionNotifier; +use windows::core::GUID; + +pub(super) const SLOT: u64 = 64 << 10; +const BLOCK: u64 = 128 * SLOT; +static BYTES: AtomicU64 = AtomicU64::new(0); +static BLOCKS: AtomicU64 = AtomicU64::new(0); +static ISSUED: AtomicU64 = AtomicU64::new(0); + +pub(crate) fn bytes() -> u64 { BYTES.load(Ordering::Relaxed) } + +pub(super) fn on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TITLE_CARD_HEAPS").is_some_and(|value| value == "1")) +} + +fn block_size(cap_available: u64, local_available: u64) -> u64 { + BLOCK.min(cap_available).min(local_available) / SLOT * SLOT +} + +/// Charge the physical allocation, including unused or retired slots. The +/// notification cannot take a lock: it may run inside any COM release. +struct Charge(u64); +impl Drop for Charge { + fn drop(&mut self) { BYTES.fetch_sub(self.0, Ordering::Relaxed); } +} + +unsafe extern "system" fn release_charge(data: *mut std::ffi::c_void) { + // SAFETY: one Charge is transferred to the notifier by track(). + drop(unsafe { Box::from_raw(data.cast::<Charge>()) }); +} + +fn track(heap: &ID3D12Heap, charge: Charge) -> windows::core::Result<()> { + let notifier: ID3DDestructionNotifier = heap.cast()?; + let data = Box::into_raw(Box::new(charge)); + // SAFETY: one owned charge, reclaimed here if registration fails. + if let Err(error) = unsafe { notifier.RegisterDestructionCallback(Some(release_charge), data.cast()) } { + // SAFETY: the callback was not registered. + drop(unsafe { Box::from_raw(data) }); + return Err(error); + } + Ok(()) +} + +struct Init { + queue: ID3D12CommandQueue, + fence: ID3D12Fence, + event: HANDLE, + progress: mapping_fence::Progress, + // A failed confirmation is not proof that it is safe to release objects. + pending: Option<Recorded>, +} + +// SAFETY: D3D12 objects are free-threaded and the event is used under Stock's mutex. +unsafe impl Send for Init {} + +impl Drop for Init { + fn drop(&mut self) { + if self.pending.is_none() { + // SAFETY: no armed pending wait; Init owns this event. + let _ = unsafe { windows::Win32::Foundation::CloseHandle(self.event) }; + } else if let Some(pending) = self.pending.take() { + // The singleton is process-owned. Even if dropped after an API + // failure, never destroy objects whose work remains unconfirmed. + std::mem::forget(pending); + } + } +} + +struct Recorded { + list: ID3D12CommandList, + _allocator: ID3D12CommandAllocator, + _zero: ID3D12Resource, + buffers: Vec<ID3D12Resource>, +} + +impl Init { + fn new(host: &Host) -> windows::core::Result<Self> { + // SAFETY: plain private direct queue, fence and event creation. + unsafe { + Ok(Self { + queue: host.device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() + })?, + fence: host.device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?, + event: CreateEventW(None, false, false, None)?, + progress: Default::default(), + pending: None, + }) + } + } + + fn retire_pending(&mut self, host: &Host) -> windows::core::Result<()> { + if self.pending.is_some() { + self.progress.finish(|value, attempt| { + mapping_fence::confirm(&host.device, &self.queue, &self.fence, self.event, value, attempt) + })?; + self.pending = None; + } + Ok(()) + } + + fn initialize(&mut self, host: &Host, recorded: Recorded) -> windows::core::Result<Vec<ID3D12Resource>> { + debug_assert!(self.pending.is_none()); + self.pending = Some(recorded); + let list = &self.pending.as_ref().expect("new initialization").list; + self.progress.run( + // SAFETY: a closed list, retained with all referenced objects. + || unsafe { self.queue.ExecuteCommandLists(&[Some(list.clone())]) }, + |value, attempt| mapping_fence::confirm(&host.device, &self.queue, &self.fence, self.event, value, attempt), + )?; + Ok(self.pending.take().expect("completed initialization").buffers) + } +} + +#[derive(Default)] +pub(super) struct Stock(Mutex<State>); + +#[derive(Default)] +struct State { + initialized: Vec<ID3D12Resource>, + init: Option<Init>, +} + +fn fresh(host: &Host, size: u64) -> windows::core::Result<Recorded> { + const HEAP_KEY: GUID = GUID::from_u128(0x519dc19e_aa81_4cd8_a150_01d4b992c1bc); + let device = &host.device; + let properties = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: SLOT, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let no_resource = windows::core::Error::empty; + // SAFETY: valid descriptor and a live host device. + let info = unsafe { device.GetResourceAllocationInfo(0, &[desc]) }; + if info.SizeInBytes != SLOT || info.Alignment != SLOT { return Err(no_resource()); } + let heap_desc = D3D12_HEAP_DESC { + SizeInBytes: size, Properties: properties, Alignment: 0, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS | not_resident(), + }; + BYTES.fetch_add(size, Ordering::Relaxed); + let charge = Charge(size); + let mut heap: Option<ID3D12Heap> = None; + // SAFETY: buffer-only heap, fully charged before allocation. + unsafe { device.CreateHeap(&heap_desc, &mut heap) }?; + let heap = heap.ok_or_else(no_resource)?; + track(&heap, charge)?; + resident(device, &heap)?; + mapped(device)?; + + let (zero, pointer) = host.upload_buffer(SLOT).ok_or_else(no_resource)?; + if pointer.is_null() { return Err(no_resource()); } + // SAFETY: one entire mapped 64 KiB upload slot, not yet exposed to the GPU. + unsafe { pointer.write_bytes(0, SLOT as usize) }; + // SAFETY: a private direct command list using a dedicated allocator. + let (allocator, list): (ID3D12CommandAllocator, ID3D12GraphicsCommandList) = unsafe { + let allocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; + (allocator, list) + }; + let mut buffers = Vec::with_capacity((size / SLOT) as usize); + for offset in (0..size).step_by(SLOT as usize) { + let mut buffer: Option<ID3D12Resource> = None; + // SAFETY: distinct aligned slots within an owned DEFAULT heap. + unsafe { device.CreatePlacedResource(&heap, offset, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buffer) }?; + let buffer = buffer.ok_or_else(no_resource)?; + // SAFETY: keep the heap alive with the resource, not just its Shadow. + // Descriptors and retired/in-flight lists can own independent COM refs. + unsafe { buffer.SetPrivateDataInterface(&HEAP_KEY, &heap) }?; + // SAFETY: borrowed pointer, as in host::transition(); the buffer and + // heap remain alive through the confirmed activation submission. + let after = unsafe { std::mem::transmute_copy(&buffer) }; + // SAFETY: private list and live pageables. Explicit initialization + // covers rounded bytes, and returns the buffer to COMMON before use. + unsafe { + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { + pResourceBefore: std::mem::ManuallyDrop::new(None), pResourceAfter: after, + }), + }, + }, transition(&buffer, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST)]); + list.CopyBufferRegion(&buffer, 0, &zero, 0, SLOT); + list.ResourceBarrier(&[transition(&buffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON)]); + } + buffers.push(buffer); + } + // SAFETY: the list was created open. It is not submitted here. + unsafe { list.Close() }?; + Ok(Recorded { list: list.cast()?, _allocator: allocator, _zero: zero, buffers }) +} + +impl Stock { + /// All registered buffer allocators are serialized by the title table + /// writer. `committed` excludes already charged heap memory. + pub(super) fn take(&self, host: &Host, committed: u64, most: u64, hundredths: u64) -> Option<ID3D12Resource> { + let mut state = self.0.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(buffer) = state.initialized.pop() { + ISSUED.fetch_add(1, Ordering::Relaxed); + return Some(buffer); + } + let [budget, used, ..] = host.video_memory()?; + let available = (budget / 100 * hundredths).saturating_sub(used); + let size = block_size(most.saturating_sub(committed.saturating_add(bytes())), available); + // A block must save at least one physical allocation. + if size <= SLOT { return None; } + let fill = (|| -> windows::core::Result<_> { + if state.init.is_none() { state.init = Some(Init::new(host)?); } + let init = state.init.as_mut().expect("initialization queue"); + init.retire_pending(host)?; + init.initialize(host, fresh(host, size)?) + })(); + match fill { + Ok(mut initialized) => { + let next = initialized.pop(); + state.initialized = initialized; + BLOCKS.fetch_add(1, Ordering::Relaxed); + ISSUED.fetch_add(1, Ordering::Relaxed); + next + } + Err(error) => { + tracing::warn!(%error, "fresh title card heap not ready; using committed allocation"); + None + } + } + } + + pub(super) fn trim_unused(&self) { + if let Ok(mut state) = self.0.try_lock() { + // Do not return an issued range to the stock. If any issued + // resource still exists the heap stays charged and alive. + let unused = std::mem::take(&mut state.initialized); + drop(state); + drop(unused); + } + } +} + +pub(super) fn report() { + if on() { + tracing::info!(heaps = BLOCKS.load(Ordering::Relaxed), issued = ISSUED.load(Ordering::Relaxed), + bytes = bytes(), "fresh registered card heaps"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn block_size_obeys_the_existing_limits() { + assert_eq!(block_size(BLOCK * 2, BLOCK * 3), BLOCK); + assert_eq!(block_size(5 * SLOT - 1, BLOCK), 4 * SLOT); + assert_eq!(block_size(BLOCK, 3 * SLOT + 2), 3 * SLOT); + assert_eq!(block_size(SLOT - 1, BLOCK), 0); + } + + #[test] + #[ignore = "run in isolation with the RTX hardware and the 64 KiB buffer profile"] + fn registered_shadow_is_initialized_before_publication_and_heap_tracks_last_reference() { + use crate::shadow; + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree}; + + assert!(cfg!(feature = "diagnostics") && on() && crate::switch::on("VICTORY_D3D12_GBV")); + let host = host().expect("native D3D12 host"); + assert!(host.messages.is_some()); + assert_eq!(host.adapter_vendor_id(), Some(0x10de)); + assert_eq!(bytes(), 0); + // SAFETY: one synthetic private page with no guest dependencies. + let title = unsafe { VirtualAlloc(std::ptr::null(), SLOT as usize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }; + assert!(!title.is_null()); + const AT: usize = 4096; + const LEN: usize = 256; + // SAFETY: the fixture owns at least AT+LEN bytes in this mapping. + unsafe { title.cast::<u8>().add(AT).write_bytes(0x52, LEN) }; + shadow::register(1, title as u64, SLOT); + let shadow = shadow::find(title as u64, SLOT).expect("registered shadow"); + assert_eq!(ISSUED.load(Ordering::Relaxed), 1, "must not silently use the committed fallback"); + assert_eq!(bytes(), BLOCK, "unissued capacity is charged as well"); + + let (upload, data) = host.upload_buffer(LEN as u64).expect("partial upload"); + let readback = host.read_back_buffer(2 * SLOT).expect("readback"); + let list = host.new_list().expect("direct list"); + let buffer = &shadow.buffer; + assert!(!data.is_null()); + // SAFETY: initialized input and disjoint output spans. The real + // published resource is accessed by a different queue than the + // initializer: first a read of the entire slot, then a partial write. + unsafe { + std::ptr::copy_nonoverlapping(title.cast::<u8>().add(AT), data, LEN); + list.list.ResourceBarrier(&[transition(buffer, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.list.CopyBufferRegion(&readback, 0, buffer, 0, SLOT); + list.list.ResourceBarrier(&[transition(buffer, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COPY_DEST)]); + list.list.CopyBufferRegion(buffer, AT as u64, &upload, 0, LEN as u64); + list.list.ResourceBarrier(&[transition(buffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.list.CopyBufferRegion(&readback, SLOT, buffer, 0, SLOT); + } + list.close(); + host.execute_sync_internal(&list); + assert!(host.log_messages().is_none()); + // SAFETY: the native copy completed. Only read the exact mapped output. + unsafe { + host.device.GetDeviceRemovedReason().unwrap(); + let mut data = std::ptr::null_mut(); + readback.Map(0, Some(&D3D12_RANGE { Begin: 0, End: (2 * SLOT) as usize }), Some(&mut data)).unwrap(); + assert!(!data.is_null()); + let output = std::slice::from_raw_parts(data.cast::<u8>(), (2 * SLOT) as usize); + let initial = output[..SLOT as usize].iter().all(|&b| b == 0); + let partial = output[SLOT as usize..].iter().enumerate().all(|(i, &b)| b == if (AT..AT+LEN).contains(&i) { 0x52 } else { 0 }); + readback.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 0 })); + assert!(initial && partial, "fresh registered data must match the committed path"); + } + + let slot_owner = shadow.buffer.clone(); + shadow::unregister(1, title as u64); + drop(shadow); + drop(list); + host.title_card_heaps.trim_unused(); + assert_eq!(bytes(), BLOCK, "a descriptor's resource still retains its heap"); + drop(slot_owner); + assert_eq!(bytes(), 0, "physical charge returns when the last resource goes"); + // SAFETY: this was the private synthetic mapping and it is no longer tracked. + assert_ne!(unsafe { VirtualFree(title, 0, MEM_RELEASE) }, 0); + println!("FRESH_HEAP_GPU_PASS initial=65536 partial=65536 lifetime=exact"); + } +} diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 0a785f0e..5b9c8984 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -498,6 +498,8 @@ struct Card { has_sent: AtomicBool, /// The buffers' bytes (the title buffer's, rounded up to 64 KiB). size: u64, + /// A fresh placed slot contributes via its entire physical heap instead. + heap_backed: bool, } /// Whether the host copies of big title buffers are in the card's own @@ -629,6 +631,10 @@ fn parse_mib(value: &str) -> Option<u64> { /// Bytes alive of copies' card sides, and of their "before" twins. static CARD_BYTES: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; +fn card_buffer_bytes() -> u64 { + CARD_BYTES[0].load(Ordering::Relaxed) + crate::host::title_card_heap::bytes() +} + /// Bytes of title-memory-by-address (RT BVH) arenas placed in local VRAM. static BY_ADDRESS_CARD_BYTES: AtomicU64 = AtomicU64::new(0); @@ -637,7 +643,7 @@ static BY_ADDRESS_CARD_BYTES: AtomicU64 = AtomicU64::new(0); pub(crate) fn vram_breakdown() -> [u64; 2] { let bvh = BY_ADDRESS_CARD_BYTES.load(Ordering::Relaxed); let win = WINDOW_CARD_BYTES.load(Ordering::Relaxed).saturating_sub(bvh); - let buf = CARD_BYTES[0].load(Ordering::Relaxed) + let buf = card_buffer_bytes() + CARD_BYTES[1].load(Ordering::Relaxed) + win + WINDOW_MAPPED_BYTES.load(Ordering::Relaxed); @@ -706,7 +712,7 @@ pub(crate) fn card_room_kept() -> u64 { ); remaining_card_room( buffers, - CARD_BYTES[0].load(Ordering::Relaxed), + card_buffer_bytes(), CARD_REFUSED[1].load(Ordering::Relaxed), windows, WINDOW_CARD_BYTES.load(Ordering::Relaxed), @@ -736,7 +742,7 @@ static CARDED: Mutex<Vec<std::sync::Weak<Shadow>>> = Mutex::new(Vec::new()); pub(crate) static CARD_STATS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7]; pub(crate) fn live_span_bytes() -> u64 { - CARD_BYTES[0].load(Ordering::Relaxed) + card_buffer_bytes() + WINDOW_CARD_BYTES.load(Ordering::Relaxed) + WINDOW_MAPPED_BYTES.load(Ordering::Relaxed) } @@ -749,7 +755,7 @@ pub(crate) fn card_stats() -> [u64; 10] { out[i] = stat.swap(0, Ordering::Relaxed); } out[7] = CARDED.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|w| w.strong_count() > 0).count() as u64; - out[8] = CARD_BYTES[0].load(Ordering::Relaxed) + out[8] = card_buffer_bytes() + WINDOW_CARD_BYTES.load(Ordering::Relaxed) + WINDOW_MAPPED_BYTES.load(Ordering::Relaxed); out[9] = CARD_BYTES[1].load(Ordering::Relaxed); @@ -767,7 +773,7 @@ pub(crate) fn card_hash_bytes(size: u64) -> u64 { /// copy, if the copy is to be there: [`cards`] is on, the size is within /// [`card_limits`] and below 1 GiB (the compare counts in 32 bits), and the /// host has what it takes (`Host::card_ready`). -fn card_for(size: u64) -> Option<ID3D12Resource> { +fn card_for(size: u64) -> Option<(ID3D12Resource, bool)> { let there = card_room_for(size); if there.is_some() || !card_all() || size >= 1 << 30 { return there; @@ -779,7 +785,7 @@ fn card_for(size: u64) -> Option<ID3D12Resource> { } let (buffer, _) = host.shared_buffer(size)?; CARD_BYTES[0].fetch_add(size, Ordering::Relaxed); - Some(buffer) + Some((buffer, false)) } /// Whether every title buffer's copy has two sides, however small @@ -797,7 +803,7 @@ fn card_all() -> bool { } /// [`card_for`] in the card's own memory. -fn card_room_for(size: u64) -> Option<ID3D12Resource> { +fn card_room_for(size: u64) -> Option<(ID3D12Resource, bool)> { if !cards() { return None; } @@ -816,6 +822,10 @@ fn card_room_for(size: u64) -> Option<ID3D12Resource> { // With room reserved for buffers, local usage including the new copy // may reach 97% of the reported budget. Disabling the reservation uses 80%. let hundredths = if card_room_kept_on() { 97 } else { 80 }; + if let Some(fresh) = host.fresh_title_card_buffer(size, CARD_BYTES[0].load(Ordering::Relaxed), most, hundredths) { + // Already admitted, fully charged, initialized, and confirmed. + return Some((fresh, true)); + } if let Some([budget, used, ..]) = host.video_memory() && used + size > budget / 100 * hundredths { @@ -832,7 +842,7 @@ fn card_room_for(size: u64) -> Option<ID3D12Resource> { used >> 20, budget >> 20, (budget / 100 * hundredths) >> 20, - CARD_BYTES[0].load(Ordering::Relaxed) >> 20, + card_buffer_bytes() >> 20, most >> 20, n, bytes >> 20, @@ -841,7 +851,7 @@ fn card_room_for(size: u64) -> Option<ID3D12Resource> { } return None; } - if CARD_BYTES[0].fetch_add(size, Ordering::Relaxed) + size > most { + if CARD_BYTES[0].fetch_add(size, Ordering::Relaxed) + crate::host::title_card_heap::bytes() + size > most { CARD_BYTES[0].fetch_sub(size, Ordering::Relaxed); return None; } @@ -849,7 +859,7 @@ fn card_room_for(size: u64) -> Option<ID3D12Resource> { if buffer.is_none() { CARD_BYTES[0].fetch_sub(size, Ordering::Relaxed); } - buffer + buffer.map(|buffer| (buffer, false)) } /// The most bytes of windows outside buffers whose copies go to the card's @@ -3478,7 +3488,7 @@ impl Drop for Shadow { if let Some(card) = &mut self.card { if window { WINDOW_CARD_BYTES.fetch_sub(card.size, Ordering::Relaxed); - } else { + } else if !card.heap_backed { CARD_BYTES[0].fetch_sub(card.size, Ordering::Relaxed); } if card.before.get_mut().unwrap_or_else(|e| e.into_inner()).is_some() { @@ -5569,6 +5579,7 @@ impl Shadow { sent: Mutex::default(), has_sent: AtomicBool::new(false), size: len.next_multiple_of(PIECE as u64), + heap_backed: false, }); } let shadow = Arc::new(shadow); @@ -5766,6 +5777,7 @@ mod land_tests { sent: Mutex::default(), has_sent: AtomicBool::new(false), size: len as u64, + heap_backed: false, }); Some(shadow) } @@ -6179,7 +6191,7 @@ fn lookup(address: u64, len: u64, any: bool) -> Option<Arc<Shadow>> { // 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) => { + Some((on_card, heap_backed)) => { crate::host::name(&on_card, || format!("title buffer {:#x}+{len:#x} on the card", key.0)); tracing::info!( start = format_args!("{:#x}", key.0), @@ -6194,6 +6206,7 @@ fn lookup(address: u64, len: u64, any: bool) -> Option<Arc<Shadow>> { sent: Mutex::default(), has_sent: AtomicBool::new(false), size, + heap_backed, }; (on_card, Some(card)) } @@ -6426,6 +6439,7 @@ pub(crate) fn by_address(start: u64, len: u64) -> Option<Arc<Shadow>> { sent: Mutex::default(), has_sent: AtomicBool::new(false), size: len, + heap_backed: false, }); let shadow = Arc::new(shadow); CARDED.lock().unwrap_or_else(|e| e.into_inner()).push(Arc::downgrade(&shadow)); @@ -6504,6 +6518,7 @@ fn build_loose_shadow(start: u64, len: u64, backing: LooseBacking) -> Arc<Shadow sent: Mutex::default(), has_sent: AtomicBool::new(false), size: len, + heap_backed: false, }; (on_card, Some(card)) } ``` </details>
NotADonky43 commented 2026-11-28 12:00:36 +00:00 (Migrated from github.com)
Author
Contributor

Imported from TaynanGT/Vice-Tay. Originally posted by NotADonky43 on 2026-11-28T12:00:36Z.


One follow-up to the allocator above: the pressure sweep dropped every never-issued resource in the current batch, even when an issued resource still held the underlying heap. The next request then started another heap without reclaiming the first one.

The attached delta keeps the active batch’s never-issued resources when an issued resource still pins it. COM destruction notifications track issued resource lifetime independently of Shadow; the actual heap destructor still releases the budget charge. Once no issued resource remains, a pressure sweep can release the ready batch. This does not recycle issued slots or change initialization, queue ordering, admission, or the committed fallback. Keeping the ready resources retains their CPU/driver-side objects while the heap is pinned; it does not itself free an otherwise unused heap earlier.

  • Native RTX 5070 Ti, D3D12 debug and GPU-based validation enabled: the regression failed on b446069e because the next allocation after trim doubled the charge from 8 MiB to 16 MiB. With the delta, the second allocation stayed at 8 MiB; after the final independent resource reference was released and pressure swept again, the charge returned to zero. The production registered-allocation test still passes exact cross-queue readback before and after a partial write. Release build, mapping-fence tests and the isolated serial workspace suite passed.
  • Game A/B: RTX 5070 Ti, Series X, 64 KiB card-copy profile and 4 GiB BAR, no attached profiler or overlay, same 25,694 precompiled shader entries and accepted 17,754,786-byte D3D12 pipeline library. Old allocator b446069e vs pressure follow-up d2a376bc, both on fe7c6e52. At reports with exactly 3,465 buffers issued, the original logged 57 heaps created / 416 MiB charged, versus 28 / 224 MiB with the fix. The new run supplied 320 buffer requests from slots retained after a pressure sweep. The 500th-to-3,200th initial allocation span was essentially unchanged (2.16 vs. 2.22 s).
  • Both reached heavy rendering without logged device loss; the original was closed at its 180 s deadline, the follow-up exited normally earlier. Draw workloads were not matched, and both still had pipelines pending. These are the allocator’s heap charges, not total VRAM, not proof of shorter visible loads, and not a frame-rate claim.

This is a source-only delta on top of the original patch in this issue, including the native regression; no title files or caches are needed for the fixture.

Source-only delta against b446069e (includes native regression)
diff --git a/crates/victory-gpu/src/host/title_card_heap.rs b/crates/victory-gpu/src/host/title_card_heap.rs
index ef021d86..55a61f2c 100644
--- a/crates/victory-gpu/src/host/title_card_heap.rs
+++ b/crates/victory-gpu/src/host/title_card_heap.rs
@@ -1,7 +1,8 @@
 //! Fresh-only device-local title buffers. Only the registered 64 KiB path
 //! uses this allocator; a declined allocation falls back to the committed path.
 use super::*;
-use std::sync::atomic::AtomicU64;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicU64, AtomicUsize};
 use windows::Win32::Graphics::Direct3D::ID3DDestructionNotifier;
 use windows::core::GUID;
 
@@ -10,6 +11,9 @@ const BLOCK: u64 = 128 * SLOT;
 static BYTES: AtomicU64 = AtomicU64::new(0);
 static BLOCKS: AtomicU64 = AtomicU64::new(0);
 static ISSUED: AtomicU64 = AtomicU64::new(0);
+static TRIMS_PINNED: AtomicU64 = AtomicU64::new(0);
+static TRIMMED_SLOTS: AtomicU64 = AtomicU64::new(0);
+static PRESERVED_ISSUES: AtomicU64 = AtomicU64::new(0);
 
 pub(crate) fn bytes() -> u64 { BYTES.load(Ordering::Relaxed) }
 
@@ -29,16 +33,17 @@ impl Drop for Charge {
     fn drop(&mut self) { BYTES.fetch_sub(self.0, Ordering::Relaxed); }
 }
 
-unsafe extern "system" fn release_charge(data: *mut std::ffi::c_void) {
-    // SAFETY: one Charge is transferred to the notifier by track().
-    drop(unsafe { Box::from_raw(data.cast::<Charge>()) });
+unsafe extern "system" fn release_tracked<T>(data: *mut std::ffi::c_void) {
+    // SAFETY: one Box<T> is transferred to this callback by track().
+    drop(unsafe { Box::from_raw(data.cast::<T>()) });
 }
 
-fn track(heap: &ID3D12Heap, charge: Charge) -> windows::core::Result<()> {
-    let notifier: ID3DDestructionNotifier = heap.cast()?;
-    let data = Box::into_raw(Box::new(charge));
-    // SAFETY: one owned charge, reclaimed here if registration fails.
-    if let Err(error) = unsafe { notifier.RegisterDestructionCallback(Some(release_charge), data.cast()) } {
+fn track<T: Send + 'static>(object: &impl Interface, value: T) -> windows::core::Result<()> {
+    let notifier: ID3DDestructionNotifier = object.cast()?;
+    let data = Box::into_raw(Box::new(value));
+    // SAFETY: one owned value safe to drop on the COM destruction thread;
+    // it is reclaimed here if registration fails.
+    if let Err(error) = unsafe { notifier.RegisterDestructionCallback(Some(release_tracked::<T>), data.cast()) } {
         // SAFETY: the callback was not registered.
         drop(unsafe { Box::from_raw(data) });
         return Err(error);
@@ -122,10 +127,43 @@ pub(super) struct Stock(Mutex<State>);
 
 #[derive(Default)]
 struct State {
-    initialized: Vec<ID3D12Resource>,
+    ready: Ready,
     init: Option<Init>,
 }
 
+#[derive(Default)]
+struct Ready {
+    buffers: Vec<ID3D12Resource>,
+    // Per heap, independent of Shadow and stock. Only issued resources hold
+    // one of these leases, and COM clones keep the lease through last use.
+    outstanding: Arc<AtomicUsize>,
+    retained_for_pressure: bool,
+}
+
+struct Issued(Arc<AtomicUsize>);
+
+impl Drop for Issued {
+    fn drop(&mut self) { self.0.fetch_sub(1, Ordering::Release); }
+}
+
+impl Ready {
+    fn take(&mut self) -> Option<ID3D12Resource> {
+        let buffer = self.buffers.pop()?;
+        self.outstanding.fetch_add(1, Ordering::Relaxed);
+        // A failed registration rolls back the lease. The unpublished slot
+        // is discarded and the caller can still use a committed resource.
+        if let Err(error) = track(&buffer, Issued(self.outstanding.clone())) {
+            tracing::warn!(%error, "cannot track fresh title card resource; using committed allocation");
+            return None;
+        }
+        ISSUED.fetch_add(1, Ordering::Relaxed);
+        if self.retained_for_pressure {
+            PRESERVED_ISSUES.fetch_add(1, Ordering::Relaxed);
+        }
+        Some(buffer)
+    }
+}
+
 fn fresh(host: &Host, size: u64) -> windows::core::Result<Recorded> {
     const HEAP_KEY: GUID = GUID::from_u128(0x519dc19e_aa81_4cd8_a150_01d4b992c1bc);
     let device = &host.device;
@@ -205,10 +243,7 @@ impl Stock {
     /// writer. `committed` excludes already charged heap memory.
     pub(super) fn take(&self, host: &Host, committed: u64, most: u64, hundredths: u64) -> Option<ID3D12Resource> {
         let mut state = self.0.lock().unwrap_or_else(|e| e.into_inner());
-        if let Some(buffer) = state.initialized.pop() {
-            ISSUED.fetch_add(1, Ordering::Relaxed);
-            return Some(buffer);
-        }
+        if !state.ready.buffers.is_empty() { return state.ready.take(); }
         let [budget, used, ..] = host.video_memory()?;
         let available = (budget / 100 * hundredths).saturating_sub(used);
         let size = block_size(most.saturating_sub(committed.saturating_add(bytes())), available);
@@ -221,12 +256,10 @@ impl Stock {
             init.initialize(host, fresh(host, size)?)
         })();
         match fill {
-            Ok(mut initialized) => {
-                let next = initialized.pop();
-                state.initialized = initialized;
+            Ok(buffers) => {
                 BLOCKS.fetch_add(1, Ordering::Relaxed);
-                ISSUED.fetch_add(1, Ordering::Relaxed);
-                next
+                state.ready = Ready { buffers, ..Default::default() };
+                state.ready.take()
             }
             Err(error) => {
                 tracing::warn!(%error, "fresh title card heap not ready; using committed allocation");
@@ -237,9 +270,18 @@ impl Stock {
 
     pub(super) fn trim_unused(&self) {
         if let Ok(mut state) = self.0.try_lock() {
-            // Do not return an issued range to the stock. If any issued
-            // resource still exists the heap stays charged and alive.
-            let unused = std::mem::take(&mut state.initialized);
+            if state.ready.buffers.is_empty() { return; }
+            // Dropping ready slots cannot free a pinned heap. Keep only the
+            // current batch's never-issued capacity in that case. COM may
+            // finish destruction concurrently, so a subsequent sweep can
+            // reclaim the heap even when this one still observes a lease.
+            if state.ready.outstanding.load(Ordering::Acquire) != 0 {
+                state.ready.retained_for_pressure = true;
+                TRIMS_PINNED.fetch_add(1, Ordering::Relaxed);
+                return;
+            }
+            let unused = std::mem::take(&mut state.ready.buffers);
+            TRIMMED_SLOTS.fetch_add(unused.len() as u64, Ordering::Relaxed);
             drop(state);
             drop(unused);
         }
@@ -249,7 +291,9 @@ impl Stock {
 pub(super) fn report() {
     if on() {
         tracing::info!(heaps = BLOCKS.load(Ordering::Relaxed), issued = ISSUED.load(Ordering::Relaxed),
-            bytes = bytes(), "fresh registered card heaps");
+            bytes = bytes(), trims_pinned = TRIMS_PINNED.load(Ordering::Relaxed),
+            trimmed_slots = TRIMMED_SLOTS.load(Ordering::Relaxed),
+            preserved_issues = PRESERVED_ISSUES.load(Ordering::Relaxed), "fresh registered card heaps");
     }
 }
 
@@ -276,8 +320,8 @@ mod tests {
         assert!(host.messages.is_some());
         assert_eq!(host.adapter_vendor_id(), Some(0x10de));
         assert_eq!(bytes(), 0);
-        // SAFETY: one synthetic private page with no guest dependencies.
-        let title = unsafe { VirtualAlloc(std::ptr::null(), SLOT as usize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) };
+        // SAFETY: two synthetic registered ranges in one private mapping.
+        let title = unsafe { VirtualAlloc(std::ptr::null(), (2 * SLOT) as usize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) };
         assert!(!title.is_null());
         const AT: usize = 4096;
         const LEN: usize = 256;
@@ -327,10 +371,27 @@ mod tests {
         drop(list);
         host.title_card_heaps.trim_unused();
         assert_eq!(bytes(), BLOCK, "a descriptor's resource still retains its heap");
+
+        // The trim couldn't release the first block. Satisfy later demand
+        // from its already prepared, never-used ranges instead of growing.
+        let next = title as u64 + SLOT;
+        shadow::register(2, next, SLOT);
+        let second = shadow::find(next, SLOT).expect("second registered shadow");
+        assert_ne!(slot_owner.as_raw(), second.buffer.as_raw(), "different regions must own different resources");
+        assert_eq!(ISSUED.load(Ordering::Relaxed), 2);
+        assert_eq!(PRESERVED_ISSUES.load(Ordering::Relaxed), 1);
+        assert_eq!(bytes(), BLOCK, "trim must not discard slots in a heap it cannot release");
+        shadow::unregister(2, next);
+        drop(second);
+        host.title_card_heaps.trim_unused();
+        assert_eq!(TRIMMED_SLOTS.load(Ordering::Relaxed), 0);
         drop(slot_owner);
-        assert_eq!(bytes(), 0, "physical charge returns when the last resource goes");
+        host.title_card_heaps.trim_unused();
+        assert_eq!(TRIMS_PINNED.load(Ordering::Relaxed), 2);
+        assert_eq!(TRIMMED_SLOTS.load(Ordering::Relaxed), BLOCK / SLOT - 2);
+        assert_eq!(bytes(), 0, "pressure releases stock once its last issued resource is gone");
         // SAFETY: this was the private synthetic mapping and it is no longer tracked.
         assert_ne!(unsafe { VirtualFree(title, 0, MEM_RELEASE) }, 0);
-        println!("FRESH_HEAP_GPU_PASS initial=65536 partial=65536 lifetime=exact");
+        println!("FRESH_HEAP_GPU_PASS initial=65536 partial=65536 lifetime=exact pressure_reuse_of_fresh_capacity=exact");
     }
 }
<!-- greyfinch-sync:TaynanGT/Vice-Tay:comment:7238929277 --> Imported from [TaynanGT/Vice-Tay](https://github.com/TaynanGT/Vice-Tay/issues/404#issuecomment-7238929277). Originally posted by [NotADonky43](https://github.com/NotADonky43) on 2026-11-28T12:00:36Z. --- One follow-up to the allocator above: the pressure sweep dropped every never-issued resource in the current batch, even when an issued resource still held the underlying heap. The next request then started another heap without reclaiming the first one. The attached delta keeps the active batch’s never-issued resources when an issued resource still pins it. COM destruction notifications track issued resource lifetime independently of `Shadow`; the actual heap destructor still releases the budget charge. Once no issued resource remains, a pressure sweep can release the ready batch. This does not recycle issued slots or change initialization, queue ordering, admission, or the committed fallback. Keeping the ready resources retains their CPU/driver-side objects while the heap is pinned; it does not itself free an otherwise unused heap earlier. - Native RTX 5070 Ti, D3D12 debug and GPU-based validation enabled: the regression failed on `b446069e` because the next allocation after trim doubled the charge from 8 MiB to 16 MiB. With the delta, the second allocation stayed at 8 MiB; after the final independent resource reference was released and pressure swept again, the charge returned to zero. The production registered-allocation test still passes exact cross-queue readback before and after a partial write. Release build, mapping-fence tests and the isolated serial workspace suite passed. - Game A/B: RTX 5070 Ti, Series X, 64 KiB card-copy profile and 4 GiB BAR, no attached profiler or overlay, same 25,694 precompiled shader entries and accepted 17,754,786-byte D3D12 pipeline library. Old allocator `b446069e` vs pressure follow-up `d2a376bc`, both on `fe7c6e52`. At reports with exactly **3,465 buffers issued**, the original logged **57 heaps created / 416 MiB charged**, versus **28 / 224 MiB** with the fix. The new run supplied **320 buffer requests** from slots retained after a pressure sweep. The 500th-to-3,200th initial allocation span was essentially unchanged (2.16 vs. 2.22 s). - Both reached heavy rendering without logged device loss; the original was closed at its 180 s deadline, the follow-up exited normally earlier. Draw workloads were not matched, and both still had pipelines pending. These are the allocator’s heap charges, not total VRAM, not proof of shorter visible loads, and not a frame-rate claim. This is a source-only delta on top of the original patch in this issue, including the native regression; no title files or caches are needed for the fixture. <details> <summary>Source-only delta against b446069e (includes native regression)</summary> ```diff diff --git a/crates/victory-gpu/src/host/title_card_heap.rs b/crates/victory-gpu/src/host/title_card_heap.rs index ef021d86..55a61f2c 100644 --- a/crates/victory-gpu/src/host/title_card_heap.rs +++ b/crates/victory-gpu/src/host/title_card_heap.rs @@ -1,7 +1,8 @@ //! Fresh-only device-local title buffers. Only the registered 64 KiB path //! uses this allocator; a declined allocation falls back to the committed path. use super::*; -use std::sync::atomic::AtomicU64; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, AtomicUsize}; use windows::Win32::Graphics::Direct3D::ID3DDestructionNotifier; use windows::core::GUID; @@ -10,6 +11,9 @@ const BLOCK: u64 = 128 * SLOT; static BYTES: AtomicU64 = AtomicU64::new(0); static BLOCKS: AtomicU64 = AtomicU64::new(0); static ISSUED: AtomicU64 = AtomicU64::new(0); +static TRIMS_PINNED: AtomicU64 = AtomicU64::new(0); +static TRIMMED_SLOTS: AtomicU64 = AtomicU64::new(0); +static PRESERVED_ISSUES: AtomicU64 = AtomicU64::new(0); pub(crate) fn bytes() -> u64 { BYTES.load(Ordering::Relaxed) } @@ -29,16 +33,17 @@ impl Drop for Charge { fn drop(&mut self) { BYTES.fetch_sub(self.0, Ordering::Relaxed); } } -unsafe extern "system" fn release_charge(data: *mut std::ffi::c_void) { - // SAFETY: one Charge is transferred to the notifier by track(). - drop(unsafe { Box::from_raw(data.cast::<Charge>()) }); +unsafe extern "system" fn release_tracked<T>(data: *mut std::ffi::c_void) { + // SAFETY: one Box<T> is transferred to this callback by track(). + drop(unsafe { Box::from_raw(data.cast::<T>()) }); } -fn track(heap: &ID3D12Heap, charge: Charge) -> windows::core::Result<()> { - let notifier: ID3DDestructionNotifier = heap.cast()?; - let data = Box::into_raw(Box::new(charge)); - // SAFETY: one owned charge, reclaimed here if registration fails. - if let Err(error) = unsafe { notifier.RegisterDestructionCallback(Some(release_charge), data.cast()) } { +fn track<T: Send + 'static>(object: &impl Interface, value: T) -> windows::core::Result<()> { + let notifier: ID3DDestructionNotifier = object.cast()?; + let data = Box::into_raw(Box::new(value)); + // SAFETY: one owned value safe to drop on the COM destruction thread; + // it is reclaimed here if registration fails. + if let Err(error) = unsafe { notifier.RegisterDestructionCallback(Some(release_tracked::<T>), data.cast()) } { // SAFETY: the callback was not registered. drop(unsafe { Box::from_raw(data) }); return Err(error); @@ -122,10 +127,43 @@ pub(super) struct Stock(Mutex<State>); #[derive(Default)] struct State { - initialized: Vec<ID3D12Resource>, + ready: Ready, init: Option<Init>, } +#[derive(Default)] +struct Ready { + buffers: Vec<ID3D12Resource>, + // Per heap, independent of Shadow and stock. Only issued resources hold + // one of these leases, and COM clones keep the lease through last use. + outstanding: Arc<AtomicUsize>, + retained_for_pressure: bool, +} + +struct Issued(Arc<AtomicUsize>); + +impl Drop for Issued { + fn drop(&mut self) { self.0.fetch_sub(1, Ordering::Release); } +} + +impl Ready { + fn take(&mut self) -> Option<ID3D12Resource> { + let buffer = self.buffers.pop()?; + self.outstanding.fetch_add(1, Ordering::Relaxed); + // A failed registration rolls back the lease. The unpublished slot + // is discarded and the caller can still use a committed resource. + if let Err(error) = track(&buffer, Issued(self.outstanding.clone())) { + tracing::warn!(%error, "cannot track fresh title card resource; using committed allocation"); + return None; + } + ISSUED.fetch_add(1, Ordering::Relaxed); + if self.retained_for_pressure { + PRESERVED_ISSUES.fetch_add(1, Ordering::Relaxed); + } + Some(buffer) + } +} + fn fresh(host: &Host, size: u64) -> windows::core::Result<Recorded> { const HEAP_KEY: GUID = GUID::from_u128(0x519dc19e_aa81_4cd8_a150_01d4b992c1bc); let device = &host.device; @@ -205,10 +243,7 @@ impl Stock { /// writer. `committed` excludes already charged heap memory. pub(super) fn take(&self, host: &Host, committed: u64, most: u64, hundredths: u64) -> Option<ID3D12Resource> { let mut state = self.0.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(buffer) = state.initialized.pop() { - ISSUED.fetch_add(1, Ordering::Relaxed); - return Some(buffer); - } + if !state.ready.buffers.is_empty() { return state.ready.take(); } let [budget, used, ..] = host.video_memory()?; let available = (budget / 100 * hundredths).saturating_sub(used); let size = block_size(most.saturating_sub(committed.saturating_add(bytes())), available); @@ -221,12 +256,10 @@ impl Stock { init.initialize(host, fresh(host, size)?) })(); match fill { - Ok(mut initialized) => { - let next = initialized.pop(); - state.initialized = initialized; + Ok(buffers) => { BLOCKS.fetch_add(1, Ordering::Relaxed); - ISSUED.fetch_add(1, Ordering::Relaxed); - next + state.ready = Ready { buffers, ..Default::default() }; + state.ready.take() } Err(error) => { tracing::warn!(%error, "fresh title card heap not ready; using committed allocation"); @@ -237,9 +270,18 @@ impl Stock { pub(super) fn trim_unused(&self) { if let Ok(mut state) = self.0.try_lock() { - // Do not return an issued range to the stock. If any issued - // resource still exists the heap stays charged and alive. - let unused = std::mem::take(&mut state.initialized); + if state.ready.buffers.is_empty() { return; } + // Dropping ready slots cannot free a pinned heap. Keep only the + // current batch's never-issued capacity in that case. COM may + // finish destruction concurrently, so a subsequent sweep can + // reclaim the heap even when this one still observes a lease. + if state.ready.outstanding.load(Ordering::Acquire) != 0 { + state.ready.retained_for_pressure = true; + TRIMS_PINNED.fetch_add(1, Ordering::Relaxed); + return; + } + let unused = std::mem::take(&mut state.ready.buffers); + TRIMMED_SLOTS.fetch_add(unused.len() as u64, Ordering::Relaxed); drop(state); drop(unused); } @@ -249,7 +291,9 @@ impl Stock { pub(super) fn report() { if on() { tracing::info!(heaps = BLOCKS.load(Ordering::Relaxed), issued = ISSUED.load(Ordering::Relaxed), - bytes = bytes(), "fresh registered card heaps"); + bytes = bytes(), trims_pinned = TRIMS_PINNED.load(Ordering::Relaxed), + trimmed_slots = TRIMMED_SLOTS.load(Ordering::Relaxed), + preserved_issues = PRESERVED_ISSUES.load(Ordering::Relaxed), "fresh registered card heaps"); } } @@ -276,8 +320,8 @@ mod tests { assert!(host.messages.is_some()); assert_eq!(host.adapter_vendor_id(), Some(0x10de)); assert_eq!(bytes(), 0); - // SAFETY: one synthetic private page with no guest dependencies. - let title = unsafe { VirtualAlloc(std::ptr::null(), SLOT as usize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }; + // SAFETY: two synthetic registered ranges in one private mapping. + let title = unsafe { VirtualAlloc(std::ptr::null(), (2 * SLOT) as usize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }; assert!(!title.is_null()); const AT: usize = 4096; const LEN: usize = 256; @@ -327,10 +371,27 @@ mod tests { drop(list); host.title_card_heaps.trim_unused(); assert_eq!(bytes(), BLOCK, "a descriptor's resource still retains its heap"); + + // The trim couldn't release the first block. Satisfy later demand + // from its already prepared, never-used ranges instead of growing. + let next = title as u64 + SLOT; + shadow::register(2, next, SLOT); + let second = shadow::find(next, SLOT).expect("second registered shadow"); + assert_ne!(slot_owner.as_raw(), second.buffer.as_raw(), "different regions must own different resources"); + assert_eq!(ISSUED.load(Ordering::Relaxed), 2); + assert_eq!(PRESERVED_ISSUES.load(Ordering::Relaxed), 1); + assert_eq!(bytes(), BLOCK, "trim must not discard slots in a heap it cannot release"); + shadow::unregister(2, next); + drop(second); + host.title_card_heaps.trim_unused(); + assert_eq!(TRIMMED_SLOTS.load(Ordering::Relaxed), 0); drop(slot_owner); - assert_eq!(bytes(), 0, "physical charge returns when the last resource goes"); + host.title_card_heaps.trim_unused(); + assert_eq!(TRIMS_PINNED.load(Ordering::Relaxed), 2); + assert_eq!(TRIMMED_SLOTS.load(Ordering::Relaxed), BLOCK / SLOT - 2); + assert_eq!(bytes(), 0, "pressure releases stock once its last issued resource is gone"); // SAFETY: this was the private synthetic mapping and it is no longer tracked. assert_ne!(unsafe { VirtualFree(title, 0, MEM_RELEASE) }, 0); - println!("FRESH_HEAP_GPU_PASS initial=65536 partial=65536 lifetime=exact"); + println!("FRESH_HEAP_GPU_PASS initial=65536 partial=65536 lifetime=exact pressure_reuse_of_fresh_capacity=exact"); } } ``` </details>
TaynanGT commented 2026-11-29 11:35:58 +00:00 (Migrated from github.com)
Author
Contributor

Imported from TaynanGT/Vice-Tay. Originally posted by TaynanGT on 2026-11-29T11:35:58Z.


Thanks for the independent resource-lifetime regression and pinned-heap accounting. The 416 vs 224 MiB result at the same issued-buffer count is useful allocator evidence, not a total VRAM or FPS claim. Please keep the follow-up separately reviewable and retain the final-reference-release test.

<!-- greyfinch-sync:TaynanGT/Vice-Tay:comment:7255221153 --> Imported from [TaynanGT/Vice-Tay](https://github.com/TaynanGT/Vice-Tay/issues/404#issuecomment-7255221153). Originally posted by [TaynanGT](https://github.com/TaynanGT) on 2026-11-29T11:35:58Z. --- Thanks for the independent resource-lifetime regression and pinned-heap accounting. The 416 vs 224 MiB result at the same issued-buffer count is useful allocator evidence, not a total VRAM or FPS claim. Please keep the follow-up separately reviewable and retain the final-reference-release test.
TaynanGT commented 2026-11-30 17:00:35 +00:00 (Migrated from github.com)
Author
Contributor

Imported from TaynanGT/Vice-Tay. Originally posted by TaynanGT on 2026-11-30T17:00:35Z.


main has moved to a new line of the code and everything is now named Vice-Tay: vice-tay.exe play, and VICE_TAY_* switches instead of VICTORY_* (details in #468). Could you check whether this still happens on the current main and say so here, with a log if you can?

<!-- greyfinch-sync:TaynanGT/Vice-Tay:comment:7285575224 --> Imported from [TaynanGT/Vice-Tay](https://github.com/TaynanGT/Vice-Tay/issues/404#issuecomment-7285575224). Originally posted by [TaynanGT](https://github.com/TaynanGT) on 2026-11-30T17:00:35Z. --- `main` has moved to a new line of the code and everything is now named Vice-Tay: `vice-tay.exe play`, and `VICE_TAY_*` switches instead of `VICTORY_*` (details in #468). Could you check whether this still happens on the current `main` and say so here, with a log if you can?
Sign in to join this conversation.
No labels
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.

Reference
TaynanGT/Vice-Tay#404
No description provided.