From 6ae2eae20ece7c603f655efda8e31327109fe53d Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 22:54:49 +0100 Subject: [PATCH] STRA-338 size-nce: cpu_report, rust_platform and rust_topology parsers take text / data probe (read_brand, has_avx2, avx512_flags, brand_text), cpu_kernel_report (probe_groups, core_line, process_line, differs_in_avx512), stack_size (check_stack_limit, check_stack_size), cores (parse_leading_number, mask_cpus, first_cpu_of_each_core), detect_cpu_topology (CpuInfo, scan_cpus, count_cores, plain_cores, hybrid_cores, topology_from). The pure steps take the sysfs text or the CPU table; the reads keep their order. rust_platform_win.rs: wide doc lines wrapped only (type-checked and tested on the Windows host). Functions over a limit in these files 5 -> 0, functions or lines over the width 9 -> 0. Proof: old vs new on the live host and on captured sysfs text, synthetic hybrid / multi-package tables and 120k fuzzed tables. --- crates/native-cpu-expert/src/cpu_report.rs | 234 +++++++++++------- crates/native-cpu-expert/src/rust_platform.rs | 98 +++++--- .../src/rust_platform_win.rs | 11 +- crates/native-cpu-expert/src/rust_topology.rs | 177 ++++++++----- 4 files changed, 327 insertions(+), 193 deletions(-) diff --git a/crates/native-cpu-expert/src/cpu_report.rs b/crates/native-cpu-expert/src/cpu_report.rs index a20a8305..edc64cb0 100644 --- a/crates/native-cpu-expert/src/cpu_report.rs +++ b/crates/native-cpu-expert/src/cpu_report.rs @@ -1,8 +1,10 @@ -//! Start-up report of the CPUs the expert kernels run on and of the kernel family chosen for them (operator log only, no behaviour). +//! Start-up report of the CPUs the expert kernels run on and of the kernel family chosen for them (operator log only, +//! no behaviour). //! -//! The kernel family (AVX-512 or AVX2) is decided once per process by `rust_simd::dispatch()`. This report probes every logical CPU the -//! process may run on (a thread pinned to it, `cpuid`, `xgetbv`) and groups the identical ones, so a machine with several packages or -//! with unlike cores shows each kind on its own line, and a core that cannot run the chosen family is named. +//! The kernel family (AVX-512 or AVX2) is decided once per process by `rust_simd::dispatch()`. This report probes every +//! logical CPU the process may run on (a thread pinned to it, `cpuid`, `xgetbv`) and groups the identical ones, so a +//! machine with several packages or with unlike cores shows each kind on its own line, and a core that cannot run the +//! chosen family is named. use core::arch::x86_64::{__cpuid, __cpuid_count, _xgetbv}; #[derive(Clone, PartialEq, Eq)] @@ -14,42 +16,58 @@ struct Core { const AVX512_NAMES: [&str; 6] = ["F", "BW", "VL", "DQ", "VBMI", "VNNI"]; +/// The text of the 48 brand bytes of CPUID leaves 0x80000002..=0x80000004: NULs and blanks trimmed at both ends. +fn brand_text(raw: &[u8]) -> String { + String::from_utf8_lossy(raw).trim_matches(|c: char| c == '\0' || c.is_whitespace()).to_owned() +} + +/// The brand string of the CPU the calling thread runs on; empty when the CPU has no brand leaves. +fn read_brand() -> String { + if __cpuid(0x8000_0000).eax < 0x8000_0004 { + return String::new(); + } + let mut raw = Vec::with_capacity(48); + for leaf in 0x8000_0002..=0x8000_0004u32 { + let r = __cpuid(leaf); + for w in [r.eax, r.ebx, r.ecx, r.edx] { + raw.extend_from_slice(&w.to_le_bytes()); + } + } + brand_text(&raw) +} + +/// AVX2, FMA and F16C usable: the CPUID.1 ECX bits, the YMM state enabled in XCR0, the AVX2 bit of leaf 7. +fn has_avx2(c1: u32, xcr0: u64, l7_ebx: u32) -> bool { + [12, 27, 28, 29].iter().all(|b| c1 & (1 << b) != 0) && xcr0 & 6 == 6 && l7_ebx & (1 << 5) != 0 +} + +/// F, BW, VL, DQ, VBMI, VNNI (in `AVX512_NAMES` order) present and the ZMM state enabled by the OS. +fn avx512_flags(osxsave: bool, xcr0: u64, l7_ebx: u32, l7_ecx: u32) -> [bool; 6] { + let os512 = osxsave && xcr0 & 0xe6 == 0xe6; + let bits = [ + l7_ebx & (1 << 16) != 0, + l7_ebx & (1 << 30) != 0, + l7_ebx & (1 << 31) != 0, + l7_ebx & (1 << 17) != 0, + l7_ecx & (1 << 1) != 0, + l7_ecx & (1 << 11) != 0, + ]; + bits.map(|b| b && os512) +} + /// The features of the core the calling thread runs on. The gates mirror `rust_simd::probe_avx2` / `probe_avx512`. fn probe() -> Core { - // SAFETY: CPUID is always available on x86_64; XGETBV only after the OSXSAVE bit is seen. - unsafe { - let max = __cpuid(0).eax; - let ext = __cpuid(0x8000_0000).eax; - let mut brand = String::new(); - if ext >= 0x8000_0004 { - let mut raw = Vec::with_capacity(48); - for leaf in 0x8000_0002..=0x8000_0004u32 { - let r = __cpuid(leaf); - for w in [r.eax, r.ebx, r.ecx, r.edx] { - raw.extend_from_slice(&w.to_le_bytes()); - } - } - brand = String::from_utf8_lossy(&raw).trim_matches(|c: char| c == '\0' || c.is_whitespace()).to_owned(); - } - if max < 7 { - return Core { brand, avx2: false, avx512: [false; 6] }; - } - let c1 = __cpuid(1).ecx; - let osxsave = c1 & (1 << 27) != 0; - let xcr0 = if osxsave { _xgetbv(0) } else { 0 }; - let l7 = __cpuid_count(7, 0); - let avx2 = [12, 27, 28, 29].iter().all(|b| c1 & (1 << b) != 0) && xcr0 & 6 == 6 && l7.ebx & (1 << 5) != 0; - let os512 = osxsave && xcr0 & 0xe6 == 0xe6; - let bits = [ - l7.ebx & (1 << 16) != 0, - l7.ebx & (1 << 30) != 0, - l7.ebx & (1 << 31) != 0, - l7.ebx & (1 << 17) != 0, - l7.ecx & (1 << 1) != 0, - l7.ecx & (1 << 11) != 0, - ]; - Core { brand, avx2, avx512: bits.map(|b| b && os512) } + let max = __cpuid(0).eax; + let brand = read_brand(); + if max < 7 { + return Core { brand, avx2: false, avx512: [false; 6] }; } + let c1 = __cpuid(1).ecx; + let osxsave = c1 & (1 << 27) != 0; + // SAFETY: XGETBV only after the OSXSAVE bit is seen. + let xcr0 = if osxsave { unsafe { _xgetbv(0) } } else { 0 }; + let l7 = __cpuid_count(7, 0); + Core { brand, avx2: has_avx2(c1, xcr0, l7.ebx), avx512: avx512_flags(osxsave, xcr0, l7.ebx, l7.ecx) } } fn avx512_complete(c: &Core) -> bool { @@ -74,71 +92,119 @@ fn ranges(cpus: &[usize]) -> String { out } -/// One line per kind of logical CPU, then one line with the kernel family the process chose and the switches that changed it. -pub fn cpu_kernel_report() -> Vec { +/// A pinned probe thread for logical CPU `cpu`; a refused pin probes wherever the thread runs (the line then shows +/// that CPU kind). `None` when the probe thread panicked. +fn probe_pinned(cpu: usize) -> Option { + std::thread::spawn(move || { + let previous = crate::rust_topology::pin_current_thread(cpu as i32); + let core = probe(); + crate::rust_topology::restore_thread_affinity(previous); + core + }) + .join() + .ok() +} + +/// Adds `cpu` to the group of identical cores `core` belongs to, or starts a new group. +fn push_group(groups: &mut Vec<(Core, Vec)>, core: Core, cpu: usize) { + match groups.iter_mut().find(|(g, _)| *g == core) { + Some((_, cpus)) => cpus.push(cpu), + None => groups.push((core, vec![cpu])), + } +} + +/// Every logical CPU the process may run on (at most 256), probed on its own thread and grouped by identical features. +fn probe_groups() -> Vec<(Core, Vec)> { let n = std::thread::available_parallelism().map_or(1, |n| n.get()).min(256); let mut groups: Vec<(Core, Vec)> = Vec::new(); for cpu in 0..n { - // a pinned probe thread per logical CPU; a refused pin probes wherever the thread runs (the line then shows that CPU's kind) - let core = std::thread::spawn(move || { - let previous = crate::rust_topology::pin_current_thread(cpu as i32); - let core = probe(); - crate::rust_topology::restore_thread_affinity(previous); - core - }) - .join(); - let Ok(core) = core else { continue }; - match groups.iter_mut().find(|(g, _)| *g == core) { - Some((_, cpus)) => cpus.push(cpu), - None => groups.push((core, vec![cpu])), - } + let Some(core) = probe_pinned(cpu) else { continue }; + push_group(&mut groups, core, cpu); } - let mut lines = Vec::new(); - for (core, cpus) in &groups { - let have: Vec<&str> = AVX512_NAMES.iter().zip(core.avx512).filter(|(_, b)| *b).map(|(n, _)| *n).collect(); - let lacks: Vec<&str> = AVX512_NAMES.iter().zip(core.avx512).filter(|(_, b)| !*b).map(|(n, _)| *n).collect(); - let avx512 = if lacks.is_empty() { - "AVX-512 F/BW/VL/DQ/VBMI/VNNI: all".to_owned() - } else if have.is_empty() { - "AVX-512: none".to_owned() - } else { - format!("AVX-512: has {}, lacks {}", have.join("/"), lacks.join("/")) - }; - lines.push(format!( - "cpu: logical {} ({}): {}; AVX2/FMA/F16C: {}; {}; kernel family on this core: {}", - ranges(cpus), - cpus.len(), - if core.brand.is_empty() { "unknown model" } else { &core.brand }, - if core.avx2 { "yes" } else { "no" }, - avx512, - if avx512_complete(core) { - "AVX-512" - } else if core.avx2 { - "AVX2" - } else { - "none (unsupported)" - } - )); + groups +} + +/// The AVX-512 part of a core line: all of the six extensions, none, or which ones the core has and lacks. +fn avx512_summary(core: &Core) -> String { + let have: Vec<&str> = AVX512_NAMES.iter().zip(core.avx512).filter(|(_, b)| *b).map(|(n, _)| *n).collect(); + let lacks: Vec<&str> = AVX512_NAMES.iter().zip(core.avx512).filter(|(_, b)| !*b).map(|(n, _)| *n).collect(); + if lacks.is_empty() { + "AVX-512 F/BW/VL/DQ/VBMI/VNNI: all".to_owned() + } else if have.is_empty() { + "AVX-512: none".to_owned() + } else { + format!("AVX-512: has {}, lacks {}", have.join("/"), lacks.join("/")) } - let dispatch = crate::rust_simd::dispatch(); +} + +/// The kernel family the core itself can run. +fn core_family(core: &Core) -> &'static str { + if avx512_complete(core) { + "AVX-512" + } else if core.avx2 { + "AVX2" + } else { + "none (unsupported)" + } +} + +/// The line of one group of identical logical CPUs. +fn core_line(core: &Core, cpus: &[usize]) -> String { + format!( + "cpu: logical {} ({}): {}; AVX2/FMA/F16C: {}; {}; kernel family on this core: {}", + ranges(cpus), + cpus.len(), + if core.brand.is_empty() { "unknown model" } else { &core.brand }, + if core.avx2 { "yes" } else { "no" }, + avx512_summary(core), + core_family(core) + ) +} + +/// The environment switches that change the kernel family, in the order they are reported. +fn family_switches() -> Vec<&'static str> { let mut switches = Vec::new(); for name in ["STRATA_FORCE_AVX2", "STRATA_NO_IQ512", "STRATA_NO_IQ256", "STRATA_NO_IQ4NL"] { if std::env::var_os(name).is_some() { switches.push(name); } } - lines.push(format!( + switches +} + +/// The line with the kernel family the process chose and the switches that changed it. +fn process_line(dispatch: &crate::rust_simd::Dispatch, switches: &[&str]) -> String { + format!( "cpu: process kernel family {} (IQ rows: 512-bit {}, 256-bit {}; IQ4_NL {}){}", if dispatch.avx512 { "AVX-512" } else { "AVX2" }, if dispatch.iq512 { "on" } else { "off" }, if dispatch.iq256 { "on" } else { "off" }, if dispatch.iq4nl { "on" } else { "off" }, if switches.is_empty() { String::new() } else { format!("; overridden by {}", switches.join(", ")) } - )); - if groups.len() > 1 + ) +} + +/// True when some group disagrees with the process family in a way that matters: the process uses AVX-512 and the +/// group lacks it, or the group has all of it and the process does not use it. +fn differs_in_avx512(groups: &[(Core, Vec)], dispatch: &crate::rust_simd::Dispatch) -> bool { + groups.len() > 1 && groups.iter().any(|(c, _)| avx512_complete(c) != dispatch.avx512 && (dispatch.avx512 || avx512_complete(c))) - { - lines.push("cpu: WARNING: the logical CPUs differ in AVX-512 support but the kernel family is chosen once per process; a worker pinned to a core without it would fault or be refused".to_owned()); +} + +const MIXED_AVX512_WARNING: &str = concat!( + "cpu: WARNING: the logical CPUs differ in AVX-512 support but the kernel family is chosen once per process; ", + "a worker pinned to a core without it would fault or be refused" +); + +/// One line per kind of logical CPU, then one line with the kernel family the process chose and the switches that +/// changed it. +pub fn cpu_kernel_report() -> Vec { + let groups = probe_groups(); + let mut lines: Vec = groups.iter().map(|(core, cpus)| core_line(core, cpus)).collect(); + let dispatch = crate::rust_simd::dispatch(); + lines.push(process_line(dispatch, &family_switches())); + if differs_in_avx512(&groups, dispatch) { + lines.push(MIXED_AVX512_WARNING.to_owned()); } lines } diff --git a/crates/native-cpu-expert/src/rust_platform.rs b/crates/native-cpu-expert/src/rust_platform.rs index 01b1926d..b79ab3b9 100644 --- a/crates/native-cpu-expert/src/rust_platform.rs +++ b/crates/native-cpu-expert/src/rust_platform.rs @@ -21,63 +21,79 @@ unsafe extern "C" { fn sysconf(name: i32) -> i64; fn madvise(addr: *mut u8, len: usize, advice: i32) -> i32; } +/// True when the soft stack limit is a finite value of at most 8 MiB. +fn check_stack_limit(current: u64) -> bool { + current != 0 && current != u64::MAX && current <= 8 * 1024 * 1024 +} +/// True when the default thread stack size is nonzero and at most 8 MiB. +fn check_stack_size(size: usize) -> bool { + size != 0 && size <= 8 * 1024 * 1024 +} +/// True when `getrlimit(RLIMIT_STACK)` succeeds and the soft limit passes `check_stack_limit`. +#[cfg(target_env = "gnu")] +fn stack_limit_admitted() -> bool { + let mut limit = Limit { current: 0, max: 0 }; + // SAFETY: `limit` is a live, writable local of the exact glibc layout (struct rlimit = 2*u64). + let failed = unsafe { getrlimit(3, &mut limit) } != 0; + !failed && check_stack_limit(limit.current) +} +/// The default thread stack size of the process (glibc default attributes), when readable and admitted. +#[cfg(target_env = "gnu")] +fn default_stack_size() -> Option { + let mut attr = Attr { words: [0; 7] }; + // SAFETY: `attr` is a live, writable local of the exact glibc layout (pthread_attr_t = 56 bytes, align 8). + if unsafe { pthread_getattr_default_np(&mut attr) } != 0 { + return None; + } + let mut size = 0; + // SAFETY: `attr` was filled by the successful getattr above and is destroyed exactly once, here; `size` is a live + // writable word. + let (query, release) = unsafe { (pthread_attr_getstacksize(&attr, &mut size), pthread_attr_destroy(&mut attr)) }; + (query == 0 && release == 0 && check_stack_size(size)).then_some(size) +} pub(super) fn stack_size() -> Result { #[cfg(not(target_env = "gnu"))] { return Err(Error::Unsupported); } - // SAFETY: `limit`/`attr`/`size` are live, writable locals of the exact glibc layouts (struct rlimit = 2*u64, - // pthread_attr_t = 56 bytes, align 8); the attr is destroyed exactly once, only after a successful getattr. #[cfg(target_env = "gnu")] - unsafe { - let mut limit = Limit { current: 0, max: 0 }; - if getrlimit(3, &mut limit) != 0 - || limit.current == 0 - || limit.current == u64::MAX - || limit.current > 8 * 1024 * 1024 - { + { + if !stack_limit_admitted() { return Err(Error::Unsupported); } - let mut attr = Attr { words: [0; 7] }; - if pthread_getattr_default_np(&mut attr) != 0 { - return Err(Error::Unsupported); - } - let mut size = 0; - let query = pthread_attr_getstacksize(&attr, &mut size); - let release = pthread_attr_destroy(&mut attr); - if query != 0 || release != 0 || size == 0 || size > 8 * 1024 * 1024 { - Err(Error::Unsupported) - } else { - Ok(size) - } + default_stack_size().ok_or(Error::Unsupported) } } +/// The leading number of the text of a sysfs file (`topology/core_id`, `cpu_capacity`), -1 when there is none. +pub(super) fn parse_leading_number(text: &str) -> i64 { + text.split_whitespace().next().and_then(|word| word.parse().ok()).unwrap_or(-1) +} fn read_cpu(cpu: i32, key: &str) -> i64 { std::fs::read_to_string(format!("/sys/devices/system/cpu/cpu{cpu}/topology/{key}")) - .ok() - .and_then(|s| s.split_whitespace().next()?.parse().ok()) - .unwrap_or(-1) + .map_or(-1, |text| parse_leading_number(&text)) } -pub(super) fn cores(skip_first: bool) -> Vec { +/// The logical CPUs set in a `cpu_set_t`-sized mask, ascending. +pub(super) fn mask_cpus(set: &[usize; 16]) -> Vec { + (0..1024).filter(|i| set[i / 64] & (1usize << (i % 64)) != 0).map(|i| i as i32).collect() +} +/// The logical CPUs this process may run on: its affinity mask, else every CPU `sysconf` counts. +fn allowed_cpus() -> Vec { let mut set = [0usize; 16]; - let mut allowed = Vec::new(); // SAFETY: initialized Linux cpu_set_t-sized mask, no pointer retention. if unsafe { sched_getaffinity(0, std::mem::size_of_val(&set), set.as_mut_ptr()) } == 0 { - for i in 0..1024 { - if set[i / 64] & (1usize << (i % 64)) != 0 { - allowed.push(i as i32); - } - } - } else { - let n = unsafe { sysconf(84) }; - for i in 0..n.max(0) { - allowed.push(i as i32); - } + return mask_cpus(&set); } + // SAFETY: `sysconf` takes an integer name and touches no memory of this process (84 = _SC_NPROCESSORS_CONF). + let n = unsafe { sysconf(84) }; + (0..n.max(0)).map(|i| i as i32).collect() +} +/// The first logical CPU of every (package, core) pair, in the order of `allowed`; a CPU whose ids are unreadable +/// (negative) counts as a core of its own. `ids_of` gives the (package, core) ids of a CPU. +pub(super) fn first_cpu_of_each_core(allowed: &[i32], ids_of: impl Fn(i32) -> (i64, i64)) -> Vec { let mut seen = Vec::new(); let mut physical = Vec::new(); - for cpu in allowed { - let key = (read_cpu(cpu, "physical_package_id"), read_cpu(cpu, "core_id")); + for &cpu in allowed { + let key = ids_of(cpu); if key.0 >= 0 && key.1 >= 0 { if seen.contains(&key) { continue; @@ -86,6 +102,12 @@ pub(super) fn cores(skip_first: bool) -> Vec { } physical.push(cpu); } + physical +} +pub(super) fn cores(skip_first: bool) -> Vec { + let allowed = allowed_cpus(); + let mut physical = + first_cpu_of_each_core(&allowed, |cpu| (read_cpu(cpu, "physical_package_id"), read_cpu(cpu, "core_id"))); if skip_first && !physical.is_empty() { physical.remove(0); } diff --git a/crates/native-cpu-expert/src/rust_platform_win.rs b/crates/native-cpu-expert/src/rust_platform_win.rs index 200f79f6..de103bd6 100644 --- a/crates/native-cpu-expert/src/rust_platform_win.rs +++ b/crates/native-cpu-expert/src/rust_platform_win.rs @@ -3,8 +3,8 @@ //! `#[cfg_attr(windows, path = "rust_platform_win.rs")]`. //! //! * Affinity is a 64-bit mask of the processor group the process starts in (this port targets machines with at most -//! 64 logical processors; a larger machine simply uses its first group). `current_affinity` returns the mask in word 0 -//! of the same 16-word array the Linux code uses. +//! 64 logical processors; a larger machine simply uses its first group). `current_affinity` returns the mask in +//! word 0 of the same 16-word array the Linux code uses. //! * `will_need` is `PrefetchVirtualMemory`: the memory manager starts reading a file-mapped range in the background. //! Advice only; failure changes nothing. //! * `cores` lists the first logical processor of every physical core (SMT siblings are skipped), like the Linux @@ -30,7 +30,8 @@ fn process_mask() -> Option { .then_some(process) } -/// Pure: the first set bit of every group of sibling bits (`cores` are the per-physical-core masks), restricted to `allowed`. +/// Pure: the first set bit of every group of sibling bits (`cores` are the per-physical-core masks), restricted to +/// `allowed`. pub(super) fn first_of_each_core(core_masks: &[usize], allowed: usize) -> Vec { let mut out: Vec = core_masks .iter() @@ -77,8 +78,8 @@ pub(super) fn cores(skip_first: bool) -> Vec { physical } -/// `PrefetchVirtualMemory` over `[addr, addr+len)` rounded out to pages: advice only, it never reads or writes the range -/// through a Rust reference, so any address is memory-safe (an unmapped range just fails). +/// `PrefetchVirtualMemory` over `[addr, addr+len)` rounded out to pages: advice only, it never reads or writes the +/// range through a Rust reference, so any address is memory-safe (an unmapped range just fails). pub fn advise_will_need(addr: usize, len: usize) { if len == 0 { return; diff --git a/crates/native-cpu-expert/src/rust_topology.rs b/crates/native-cpu-expert/src/rust_topology.rs index cbc5794f..c038a753 100644 --- a/crates/native-cpu-expert/src/rust_topology.rs +++ b/crates/native-cpu-expert/src/rust_topology.rs @@ -25,95 +25,140 @@ unsafe extern "C" { } #[cfg(unix)] fn number(path: String) -> i64 { - std::fs::read_to_string(path).ok().and_then(|s| s.split_whitespace().next()?.parse().ok()).unwrap_or(-1) + std::fs::read_to_string(path).map_or(-1, |text| super::rust_platform::parse_leading_number(&text)) +} +/// What sysfs says about one logical CPU (-1 where a file is missing or has no number). +#[cfg(unix)] +#[derive(Clone, Copy)] +struct CpuInfo { + cpu: i32, + package: i64, + core: i64, + capacity: i64, } #[cfg(unix)] -pub fn detect_cpu_topology(skip_first: bool, affinity: PoolAffinity) -> CpuTopology { - let mut t = CpuTopology { host_core: -1, ..CpuTopology::default() }; +fn read_cpu_info(cpu: i32) -> CpuInfo { + let package = number(format!("/sys/devices/system/cpu/cpu{cpu}/topology/physical_package_id")); + let core = number(format!("/sys/devices/system/cpu/cpu{cpu}/topology/core_id")); + let capacity = number(format!("/sys/devices/system/cpu/cpu{cpu}/cpu_capacity")); + CpuInfo { cpu, package, core, capacity } +} +/// The logical CPUs this process may run on: its affinity mask, else every CPU `available_parallelism` counts. +#[cfg(unix)] +fn allowed_cpus() -> Vec { let mut mask = [0usize; 16]; - let mut allowed = Vec::new(); if /* SAFETY: `mask` is a live, writable 128-byte cpu_set_t-sized buffer; no pointer is retained. */ unsafe { sched_getaffinity(0, std::mem::size_of_val(&mask), mask.as_mut_ptr()) } == 0 { - for i in 0..1024 { - if mask[i / 64] & (1usize << (i % 64)) != 0 { - allowed.push(i as i32); - } - } - } else { - allowed.extend(0..std::thread::available_parallelism().map(|n| n.get()).unwrap_or(0) as i32); + return super::rust_platform::mask_cpus(&mask); } + (0..std::thread::available_parallelism().map(|n| n.get()).unwrap_or(0) as i32).collect() +} +/// The CPUs in the order read, each with its capacity and whether an earlier CPU already has its (package, core) ids +/// (an SMT sibling); the highest and lowest nonzero capacity; the number of distinct cores. +#[cfg(unix)] +struct Scan { + rows: Vec<(i32, i64, bool)>, + cores: usize, + max: i64, + min: i64, +} +/// True when `info` has the (package, core) ids of an earlier CPU; else the pair is recorded in `seen`. +#[cfg(unix)] +fn record_core(seen: &mut Vec<(i64, i64)>, info: &CpuInfo) -> bool { + if info.package < 0 || info.core < 0 { + return false; + } + let key = (info.package, info.core); + if seen.contains(&key) { + return true; + } + seen.push(key); + false +} +#[cfg(unix)] +fn scan_cpus(infos: &[CpuInfo]) -> Scan { let mut seen = Vec::new(); - let mut all = Vec::new(); + let mut rows = Vec::new(); let mut max = 0; let mut min = 1_000_000; - for cpu in allowed { - let package = number(format!("/sys/devices/system/cpu/cpu{cpu}/topology/physical_package_id")); - let core = number(format!("/sys/devices/system/cpu/cpu{cpu}/topology/core_id")); - let cap = number(format!("/sys/devices/system/cpu/cpu{cpu}/cpu_capacity")); - if cap > 0 { - max = max.max(cap); - min = min.min(cap); + for info in infos { + if info.capacity > 0 { + max = max.max(info.capacity); + min = min.min(info.capacity); } - let sibling = if package >= 0 && core >= 0 { - let key = (package, core); - if seen.contains(&key) { - true - } else { - seen.push(key); - false - } - } else { - false - }; - all.push((cpu, cap, sibling)); + let sibling = record_core(&mut seen, info); + rows.push((info.cpu, info.capacity, sibling)); } - t.is_hybrid = max > 0 && max > min; - if t.is_hybrid { - for &(_, cap, sibling) in &all { - if cap == max { - if !sibling { - t.p_cores += 1; - } - t.p_threads += 1; - } else if !sibling { - t.e_cores += 1; + Scan { rows, cores: seen.len(), max, min } +} +/// Performance cores, performance threads and efficiency cores: by capacity on a hybrid CPU, else the plain counts. +#[cfg(unix)] +fn count_cores(scan: &Scan, is_hybrid: bool) -> (usize, usize, usize) { + if !is_hybrid { + return (scan.cores, scan.rows.len(), 0); + } + let (mut p_cores, mut p_threads, mut e_cores) = (0, 0, 0); + for &(_, cap, sibling) in &scan.rows { + if cap == scan.max { + if !sibling { + p_cores += 1; } + p_threads += 1; + } else if !sibling { + e_cores += 1; } - } else { - t.p_cores = seen.len(); - t.p_threads = all.len(); - } - if affinity == PoolAffinity::All || !t.is_hybrid { - t.worker_cores = all.iter().filter_map(|&(cpu, _, sib)| (!sib).then_some(cpu)).collect(); - if skip_first && !t.worker_cores.is_empty() { - t.host_core = t.worker_cores.remove(0); - } - return t; } + (p_cores, p_threads, e_cores) +} +/// The host core (the first worker core when `skip_first`, else -1) and the worker cores: one thread per core. +#[cfg(unix)] +fn plain_cores(scan: &Scan, skip_first: bool) -> (i32, Vec) { + let mut workers: Vec = scan.rows.iter().filter_map(|&(cpu, _, sib)| (!sib).then_some(cpu)).collect(); + let host = if skip_first && !workers.is_empty() { workers.remove(0) } else { -1 }; + (host, workers) +} +/// The host core and the worker cores of a hybrid CPU: the performance cores, then their siblings, then (unless +/// `PCores`) the efficiency cores. +#[cfg(unix)] +fn hybrid_cores(scan: &Scan, skip_first: bool, affinity: PoolAffinity) -> (i32, Vec) { let mut primary = Vec::new(); let mut siblings = Vec::new(); let mut efficient = Vec::new(); - for (cpu, cap, sib) in all { - if cap == max { - if sib { - siblings.push(cpu); - } else { - primary.push(cpu); - } - } else { + for &(cpu, cap, sib) in &scan.rows { + if cap != scan.max { efficient.push(cpu); + } else if sib { + siblings.push(cpu); + } else { + primary.push(cpu); } } - if skip_first && !primary.is_empty() { - t.host_core = primary.remove(0); - } - t.worker_cores = primary; - t.worker_cores.extend(siblings); + let host = if skip_first && !primary.is_empty() { primary.remove(0) } else { -1 }; + let mut workers = primary; + workers.extend(siblings); if affinity != PoolAffinity::PCores { - t.worker_cores.extend(efficient); + workers.extend(efficient); } - t + (host, workers) +} +/// The topology the sysfs descriptions `infos` of the allowed CPUs give. +#[cfg(unix)] +fn topology_from(infos: &[CpuInfo], skip_first: bool, affinity: PoolAffinity) -> CpuTopology { + let scan = scan_cpus(infos); + let is_hybrid = scan.max > 0 && scan.max > scan.min; + let (p_cores, p_threads, e_cores) = count_cores(&scan, is_hybrid); + let (host_core, worker_cores) = if affinity == PoolAffinity::All || !is_hybrid { + plain_cores(&scan, skip_first) + } else { + hybrid_cores(&scan, skip_first, affinity) + }; + CpuTopology { is_hybrid, p_cores, p_threads, e_cores, worker_cores, host_core } +} +#[cfg(unix)] +pub fn detect_cpu_topology(skip_first: bool, affinity: PoolAffinity) -> CpuTopology { + let infos: Vec = allowed_cpus().into_iter().map(read_cpu_info).collect(); + topology_from(&infos, skip_first, affinity) } #[cfg(unix)] pub fn pin_current_thread(core: i32) -> i64 {