Browse Source

The threads a frame waits for are kept on the fast cores (VICTORY_FAST_CORES=0: not; 1: without the helpers)

cpu_sets and keep_on_fast_cores are fxceless/victory-fork's (framelog.rs,
commit 0b0074e0). Asked for by: submit, relay, late-wait, heap-sync, aside;
and the helpers of the wide copies (refreshes, fills, snapshots) and of the
landings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
local 2 ngày trước cách đây
mục cha
commit
96f2f32e84

+ 98 - 0
crates/victory-gpu/src/cores.rs

@@ -0,0 +1,98 @@
+//! Which processors our own threads run on, where a processor has two kinds
+//! of cores. `cpu_sets` and `keep_on_fast_cores` are fxceless/victory-fork's
+//! (`framelog.rs`, commit 0b0074e0, GPL-3.0-or-later, as this).
+
+/// The system's processor sets of group 0: each one's id and its efficiency
+/// class (higher is faster).
+fn cpu_sets() -> Vec<(u32, u8)> {
+    use windows_sys::Win32::System::SystemInformation::{GetSystemCpuSetInformation, SYSTEM_CPU_SET_INFORMATION};
+    use windows_sys::Win32::System::Threading::GetCurrentProcess;
+    let mut bytes = 0u32;
+    // SAFETY: a size query, then the call into a buffer of that size.
+    unsafe { GetSystemCpuSetInformation(std::ptr::null_mut(), 0, &mut bytes, GetCurrentProcess(), 0) };
+    let mut buffer = vec![0u64; (bytes as usize).div_ceil(8).max(1)];
+    // SAFETY: as above; the buffer holds `bytes` bytes, aligned for the records.
+    let ok = unsafe { GetSystemCpuSetInformation(buffer.as_mut_ptr().cast(), bytes, &mut bytes, GetCurrentProcess(), 0) };
+    let mut sets = Vec::new();
+    let mut at = 0usize;
+    while ok != 0 && at + size_of::<SYSTEM_CPU_SET_INFORMATION>() <= bytes as usize {
+        // SAFETY: a record inside the buffer; each says its own size.
+        let info = unsafe { &*(buffer.as_ptr().cast::<u8>().add(at).cast::<SYSTEM_CPU_SET_INFORMATION>()) };
+        if info.Size == 0 {
+            break;
+        }
+        // SAFETY: the record's type is CpuSet (the only one there is).
+        let set = unsafe { &info.Anonymous.CpuSet };
+        if set.Group == 0 {
+            sets.push((set.Id, set.EfficiencyClass));
+        }
+        at += info.Size as usize;
+    }
+    sets
+}
+
+/// The sets of the fastest class, if there are slower ones too.
+fn fast_of(sets: &[(u32, u8)]) -> Vec<u32> {
+    let best = sets.iter().map(|c| c.1).max().unwrap_or(0);
+    let fast: Vec<u32> = sets.iter().filter(|c| c.1 == best).map(|c| c.0).collect();
+    if fast.len() == sets.len() { Vec::new() } else { fast }
+}
+
+/// `VICTORY_FAST_CORES`: 0: no thread asks; 1: the threads a frame waits for
+/// one by one; 2 (the default): the threads they share their work with too.
+fn stage() -> u32 {
+    static STAGE: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
+    *STAGE.get_or_init(|| std::env::var("VICTORY_FAST_CORES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(2))
+}
+
+/// Asks the system to run the calling thread, which a frame waits for, on
+/// the fast cores only, where the processor has two kinds. That fork's submit
+/// thread was found on a slow one in 1,529 looks of 24,021. (A selection of
+/// processors is a preference the scheduler keeps unless nothing of it is
+/// free.) The title's threads are not asked for.
+pub(crate) fn keep_on_fast_cores(what: &str) {
+    ask(what, 1);
+}
+
+/// [`keep_on_fast_cores`] for one of the threads a submission's preparing or
+/// a landing shares its work with.
+pub(crate) fn keep_helper_on_fast_cores(what: &str) {
+    ask(what, 2);
+}
+
+fn ask(what: &str, from: u32) {
+    use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadSelectedCpuSets};
+    if stage() < from {
+        return;
+    }
+    static FAST: std::sync::OnceLock<(Vec<u32>, usize)> = std::sync::OnceLock::new();
+    let (fast, of) = FAST.get_or_init(|| {
+        let sets = cpu_sets();
+        (fast_of(&sets), sets.len())
+    });
+    // All alike (or nothing known): nothing to ask for.
+    if fast.is_empty() {
+        return;
+    }
+    // SAFETY: our own thread and a list of the system's own set ids.
+    let ok = unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), fast.as_ptr(), fast.len() as u32) };
+    if ok == 0 {
+        tracing::warn!(what, error = %std::io::Error::last_os_error(), "the thread could not be kept on the fast cores");
+    } else {
+        tracing::info!(what, fast = fast.len(), of, "the thread is kept on the fast cores (VICTORY_FAST_CORES=0: not)");
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn the_fast_cores_are_those_of_the_best_class_if_there_is_a_worse_one() {
+        assert_eq!(fast_of(&[(256, 1), (257, 1), (258, 0)]), [256, 257]);
+        assert!(fast_of(&[(256, 0), (257, 0)]).is_empty());
+        assert!(fast_of(&[]).is_empty());
+        assert!(!cpu_sets().is_empty());
+        std::thread::spawn(|| keep_on_fast_cores("test")).join().unwrap();
+    }
+}

