Windows' card side in shared 64 KiB tiles; the windows read most move to the card (with VICTORY_WINDOW_ARENA=1) #4922

Closed
xteral67 wants to merge 10 commits from upstream-pr/4922 into main
xteral67 commented 2026-12-01 14:08:32 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by xteral67 on 2026-12-01T14:08:32Z.


Depends on #4750. This branch holds #4750's commits; the new ones are the last five. Merge #4750 first.

Refs #4036

What it changes

With VICTORY_WINDOW_ARENA=1 (#4750), windows share one copy of title memory in 64 KiB tiles on the PC. Their card side was still a committed buffer per window, so overlapping windows held the same bytes on the card two or three times. The room for windows on the card (about 1 GB on a 12 GB card) was full in the first minute, and about 4.7 GB of windows were read over the bus.

  • VICTORY_WINDOW_ARENA_CARD (on with the arena, =0 as before): the card side is a reserved buffer over 64 KiB tiles of a second pool, shared by windows. The room counts only new tiles. Free tiles of the pool are weighed against the windows' cap only.
  • When the room is 95 % full, the card windows least recently read and held by nothing go, once in 30 frames.
  • Windows are counted by the bytes asked of them, by draws (loose()) and by the heap pass (heap_read()), as #4036 asks: windows read only through the heap were never counted. Once every 30 frames, up to 16 of the most-read windows without a card side move to the card, and windows on the card read at most half as much make room. Moves go through take-overs, as VICTORY_WINDOW_GROW does.
  • With the arena off (the default), nothing changes.

How it was tested

  • RTX 3080 Ti 12 GB, i5-14600KF, 32 GB RAM, driver 621.40. Series X profile, 1440p, DLSS quality, FSR frame generation 2x, no ray tracing. Diagnostics build.
  • Shared card tiles, scripted walking route, about 350 s in the world, one run each:
    • before (VICTORY_WINDOW_ARENA_CARD=0): 51.1 ms a frame, card 45 ms at 4.3–4.7k draws;
    • after: 41.6 ms a frame, card 31 ms at the same draws, VRAM 9.9 of 11.1 GB both times.
  • Moving windows by bytes read, one ride by hand in town (about 9 minutes): 460 windows moved onto the card and 1,759 off it. Windows in PC memory asked for 941, 870, 536, 683, then 306 MB a frame. No new picture errors seen. That ride also ran another change (render-target memory), so its frame times are not given as this change's effect.
  • Not tested: cargo test, other cards, the Series S profile, Linux.
  • These commits were built and played in a tree based on v2026.11.30.03, not on this branch as such.

Checked for overlap

  • I searched the open pull requests for the same issue and for the files this touches. Related: #1756, #3574, #4456 (when windows get a card side), #4893, #4189 (windows in CPU-mapped card memory), #2910 (window growing and a card ledger).

🤖 Generated with Claude Code

<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:issue:5587395407 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/4922). Originally posted by [xteral67](https://github.com/xteral67) on 2026-12-01T14:08:32Z. --- Depends on #4750. This branch holds #4750's commits; the new ones are the last five. Merge #4750 first. Refs #4036 ## What it changes With `VICTORY_WINDOW_ARENA=1` (#4750), windows share one copy of title memory in 64 KiB tiles on the PC. Their card side was still a committed buffer per window, so overlapping windows held the same bytes on the card two or three times. The room for windows on the card (about 1 GB on a 12 GB card) was full in the first minute, and about 4.7 GB of windows were read over the bus. - `VICTORY_WINDOW_ARENA_CARD` (on with the arena, `=0` as before): the card side is a reserved buffer over 64 KiB tiles of a second pool, shared by windows. The room counts only new tiles. Free tiles of the pool are weighed against the windows' cap only. - When the room is 95 % full, the card windows least recently read and held by nothing go, once in 30 frames. - Windows are counted by the bytes asked of them, by draws (`loose()`) and by the heap pass (`heap_read()`), as #4036 asks: windows read only through the heap were never counted. Once every 30 frames, up to 16 of the most-read windows without a card side move to the card, and windows on the card read at most half as much make room. Moves go through take-overs, as `VICTORY_WINDOW_GROW` does. - With the arena off (the default), nothing changes. ## How it was tested - RTX 3080 Ti 12 GB, i5-14600KF, 32 GB RAM, driver 621.40. Series X profile, 1440p, DLSS quality, FSR frame generation 2x, no ray tracing. Diagnostics build. - Shared card tiles, scripted walking route, about 350 s in the world, one run each: - before (`VICTORY_WINDOW_ARENA_CARD=0`): 51.1 ms a frame, card 45 ms at 4.3–4.7k draws; - after: 41.6 ms a frame, card 31 ms at the same draws, VRAM 9.9 of 11.1 GB both times. - Moving windows by bytes read, one ride by hand in town (about 9 minutes): 460 windows moved onto the card and 1,759 off it. Windows in PC memory asked for 941, 870, 536, 683, then 306 MB a frame. No new picture errors seen. That ride also ran another change (render-target memory), so its frame times are not given as this change's effect. - Not tested: `cargo test`, other cards, the Series S profile, Linux. - These commits were built and played in a tree based on v2026.11.30.03, not on this branch as such. ## Checked for overlap - [x] I searched the open pull requests for the same issue and for the files this touches. Related: #1756, #3574, #4456 (when windows get a card side), #4893, #4189 (windows in CPU-mapped card memory), #2910 (window growing and a card ledger). 🤖 Generated with [Claude Code](https://claude.com/claude-code)
gut0to commented 2026-12-01 14:27:03 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by gut0to on 2026-12-01T14:27:03Z.

Review: COMMENTED


AI-assisted review; I used an AI assistant to inspect this diff.

<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:review:6133279172 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/4922#pullrequestreview-6133279172). Originally posted by [gut0to](https://github.com/gut0to) on 2026-12-01T14:27:03Z. **Review:** COMMENTED --- AI-assisted review; I used an AI assistant to inspect this diff.
gut0to commented 2026-12-01 14:27:03 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by gut0to on 2026-12-01T14:27:03Z.

Code review location: crates/victory-gpu/src/arena.rs; line 307

@@ -0,0 +1,667 @@
+//! One copy of title memory for the windows over it (`VICTORY_WINDOW_ARENA=1`).
+//!
+//! A window outside buffers (`crate::shadow`) was a buffer of its own, and
+//! windows overlap: a cell's window reaches 2 MiB into the next cell, whose
+//! window holds the same bytes again. In a scripted walk through town
+//! 837-888 windows held 5.1-5.5 GB for 3.75-3.9 GB of title memory (measured
+//! by the union of their ranges), on a PC whose memory ran out.
+//!
+//! Here a window is a reserved buffer whose 64 KiB tiles are tiles of a pool
+//! shared by every window: the tile of a title address is the same whichever
+//! window shows it, so each byte is held once. The pool's heaps are in the
+//! PC's memory, write-back, and each is mapped for the CPU through a
+//! buffer placed over all of it: the CPU fills a tile there, the card reads
+//! it through any window's reserved buffer (tried on an RTX 3080 Ti, tiled
+//! resources tier 4: tiles mapped out of order read back right; where the
+//! card refuses a reserved buffer, the window gets a buffer of its own).
+//! A window keeps its own start, length and GPU address, so whatever the
+//! card is given of it is as before; only the CPU's side is no longer one
+//! run of memory: [`Tiles::runs`] cuts a range of it where tiles end.
+//!
+//! shortcut: windows shaders are declared to write stay as before (a buffer
+//! of their own), and so do windows with a side in the card's memory; a
+//! window made before shaders were first declared to write its memory keeps
+//! its tiles (`crate::shadow` counts those).
+
+use std::collections::HashMap;
+use std::sync::Mutex;
+use std::sync::atomic::{AtomicU64, Ordering};
+
+use windows::Win32::Graphics::Direct3D12::*;
+use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC;
+
+/// The size of a tile, and the line windows in the pool start on.
+pub(crate) const TILE: u64 = 64 << 10;
+/// Tiles of a heap of the pool: 32 MiB.
+/// Tiles of 64 KiB per heap of the pool (`VICTORY_WINDOW_ARENA_MB`, 2 to 64
+/// MiB, default 8). At 32 MiB a drive held 4.7 GB of heaps for 4.1 GB of
+/// tiles (148 heaps, 8 given back): a heap goes back only when every tile
+/// is free, and a few long-lived tiles kept most heaps. Smaller heaps empty
+/// out sooner.
+fn heap_tiles() -> u32 {
+    static TILES: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
+    *TILES.get_or_init(|| {
+        let mb = std::env::var("VICTORY_WINDOW_ARENA_MB").ok().and_then(|v| v.trim().parse::<u32>().ok()).unwrap_or(8).clamp(2, 64);
+        mb * 16
+    })
+}
+
+/// Whether windows outside buffers share one copy (`VICTORY_WINDOW_ARENA=1`;
+/// off by default).
+pub(crate) fn on() -> bool {
+    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+    *ON.get_or_init(|| {
+        let on = std::env::var_os("VICTORY_WINDOW_ARENA").is_some_and(|v| v == "1");
+        if on {
+            tracing::info!("windows outside buffers share one copy of title memory, in 64 KiB tiles (VICTORY_WINDOW_ARENA=1)");
+        }
+        on
+    })
+}
+
+/// A heap of the pool: the heap, the buffer over it the CPU maps, where
+/// that is mapped, and its free tiles.
+struct Heap {
+    heap: ID3D12Heap,
+    _cpu: ID3D12Resource,
+    data: usize,
+    free: Vec<u32>,
+}
+
+/// Where a title tile is held: heap, tile in it, windows that show it.
+#[derive(Clone, Copy)]
+struct Held {
+    heap: u32,
+    tile: u32,
+    windows: u32,
+}
+
+#[derive(Default)]
+struct Pool {
+    /// `None`: a heap given back ([`Pool::give_back`]); its place is taken
+    /// by the next heap made.
+    heaps: Vec<Option<Heap>>,
+    /// By title tile (address / [`TILE`]).
+    held: HashMap<u64, Held>,
+}
+
+// SAFETY: D3D12 objects are free-threaded; `data` is an address of a
+// persistent mapping.
+unsafe impl Send for Pool {}
+
+static POOL: Mutex<Option<Pool>> = Mutex::new(None);
+
+/// Since the start: windows made in the pool, refused (no room, no
+/// mapping), title tiles held now, tiles shared when a window was made
+/// (held already), tiles new, heaps made, windows let go, heaps given back.
+pub(crate) static STATS: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8];
+
+/// The CPU's side of a window in the pool: where each of its tiles is
+/// mapped. Dropping it gives the tiles back: drop it only once the card is
+/// done with the window ([`crate::host::retire`]).
+pub(crate) struct Tiles {
+    /// The window's first title tile.
+    first: u64,
+    /// Per tile of the window: its address in the CPU's mapping.
+    at: Box<[usize]>,
+}
+
+impl Tiles {
+    /// The CPU's address of offset `offset` of the window; good up to the
+    /// end of its tile.
+    pub(crate) fn at(&self, offset: usize) -> *mut u8 {
+        (self.at[offset / TILE as usize] + offset % TILE as usize) as *mut u8
+    }
+
+    /// `[from, to)` of the window as runs of the CPU's mapping: (offset,
+    /// address, bytes), tiles that lie one after the other in a heap taken
+    /// as one run.
+    pub(crate) fn runs(&self, from: usize, to: usize) -> Vec<(usize, *mut u8, usize)> {
+        let mut out: Vec<(usize, *mut u8, usize)> = Vec::new();
+        let mut at = from;
+        while at < to {
+            let end = ((at / TILE as usize + 1) * TILE as usize).min(to);
+            let here = self.at(at);
+            match out.last_mut() {
+                Some((_, last, n)) if (*last as usize) + *n == here as usize => *n += end - at,
+                _ => out.push((at, here, end - at)),
+            }
+            at = end;
+        }
+        out
+    }
+}
+
+impl Drop for Tiles {
+    fn drop(&mut self) {
+        let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner());
+        let Some(pool) = pool.as_mut() else {
+            return;
+        };
+        for i in 0..self.at.len() as u64 {
+            let key = self.first + i;
+            let Some(held) = pool.held.get_mut(&key) else {
+                continue;
+            };
+            held.windows -= 1;
+            if held.windows == 0 {
+                let Held { heap, tile, .. } = *held;
+                pool.held.remove(&key);
+                pool.free_tile(heap, tile);
+            }
+        }
+        STATS[6].fetch_add(1, Ordering::Relaxed);
+    }
+}
+
+impl Pool {
+    /// Tile `tile` of heap `heap` is held by no window: free. A heap with
+    /// every tile free goes back to the system (unless it is the only one
+    /// left): the pool grew to 3.8 GB in the world's first minutes and kept
+    /// it while windows were let go (2026-11-30), on a PC short of memory.
+    /// (Only from [`Tiles`]' drop, which comes once the card is done with
+    /// the window: nothing reads the heap any more.)
+    fn free_tile(&mut self, heap: u32, tile: u32) {
+        STATS[2].fetch_sub(1, Ordering::Relaxed);
+        let alive = self.heaps.iter().filter(|h| h.is_some()).count();
+        let Some(h) = self.heaps[heap as usize].as_mut() else {
+            return;
+        };
+        h.free.push(tile);
+        if h.free.len() == heap_tiles() as usize && alive > 1 {
+            self.heaps[heap as usize] = None;
+            STATS[7].fetch_add(1, Ordering::Relaxed);
+        }
+    }
+
+    /// The heap to take a new tile from: the one with the fewest free tiles
+    /// (others empty out and go back), or a new one.
+    fn heap_for_tile(&mut self, device: &ID3D12Device) -> Option<usize> {
+        let found = self
+            .heaps
+            .iter()
+            .enumerate()
+            .filter_map(|(i, h)| h.as_ref().filter(|h| !h.free.is_empty()).map(|h| (h.free.len(), i)))
+            .min()
+            .map(|(_, i)| i);
+        if found.is_some() {
+            return found;
+        }
+        let made = new_heap(device)?;
+        match self.heaps.iter().position(Option::is_none) {
+            Some(i) => {
+                self.heaps[i] = Some(made);
+                Some(i)
+            }
+            None => {
+                self.heaps.push(Some(made));
+                Some(self.heaps.len() - 1)
+            }
+        }
+    }
+}
+
+fn buffer_desc(bytes: u64) -> D3D12_RESOURCE_DESC {
+    D3D12_RESOURCE_DESC {
+        Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
+        Width: bytes,
+        Height: 1,
+        DepthOrArraySize: 1,
+        MipLevels: 1,
+        SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+        Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
+        ..Default::default()
+    }
+}
+
+/// A new heap for the pool, mapped for the CPU.
+fn new_heap(device: &ID3D12Device) -> Option<Heap> {
+    let desc = D3D12_HEAP_DESC {
+        SizeInBytes: u64::from(heap_tiles()) * TILE,
+        Properties: D3D12_HEAP_PROPERTIES {
+            Type: D3D12_HEAP_TYPE_CUSTOM,
+            // Write-back, as the buffers of windows outside the pool are
+            // (`Host::shared_buffer`): the CPU reads tiles too (the sends of
+            // `crate::host::send` and the compares of `crate::shadow`), and
+            // write-combined memory is not cached for reads: 44.9 MB a frame
+            // took 16.4 ms to send out of it in town (2.7 GB/s).
+            CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
+            MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
+            ..Default::default()
+        },
+        Alignment: 0,
+        Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS,
+    };
+    // SAFETY: plain creation; out pointers are ours.
+    unsafe {
+        let mut heap: Option<ID3D12Heap> = None;
+        if let Err(e) = device.CreateHeap::<ID3D12Heap>(&raw const desc, &raw mut heap) {
+            tracing::warn!(error = %e, "no heap for the windows' shared copy: windows get buffers of their own");
+            return None;
+        }
+        let heap = heap?;
+        let whole = buffer_desc(desc.SizeInBytes);
+        let mut cpu: Option<ID3D12Resource> = None;
+        if let Err(e) = device.CreatePlacedResource(&heap, 0, &raw const whole, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut cpu) {
+            tracing::warn!(error = %e, "no buffer over a heap of the windows' shared copy");
+            return None;
+        }
+        let cpu = cpu?;
+        let mut data = std::ptr::null_mut();
+        if let Err(e) = cpu.Map(0, None, Some(&raw mut data)) {
+            tracing::warn!(error = %e, "a heap of the windows' shared copy does not map");
+            return None;
+        }
+        crate::host::name(&cpu, || "windows' shared copy of title memory".to_owned());
+        STATS[5].fetch_add(1, Ordering::Relaxed);
+        Some(Heap {
+            heap,
+            _cpu: cpu,
+            data: data as usize,
+            // Taken from the end: low tiles first.
+            free: (0..heap_tiles()).rev().collect(),
+        })
+    }
+}
+
+/// A window `[start, start + len)` in the pool: a reserved buffer of its
+/// length over the pool's tiles of its title memory, given its tiles on the
+/// host's queue (before any submission that reads it), and where the CPU
+/// fills each. `None` if `start` is not on a tile's line or the pool has no
+/// room: the window then gets a buffer of its own.
+///
+/// Tiles new to the pool hold whatever the heap held: a new window's copy
+/// starts with every page uncopied (`crate::shadow`), so its first refresh
+/// fills what it reads; a tile it shares holds the other window's bytes,
+/// which are title bytes too.
+pub(crate) fn window(start: u64, len: u64) -> Option<(ID3D12Resource, Tiles)> {
+    if !start.is_multiple_of(TILE) || len == 0 {
+        return None;
+    }
+    let host = crate::host::host()?;
+    let device = &host.device;
+    let tiles = len.div_ceil(TILE);
+    let first = start / TILE;
+    // The reserved buffer first: if the card refuses, nothing is taken.
+    let desc = buffer_desc(tiles * TILE);
+    let mut buffer: Option<ID3D12Resource> = None;
+    // SAFETY: plain creation.
+    if let Err(e) = unsafe { device.CreateReservedResource(&raw const desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut buffer) } {
+        STATS[1].fetch_add(1, Ordering::Relaxed);
+        tracing::warn!(error = %e, start = format_args!("{start:#x}"), len, "no reserved buffer for a window: it gets a buffer of its own");
+        return None;
+    }
+    let buffer = buffer?;
+    let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner());
+    let pool = pool.get_or_insert_with(Pool::default);
+    // Each tile: held already, or a free tile (a new heap if none).
+    let mut placed: Vec<(u32, u32)> = Vec::with_capacity(tiles as usize);
+    for i in 0..tiles {
+        let key = first + i;
+        if let Some(held) = pool.held.get_mut(&key) {
+            held.windows += 1;
+            placed.push((held.heap, held.tile));
+            STATS[3].fetch_add(1, Ordering::Relaxed);
+            continue;
+        }
+        let heap = match pool.heap_for_tile(device) {

Could this rollback bookkeeping get a CPU-only test with a mix of already-shared and newly allocated tiles? On a later-tile allocation failure, this branch decrements the refs for every entry in placed and returns tiles whose count reaches zero; a regression here could either strand tiles or free one still used by another window. The added arena test covers run coalescing, but not this lifecycle path. Factoring the refcount/rollback operations into a pure helper would make the failure and overlapping-window cases testable without D3D12. AI-assisted review; I traced the partial-allocation cleanup against the shared-window reference counts.

<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:review-comment:4755626624 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/4922#discussion_r4755626624). Originally posted by [gut0to](https://github.com/gut0to) on 2026-12-01T14:27:03Z. **Code review location:** `crates/victory-gpu/src/arena.rs`; line 307 ~~~~diff @@ -0,0 +1,667 @@ +//! One copy of title memory for the windows over it (`VICTORY_WINDOW_ARENA=1`). +//! +//! A window outside buffers (`crate::shadow`) was a buffer of its own, and +//! windows overlap: a cell's window reaches 2 MiB into the next cell, whose +//! window holds the same bytes again. In a scripted walk through town +//! 837-888 windows held 5.1-5.5 GB for 3.75-3.9 GB of title memory (measured +//! by the union of their ranges), on a PC whose memory ran out. +//! +//! Here a window is a reserved buffer whose 64 KiB tiles are tiles of a pool +//! shared by every window: the tile of a title address is the same whichever +//! window shows it, so each byte is held once. The pool's heaps are in the +//! PC's memory, write-back, and each is mapped for the CPU through a +//! buffer placed over all of it: the CPU fills a tile there, the card reads +//! it through any window's reserved buffer (tried on an RTX 3080 Ti, tiled +//! resources tier 4: tiles mapped out of order read back right; where the +//! card refuses a reserved buffer, the window gets a buffer of its own). +//! A window keeps its own start, length and GPU address, so whatever the +//! card is given of it is as before; only the CPU's side is no longer one +//! run of memory: [`Tiles::runs`] cuts a range of it where tiles end. +//! +//! shortcut: windows shaders are declared to write stay as before (a buffer +//! of their own), and so do windows with a side in the card's memory; a +//! window made before shaders were first declared to write its memory keeps +//! its tiles (`crate::shadow` counts those). + +use std::collections::HashMap; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + +/// The size of a tile, and the line windows in the pool start on. +pub(crate) const TILE: u64 = 64 << 10; +/// Tiles of a heap of the pool: 32 MiB. +/// Tiles of 64 KiB per heap of the pool (`VICTORY_WINDOW_ARENA_MB`, 2 to 64 +/// MiB, default 8). At 32 MiB a drive held 4.7 GB of heaps for 4.1 GB of +/// tiles (148 heaps, 8 given back): a heap goes back only when every tile +/// is free, and a few long-lived tiles kept most heaps. Smaller heaps empty +/// out sooner. +fn heap_tiles() -> u32 { + static TILES: std::sync::OnceLock<u32> = std::sync::OnceLock::new(); + *TILES.get_or_init(|| { + let mb = std::env::var("VICTORY_WINDOW_ARENA_MB").ok().and_then(|v| v.trim().parse::<u32>().ok()).unwrap_or(8).clamp(2, 64); + mb * 16 + }) +} + +/// Whether windows outside buffers share one copy (`VICTORY_WINDOW_ARENA=1`; +/// off by default). +pub(crate) fn on() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var_os("VICTORY_WINDOW_ARENA").is_some_and(|v| v == "1"); + if on { + tracing::info!("windows outside buffers share one copy of title memory, in 64 KiB tiles (VICTORY_WINDOW_ARENA=1)"); + } + on + }) +} + +/// A heap of the pool: the heap, the buffer over it the CPU maps, where +/// that is mapped, and its free tiles. +struct Heap { + heap: ID3D12Heap, + _cpu: ID3D12Resource, + data: usize, + free: Vec<u32>, +} + +/// Where a title tile is held: heap, tile in it, windows that show it. +#[derive(Clone, Copy)] +struct Held { + heap: u32, + tile: u32, + windows: u32, +} + +#[derive(Default)] +struct Pool { + /// `None`: a heap given back ([`Pool::give_back`]); its place is taken + /// by the next heap made. + heaps: Vec<Option<Heap>>, + /// By title tile (address / [`TILE`]). + held: HashMap<u64, Held>, +} + +// SAFETY: D3D12 objects are free-threaded; `data` is an address of a +// persistent mapping. +unsafe impl Send for Pool {} + +static POOL: Mutex<Option<Pool>> = Mutex::new(None); + +/// Since the start: windows made in the pool, refused (no room, no +/// mapping), title tiles held now, tiles shared when a window was made +/// (held already), tiles new, heaps made, windows let go, heaps given back. +pub(crate) static STATS: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; + +/// The CPU's side of a window in the pool: where each of its tiles is +/// mapped. Dropping it gives the tiles back: drop it only once the card is +/// done with the window ([`crate::host::retire`]). +pub(crate) struct Tiles { + /// The window's first title tile. + first: u64, + /// Per tile of the window: its address in the CPU's mapping. + at: Box<[usize]>, +} + +impl Tiles { + /// The CPU's address of offset `offset` of the window; good up to the + /// end of its tile. + pub(crate) fn at(&self, offset: usize) -> *mut u8 { + (self.at[offset / TILE as usize] + offset % TILE as usize) as *mut u8 + } + + /// `[from, to)` of the window as runs of the CPU's mapping: (offset, + /// address, bytes), tiles that lie one after the other in a heap taken + /// as one run. + pub(crate) fn runs(&self, from: usize, to: usize) -> Vec<(usize, *mut u8, usize)> { + let mut out: Vec<(usize, *mut u8, usize)> = Vec::new(); + let mut at = from; + while at < to { + let end = ((at / TILE as usize + 1) * TILE as usize).min(to); + let here = self.at(at); + match out.last_mut() { + Some((_, last, n)) if (*last as usize) + *n == here as usize => *n += end - at, + _ => out.push((at, here, end - at)), + } + at = end; + } + out + } +} + +impl Drop for Tiles { + fn drop(&mut self) { + let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + let Some(pool) = pool.as_mut() else { + return; + }; + for i in 0..self.at.len() as u64 { + let key = self.first + i; + let Some(held) = pool.held.get_mut(&key) else { + continue; + }; + held.windows -= 1; + if held.windows == 0 { + let Held { heap, tile, .. } = *held; + pool.held.remove(&key); + pool.free_tile(heap, tile); + } + } + STATS[6].fetch_add(1, Ordering::Relaxed); + } +} + +impl Pool { + /// Tile `tile` of heap `heap` is held by no window: free. A heap with + /// every tile free goes back to the system (unless it is the only one + /// left): the pool grew to 3.8 GB in the world's first minutes and kept + /// it while windows were let go (2026-11-30), on a PC short of memory. + /// (Only from [`Tiles`]' drop, which comes once the card is done with + /// the window: nothing reads the heap any more.) + fn free_tile(&mut self, heap: u32, tile: u32) { + STATS[2].fetch_sub(1, Ordering::Relaxed); + let alive = self.heaps.iter().filter(|h| h.is_some()).count(); + let Some(h) = self.heaps[heap as usize].as_mut() else { + return; + }; + h.free.push(tile); + if h.free.len() == heap_tiles() as usize && alive > 1 { + self.heaps[heap as usize] = None; + STATS[7].fetch_add(1, Ordering::Relaxed); + } + } + + /// The heap to take a new tile from: the one with the fewest free tiles + /// (others empty out and go back), or a new one. + fn heap_for_tile(&mut self, device: &ID3D12Device) -> Option<usize> { + let found = self + .heaps + .iter() + .enumerate() + .filter_map(|(i, h)| h.as_ref().filter(|h| !h.free.is_empty()).map(|h| (h.free.len(), i))) + .min() + .map(|(_, i)| i); + if found.is_some() { + return found; + } + let made = new_heap(device)?; + match self.heaps.iter().position(Option::is_none) { + Some(i) => { + self.heaps[i] = Some(made); + Some(i) + } + None => { + self.heaps.push(Some(made)); + Some(self.heaps.len() - 1) + } + } + } +} + +fn buffer_desc(bytes: u64) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + } +} + +/// A new heap for the pool, mapped for the CPU. +fn new_heap(device: &ID3D12Device) -> Option<Heap> { + let desc = D3D12_HEAP_DESC { + SizeInBytes: u64::from(heap_tiles()) * TILE, + Properties: D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + // Write-back, as the buffers of windows outside the pool are + // (`Host::shared_buffer`): the CPU reads tiles too (the sends of + // `crate::host::send` and the compares of `crate::shadow`), and + // write-combined memory is not cached for reads: 44.9 MB a frame + // took 16.4 ms to send out of it in town (2.7 GB/s). + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS, + }; + // SAFETY: plain creation; out pointers are ours. + unsafe { + let mut heap: Option<ID3D12Heap> = None; + if let Err(e) = device.CreateHeap::<ID3D12Heap>(&raw const desc, &raw mut heap) { + tracing::warn!(error = %e, "no heap for the windows' shared copy: windows get buffers of their own"); + return None; + } + let heap = heap?; + let whole = buffer_desc(desc.SizeInBytes); + let mut cpu: Option<ID3D12Resource> = None; + if let Err(e) = device.CreatePlacedResource(&heap, 0, &raw const whole, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut cpu) { + tracing::warn!(error = %e, "no buffer over a heap of the windows' shared copy"); + return None; + } + let cpu = cpu?; + let mut data = std::ptr::null_mut(); + if let Err(e) = cpu.Map(0, None, Some(&raw mut data)) { + tracing::warn!(error = %e, "a heap of the windows' shared copy does not map"); + return None; + } + crate::host::name(&cpu, || "windows' shared copy of title memory".to_owned()); + STATS[5].fetch_add(1, Ordering::Relaxed); + Some(Heap { + heap, + _cpu: cpu, + data: data as usize, + // Taken from the end: low tiles first. + free: (0..heap_tiles()).rev().collect(), + }) + } +} + +/// A window `[start, start + len)` in the pool: a reserved buffer of its +/// length over the pool's tiles of its title memory, given its tiles on the +/// host's queue (before any submission that reads it), and where the CPU +/// fills each. `None` if `start` is not on a tile's line or the pool has no +/// room: the window then gets a buffer of its own. +/// +/// Tiles new to the pool hold whatever the heap held: a new window's copy +/// starts with every page uncopied (`crate::shadow`), so its first refresh +/// fills what it reads; a tile it shares holds the other window's bytes, +/// which are title bytes too. +pub(crate) fn window(start: u64, len: u64) -> Option<(ID3D12Resource, Tiles)> { + if !start.is_multiple_of(TILE) || len == 0 { + return None; + } + let host = crate::host::host()?; + let device = &host.device; + let tiles = len.div_ceil(TILE); + let first = start / TILE; + // The reserved buffer first: if the card refuses, nothing is taken. + let desc = buffer_desc(tiles * TILE); + let mut buffer: Option<ID3D12Resource> = None; + // SAFETY: plain creation. + if let Err(e) = unsafe { device.CreateReservedResource(&raw const desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut buffer) } { + STATS[1].fetch_add(1, Ordering::Relaxed); + tracing::warn!(error = %e, start = format_args!("{start:#x}"), len, "no reserved buffer for a window: it gets a buffer of its own"); + return None; + } + let buffer = buffer?; + let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + let pool = pool.get_or_insert_with(Pool::default); + // Each tile: held already, or a free tile (a new heap if none). + let mut placed: Vec<(u32, u32)> = Vec::with_capacity(tiles as usize); + for i in 0..tiles { + let key = first + i; + if let Some(held) = pool.held.get_mut(&key) { + held.windows += 1; + placed.push((held.heap, held.tile)); + STATS[3].fetch_add(1, Ordering::Relaxed); + continue; + } + let heap = match pool.heap_for_tile(device) { ~~~~ --- Could this rollback bookkeeping get a CPU-only test with a mix of already-shared and newly allocated tiles? On a later-tile allocation failure, this branch decrements the refs for every entry in `placed` and returns tiles whose count reaches zero; a regression here could either strand tiles or free one still used by another window. The added arena test covers run coalescing, but not this lifecycle path. Factoring the refcount/rollback operations into a pure helper would make the failure and overlapping-window cases testable without D3D12. AI-assisted review; I traced the partial-allocation cleanup against the shared-window reference counts.
vi-tester-8gb commented 2026-12-01 16:16:08 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by vi-tester-8gb on 2026-12-01T16:16:08Z.


A result from an 8 GB laptop card, where the arena with card tiles came out slower. One session, played by hand, so treat it as one data point.

PC: RTX 5060 Laptop GPU 8 GB (driver 621.24), i7-13620H, 32 GB RAM, Windows 11.
Build: v2026.11.30.03 + #4206 + #4294 + #4943 (first commit only) + #4947 (with e41f18ea) + this PR (all eight commits, so #4750 included), local --release. Series S profile, DLSS Performance, DLSS FG 2x, --fps 16, VICTORY_SAMPLED_EVICT=1, VICTORY_WAIT_RESIDENT=textures, VICTORY_VRAM_BUDGET_MB=6400, VICTORY_WINDOW_ARENA=1 (card tiles on by default). The log confirmed the arena was on.

Compared with our previous session (same base and settings, no arena and no #4943/#4947, but with #4581 + #4880):

arena + card tiles (21 min) previous (79 min)
card time per frame (card meter, title lists), median / p90 62.7 / 91.9 ms 48.1 / 73.2 ms
submitting thread preparing, median / p90 54.9 / 79.8 ms 46.6 / 68.6 ms
PC memory shared with the card, median 5753 MB 6803 MB
frames over 100 ms, min 3-10 / 10-20 17.0 % / 10.9 % 4.5 % / 2.5 %

So the arena did what it says on the memory side (about 1 GB less shared memory), but on this card the card's own time went up, not down.

End of the session: after 21 minutes, DXGI_ERROR_DEVICE_HUNG (0x887A0006) with nvlddmkm event 153 three times. The log says the submitting thread was between submissions (nothing of ours was running on the card), of 0 lists, for 12392.7 ms just before. The card had ~470 MB of real headroom (6531 of ~7000 MB), so unlike our earlier hangs it wasn't at its budget. I can't say the arena caused it: we've had hangs without it, and this was one run. But it's the first hang we've seen with this much headroom, and the reserved buffers / tile mappings are the new thing in this run.

Next we'll run the same build with the arena off (just #4943 + #4947) to separate the two.

Written up with help from Claude (AI); numbers are from our own logs.

<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:comment:7317319392 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/4922#issuecomment-7317319392). Originally posted by [vi-tester-8gb](https://github.com/vi-tester-8gb) on 2026-12-01T16:16:08Z. --- A result from an 8 GB laptop card, where the arena with card tiles came out slower. One session, played by hand, so treat it as one data point. **PC:** RTX 5060 Laptop GPU 8 GB (driver 621.24), i7-13620H, 32 GB RAM, Windows 11. **Build:** `v2026.11.30.03` + #4206 + #4294 + #4943 (first commit only) + #4947 (with e41f18ea) + this PR (all eight commits, so #4750 included), local `--release`. Series S profile, DLSS Performance, DLSS FG 2x, `--fps 16`, `VICTORY_SAMPLED_EVICT=1`, `VICTORY_WAIT_RESIDENT=textures`, `VICTORY_VRAM_BUDGET_MB=6400`, **`VICTORY_WINDOW_ARENA=1`** (card tiles on by default). The log confirmed the arena was on. Compared with our previous session (same base and settings, no arena and no #4943/#4947, but with #4581 + #4880): | | arena + card tiles (21 min) | previous (79 min) | |---|---|---| | card time per frame (card meter, title lists), median / p90 | **62.7 / 91.9 ms** | 48.1 / 73.2 ms | | submitting thread preparing, median / p90 | 54.9 / 79.8 ms | 46.6 / 68.6 ms | | PC memory shared with the card, median | 5753 MB | 6803 MB | | frames over 100 ms, min 3-10 / 10-20 | 17.0 % / 10.9 % | 4.5 % / 2.5 % | So the arena did what it says on the memory side (about 1 GB less shared memory), but on this card the card's own time went up, not down. **End of the session:** after 21 minutes, `DXGI_ERROR_DEVICE_HUNG` (0x887A0006) with nvlddmkm event 153 three times. The log says `the submitting thread was between submissions (nothing of ours was running on the card), of 0 lists, for 12392.7 ms` just before. The card had ~470 MB of real headroom (6531 of ~7000 MB), so unlike our earlier hangs it wasn't at its budget. I can't say the arena caused it: we've had hangs without it, and this was one run. But it's the first hang we've seen with this much headroom, and the reserved buffers / tile mappings are the new thing in this run. Next we'll run the same build with the arena off (just #4943 + #4947) to separate the two. _Written up with help from Claude (AI); numbers are from our own logs._
xteral67 commented 2026-12-01 17:01:13 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by xteral67 on 2026-12-01T17:01:13Z.


Thanks for testing. Two notes: (1) I'll add a CPU-only test for the rollback path. (2) To split the card-time rise, a run with VICTORY_WINDOW_ARENA=1 VICTORY_WINDOW_ARENA_CARD=0 (arena on, card tiles off, windows' old card buffers) next to your arena-off run would show whether it is the shared card tiles or something else in the build; on an 8 GB card the windows' card room is about 9 % of the budget, so the tiles compete with textures there. I can't tell from here whether the hang is related.

<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:comment:7318619514 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/4922#issuecomment-7318619514). Originally posted by [xteral67](https://github.com/xteral67) on 2026-12-01T17:01:13Z. --- Thanks for testing. Two notes: (1) I'll add a CPU-only test for the rollback path. (2) To split the card-time rise, a run with `VICTORY_WINDOW_ARENA=1 VICTORY_WINDOW_ARENA_CARD=0` (arena on, card tiles off, windows' old card buffers) next to your arena-off run would show whether it is the shared card tiles or something else in the build; on an 8 GB card the windows' card room is about 9 % of the budget, so the tiles compete with textures there. I can't tell from here whether the hang is related.
trustno1-coder commented 2026-12-01 18:28:21 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by trustno1-coder on 2026-12-01T18:28:21Z.


Closing this as part of moving main to the texture and video-memory rework (v2026.12.01.01-test). A lot of the code changed, and this pull request no longer applies cleanly to it; it would need to be rewritten against the new main rather than rebased. Thank you for the work. If the change is still needed, please open a new pull request based on the current main.

<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:comment:7320999755 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/4922#issuecomment-7320999755). Originally posted by [trustno1-coder](https://github.com/trustno1-coder) on 2026-12-01T18:28:21Z. --- Closing this as part of moving main to the texture and video-memory rework (v2026.12.01.01-test). A lot of the code changed, and this pull request no longer applies cleanly to it; it would need to be rewritten against the new main rather than rebased. Thank you for the work. If the change is still needed, please open a new pull request based on the current main.

Pull request closed

Sign in to join this conversation.
No reviewers
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
trustno1-coder/VIctory-NVIDIA!4922
No description provided.