Просмотр исходного кода

Sets of heap slots are bits, the heaps' records have threads of their own, what is mirrored of them is counted

Co-Authored-By: Claude Opus 5.5 <[email protected]>
local 1 день назад
Родитель
Сommit
c3e643ebbd

+ 32 - 4
crates/victory-gpu/src/descriptor.rs

@@ -301,6 +301,7 @@ pub(crate) fn sync_heaps() {
     }
     let started = std::time::Instant::now();
     let (mut pages, mut looked, mut mirrored, mut tabled, mut later) = (0u64, 0u64, 0u64, 0u64, 0u64);
+    let mut kinds = [0u64; 6];
     let mut page_bytes: Vec<u8> = Vec::new();
     let mut changed: Vec<u32> = Vec::new();
     let mut wait: Vec<u32> = Vec::new();
@@ -322,7 +323,7 @@ pub(crate) fn sync_heaps() {
         // since: a shader may pick them by index.
         let before = host.copied_before(frame);
         let of_tables = std::sync::atomic::AtomicU64::new(0);
-        crate::land::each_view(before.len().div_ceil(SYNC_AT_A_TIME), &|n| {
+        crate::land::each_view(true, before.len().div_ceil(SYNC_AT_A_TIME), &|n| {
             for &index in before.chunks(SYNC_AT_A_TIME).nth(n).unwrap_or_default() {
                 if host.copied_tabled(index, frame) {
                     of_tables.fetch_add(1, Relaxed);
@@ -334,6 +335,7 @@ pub(crate) fn sync_heaps() {
         let of_tables = of_tables.into_inner();
         tabled += of_tables;
         mirrored += before.len() as u64 - of_tables;
+        kinds[4] += before.len() as u64 - of_tables;
         // Those of the changed pages, made together at the end.
         let mut make: Vec<u32> = Vec::new();
         for (range_from, range_end) in written.take(start as usize, end as usize) {
@@ -388,12 +390,22 @@ pub(crate) fn sync_heaps() {
                         }
                         make.push(index);
                         mirrored += 1;
+                        kinds[if heap.samplers() {
+                            3
+                        } else if word(0) != VIEW_TAG {
+                            0
+                        } else if word(2) >> KIND_SHIFT == 0 {
+                            1
+                        } else {
+                            2
+                        }] += 1;
+                        kinds[5] += u64::from(!heap.samplers() && host.near_tabled(index, frame));
                     }
                 }
                 page += crate::watch::PAGE;
             }
         }
-        crate::land::each_view(make.len().div_ceil(SYNC_AT_A_TIME), &|n| {
+        crate::land::each_view(true, make.len().div_ceil(SYNC_AT_A_TIME), &|n| {
             for &index in make.chunks(SYNC_AT_A_TIME).nth(n).unwrap_or_default() {
                 host.mirror(index, start + u64::from(index) * step, false);
             }
@@ -407,8 +419,16 @@ pub(crate) fn sync_heaps() {
     for (count, n) in SYNCED.iter().zip([pages, looked, mirrored, micros, tabled, later]) {
         count.fetch_add(n, Relaxed);
     }
+    for (count, n) in SYNCED_KINDS.iter().zip(kinds) {
+        count.fetch_add(n, Relaxed);
+    }
 }
 
+/// Of those mirrored, since the last frame line: no view, a view of an object,
+/// another, a sampler; waited and no draw came; next to a slot of a table's.
+#[cfg(windows)]
+static SYNCED_KINDS: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6];
+
 /// Records [`sync_heaps`] gives a thread at a time.
 #[cfg(windows)]
 const SYNC_AT_A_TIME: usize = 256;
@@ -436,20 +456,28 @@ pub(crate) fn sync_line(frames: f64) {
         );
     }
     let [pages, looked, mirrored, micros, tabled, later, waited] = [0, 1, 2, 3, 4, 5, 6].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed));
+    let kinds = [0, 1, 2, 3, 4, 5].map(|i| SYNCED_KINDS[i].swap(0, std::sync::atomic::Ordering::Relaxed) as f64 / frames);
     if pages == 0 {
         return;
     }
     tracing::info!(
         "descriptor records the title copied into its heap as bytes (VICTORY_HEAP_SYNC=0: not looked for): per frame \
          {:.1} changed heap pages, {:.0} slots looked at, {:.1} whose record was new and was mirrored, {:.1} new ones of \
-         draws' tables left to the draws, {:.1} that waited for a draw first, {:.2} ms ({:.2} ms waited for)",
+         draws' tables left to the draws, {:.1} that waited for a draw first, {:.2} ms ({:.2} ms waited for); of the mirrored \
+         {:.0} no views, {:.0} of objects, {:.0} others, {:.0} samplers, {:.0} that waited and no draw came, {:.0} near a table's slot",
         pages as f64 / frames,
         looked as f64 / frames,
         mirrored as f64 / frames,
         tabled as f64 / frames,
         later as f64 / frames,
         micros as f64 / 1000.0 / frames,
-        waited as f64 / 1000.0 / frames
+        waited as f64 / 1000.0 / frames,
+        kinds[0],
+        kinds[1],
+        kinds[2],
+        kinds[3],
+        kinds[4],
+        kinds[5]
     );
 }
 

+ 89 - 17
crates/victory-gpu/src/descriptor/host.rs

@@ -13,6 +13,65 @@ use windows::Win32::Graphics::Dxgi::Common::*;
 use super::{VIEW_TAG, View, view_at};
 use crate::host::host;
 
+/// A set of a heap's slots, a bit for each: no lock (a pass that went through
+/// a set of 70,000 under its lock kept everyone who writes slots waiting for
+/// 5 ms of a frame, timeline thin-6).
+struct Slots(Vec<std::sync::atomic::AtomicU64>);
+
+impl Slots {
+    fn new(count: usize) -> Self {
+        let mut bits = Vec::new();
+        bits.resize_with(count.div_ceil(64), Default::default);
+        Slots(bits)
+    }
+
+    fn put(&self, slot: u32) {
+        if let Some(bits) = self.0.get(slot as usize / 64) {
+            bits.fetch_or(1 << (slot % 64), std::sync::atomic::Ordering::AcqRel);
+        }
+    }
+
+    /// Whether it was there.
+    fn remove(&self, slot: u32) -> bool {
+        use std::sync::atomic::Ordering::{AcqRel, Acquire};
+        let bit = 1 << (slot % 64);
+        self.0.get(slot as usize / 64).is_some_and(|bits| {
+            bits.load(Acquire) & bit != 0 && bits.fetch_and(!bit, AcqRel) & bit != 0
+        })
+    }
+
+    fn of(n: usize, mut bits: u64, out: &mut Vec<u32>, which: &impl Fn(u32) -> bool) {
+        while bits != 0 {
+            let slot = n as u32 * 64 + bits.trailing_zeros();
+            bits &= bits - 1;
+            if which(slot) {
+                out.push(slot);
+            }
+        }
+    }
+
+    /// Those that `which` says, in order.
+    fn all(&self, which: impl Fn(u32) -> bool) -> Vec<u32> {
+        let mut out = Vec::new();
+        for (n, bits) in self.0.iter().enumerate() {
+            Self::of(n, bits.load(std::sync::atomic::Ordering::Acquire), &mut out, &which);
+        }
+        out
+    }
+
+    /// All of them, and none is left.
+    fn take(&self) -> Vec<u32> {
+        use std::sync::atomic::Ordering::{AcqRel, Acquire};
+        let mut out = Vec::new();
+        for (n, bits) in self.0.iter().enumerate() {
+            if bits.load(Acquire) != 0 {
+                Self::of(n, bits.swap(0, AcqRel), &mut out, &|_| true);
+            }
+        }
+        out
+    }
+}
+
 /// The record each slot of a heap was last made from, and a lock for every
 /// few hundredth of the slots: whoever makes a slot holds its lock, and no
 /// other.
@@ -123,10 +182,10 @@ pub(crate) struct HostHeap {
     /// (and its memory a host copy) only when something reads it: a draw
     /// through a table, or [`HostHeap::buffer_slots`] for shaders that pick
     /// buffers from the whole heap.
-    buffers: Mutex<std::collections::BTreeSet<u32>>,
+    buffers: Slots,
     /// Of those and of the slots that left the set: the ones written since
     /// [`HostHeap::buffer_changes`] last took them.
-    changed: Mutex<std::collections::HashSet<u32>>,
+    changed: Slots,
     /// Title slots holding a view of a texture the title may fill itself (a
     /// placed texture, a texture object), with the frame from which they
     /// are due: such a texture is uploaded when a draw reads it through a
@@ -1487,8 +1546,8 @@ impl HostHeap {
             free: std::sync::atomic::AtomicU32::new(extra),
             too_long: std::sync::atomic::AtomicU32::new(u32::MAX),
             strides,
-            buffers: Mutex::default(),
-            changed: Mutex::default(),
+            buffers: Slots::new(count as usize),
+            changed: Slots::new(count as usize),
             textures: Mutex::default(),
             tabled: (0..if sampler { 0 } else { count })
                 .map(|_| std::sync::atomic::AtomicU32::new(0))
@@ -2351,22 +2410,19 @@ impl HostHeap {
 
     /// The title slots that hold buffer views.
     pub(crate) fn buffer_slots(&self) -> Vec<u32> {
-        let buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
-        buffers.iter().copied().collect()
+        self.buffers.all(|_| true)
     }
 
     /// Of [`HostHeap::buffer_slots`], those of one of `parts` parts: every
     /// slot is in the same part each time.
     pub(crate) fn buffer_slots_of(&self, part: u32, parts: u32) -> Vec<u32> {
-        let buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
-        buffers.iter().copied().filter(|slot| slot % parts == part).collect()
+        self.buffers.all(|slot| slot % parts == part)
     }
 
     /// The title slots whose buffer view was written, or went, since the
     /// last call.
     pub(crate) fn buffer_changes(&self) -> Vec<u32> {
-        let mut changed = self.changed.lock().unwrap_or_else(|e| e.into_inner());
-        std::mem::take(&mut *changed).into_iter().collect()
+        self.changed.take()
     }
 
     /// Records what title slot `index` now holds for shaders that pick
@@ -2455,18 +2511,14 @@ impl HostHeap {
             // dword, either value is one the slot had).
             unsafe { (*data as *mut u32).add(index as usize).write_volatile(stride.unwrap_or(0) | kind) };
         }
-        let mut buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
         let was = if stride.is_some() {
-            buffers.insert(index);
+            self.buffers.put(index);
             true
         } else {
-            buffers.remove(&index)
+            self.buffers.remove(index)
         };
         if was {
-            self.changed
-                .lock()
-                .unwrap_or_else(|e| e.into_inner())
-                .insert(index);
+            self.changed.put(index);
         }
         stale
     }
@@ -2889,6 +2941,13 @@ impl HostHeap {
         stamp != 0 && now.wrapping_sub(stamp) & !TABLED_READ <= COPIED_FRAMES
     }
 
+    /// Whether a slot within 64 of `index` is a table's lately (counted for
+    /// the log: such a slot is likely one of a table not read yet).
+    pub(crate) fn near_tabled(&self, index: u32, frame: u64) -> bool {
+        let first = index & !63;
+        (first..first + 64).any(|i| i < self.count && self.copied_tabled(i, frame))
+    }
+
     /// New records the title copied into slots `slots` in `frame` wait for
     /// the draw that may read them through a table.
     pub(crate) fn copied_wait(&self, frame: u64, slots: Vec<u32>) {
@@ -5267,6 +5326,19 @@ mod tests {
         assert_eq!(slots(u64::MAX), [2]);
     }
 
+    #[test]
+    fn a_set_of_slots_holds_what_was_put_in() {
+        let set = Slots::new(200);
+        for slot in [199, 0, 64, 63, 130, 64] {
+            set.put(slot);
+        }
+        assert_eq!(set.all(|_| true), [0, 63, 64, 130, 199]);
+        assert_eq!(set.all(|slot| slot % 2 == 0), [0, 64, 130]);
+        assert!(set.remove(64) && !set.remove(64) && !set.remove(5));
+        assert_eq!(set.take(), [0, 63, 130, 199]);
+        assert!(set.take().is_empty());
+    }
+
     /// A slot a draw read through a table leaves the queue; the title's
     /// next write of it waits for its draw, and is due after the grace
     /// frames if none reads it.

+ 1 - 1
crates/victory-gpu/src/draw.rs

@@ -806,7 +806,7 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho
     const AT_A_TIME: usize = 256;
     let parts: Vec<&[u32]> = slots.chunks(AT_A_TIME).collect();
     let found: Vec<std::sync::OnceLock<Vec<_>>> = parts.iter().map(|_| Default::default()).collect();
-    crate::land::each_view(parts.len(), &|n| {
+    crate::land::each_view(false, parts.len(), &|n| {
         let looked: Vec<_> = parts[n].iter().map(|&index| (index, look(index))).collect();
         // (After each piece while the device lives: a cheap query.)
         if alive

+ 12 - 9
crates/victory-gpu/src/land.rs

@@ -325,15 +325,18 @@ pub(crate) fn each(count: usize, f: &(dyn Fn(usize) + Sync)) {
 }
 
 /// Calls `f` with every number below `count`, on this thread and on threads
-/// kept for making descriptors (`VICTORY_VIEW_THREADS`, 5 with this one; 1:
-/// on this one alone).
-pub(crate) fn each_view(count: usize, f: &(dyn Fn(usize) + Sync)) {
-    static POOL: OnceLock<&'static Pool> = OnceLock::new();
-    POOL.get_or_init(|| {
-        let threads = std::env::var("VICTORY_VIEW_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(5usize);
-        Pool::new("victory-views", threads.clamp(1, 16))
-    })
-    .each(count, f);
+/// kept for making descriptors (`VICTORY_VIEW_THREADS`, 4 with this one; 1:
+/// on this one alone). Those for `records`, the heaps' records copied as
+/// bytes, are others than those for the views picked by index: submissions
+/// wait for the first, lists for the second, and each kept the other waiting.
+pub(crate) fn each_view(records: bool, count: usize, f: &(dyn Fn(usize) + Sync)) {
+    static POOLS: [OnceLock<&'static Pool>; 2] = [const { OnceLock::new() }; 2];
+    POOLS[usize::from(records)]
+        .get_or_init(|| {
+            let threads = std::env::var("VICTORY_VIEW_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(4usize);
+            Pool::new(if records { "victory-records" } else { "victory-views" }, threads.clamp(1, 16))
+        })
+        .each(count, f);
 }
 
 /// A piece to land: the copy's number, the title address, its bytes.