+ 1 - 0
crates/victory-gpu/src/descriptor.rs

@@ -216,6 +216,7 @@ pub(crate) fn begin_sync_heaps() -> SyncedHeaps {
     static THREAD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
     STARTED.call_once(|| {
         let made = std::thread::Builder::new().name("victory-heap-sync".into()).spawn(|| {
+            crate::cores::keep_on_fast_cores("victory-heap-sync");
             let rounds = || SYNC_ROUNDS.0.lock().unwrap_or_else(|e| e.into_inner());
             /// A round is over, however it ends.
             struct Over;

+ 2 - 0
crates/victory-gpu/src/host.rs

@@ -2833,6 +2833,7 @@ fn land() {
 /// value while the submitting thread waits for that thread would never
 /// see it.
 fn late_helper() {
+    crate::cores::keep_on_fast_cores("victory-late-wait");
     let Some(host) = host() else {
         return;
     };
@@ -2963,6 +2964,7 @@ struct RelayFetch {
 /// anything a caller of [`Host::settle`] may hold: resetting the landed
 /// lists and looking at what queues hold are left to [`late_helper`].
 fn relay_worker() {
+    crate::cores::keep_on_fast_cores("victory-relay");
     let Some(host) = host() else {
         return;
     };

+ 4 - 1
crates/victory-gpu/src/host/aside.rs

@@ -63,7 +63,10 @@ pub(crate) fn begin(work: impl FnOnce() -> Vec<Refresh> + Send + 'static) -> std
         let (send, jobs) = std::sync::mpsc::channel::<Job>();
         std::thread::Builder::new()
             .name("victory-aside".into())
-            .spawn(move || jobs.into_iter().for_each(|job| job()))
+            .spawn(move || {
+                crate::cores::keep_on_fast_cores("victory-aside");
+                jobs.into_iter().for_each(|job| job())
+            })
             .ok()
             .map(|_| Mutex::new(send))
     });

+ 4 - 1
crates/victory-gpu/src/land.rs

@@ -237,7 +237,10 @@ impl Pool {
         }));
         for i in 1..threads {
             // (A helper that is not there is only missed.)
-            let _ = std::thread::Builder::new().name(format!("victory-land-{i}")).spawn(move || pool.help());
+            let _ = std::thread::Builder::new().name(format!("victory-land-{i}")).spawn(move || {
+                crate::cores::keep_helper_on_fast_cores("victory-land");
+                pool.help()
+            });
         }
         pool
     }

+ 2 - 0
crates/victory-gpu/src/lib.rs

@@ -20,6 +20,8 @@ mod capture;
 pub mod console;
 #[cfg(all(windows, feature = "diagnostics"))]
 mod copystat;
+#[cfg(windows)]
+mod cores;
 pub mod descriptor;
 pub mod device;
 #[cfg(windows)]

+ 1 - 0
crates/victory-gpu/src/queue/behind.rs

@@ -439,6 +439,7 @@ pub(super) fn on() -> bool {
             use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_ABOVE_NORMAL};
             // SAFETY: this thread's own priority.
             unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL) };
+            crate::cores::keep_on_fast_cores("victory-submit");
             OURS.set(true);
             let ended = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| LANE.serve()));
             if ended.is_err() {

+ 1 - 0
crates/victory-gpu/src/shadow.rs

@@ -1453,6 +1453,7 @@ fn workers() -> &'static Workers {
     STARTED.call_once(|| {
         for i in 0..wide_threads() {
             let _ = std::thread::Builder::new().name(format!("victory-wide-{i}")).spawn(move || {
+                crate::cores::keep_helper_on_fast_cores("victory-wide");
                 let workers = WORKERS.get().expect("made above");
                 loop {
                     let job = {