Skip to main content

sys_lib/cpu/
topology.rs

1//! Topology, caches, and NUMA nodes: static facts, read on first use. The first
2//! call reads up to a few hundred small files on a large Linux host, which is
3//! why these are apart from `cpu::name()`. CPU hot-plug after the first call is
4//! not reflected; `cpu::online()` is the live count.
5
6use std::sync::OnceLock;
7
8use crate::{Bytes, sys::TopologyFacts};
9
10/// Packages (sockets) and cores, sorted by id.
11///
12/// ```
13/// use sys_lib as sys;
14///
15/// let t = sys::cpu::topology();
16/// let fast = t.cores.iter().filter(|c| c.kind == sys::cpu::CoreKind::Performance).count();
17/// println!("{} cores, {fast} performance cores, hybrid: {}", t.cores.len(), sys::cpu::is_hybrid());
18/// ```
19#[derive(Clone, Debug, Default, PartialEq, Eq)]
20#[non_exhaustive]
21pub struct Topology {
22    /// The packages.
23    pub packages: Vec<Package>,
24    /// The cores.
25    pub cores: Vec<Core>,
26}
27
28/// A processor package (socket).
29#[derive(Clone, Debug, PartialEq, Eq)]
30#[non_exhaustive]
31pub struct Package {
32    /// Its id.
33    pub id: u32,
34    /// The ids of its cores.
35    pub cores: Vec<u32>,
36}
37
38/// A physical core.
39#[derive(Clone, Debug, PartialEq, Eq)]
40#[non_exhaustive]
41pub struct Core {
42    /// Its id, unique across packages.
43    pub id: u32,
44    /// The package it is in.
45    pub package: u32,
46    /// Its logical CPU indexes.
47    pub logical: Vec<u32>,
48    /// Its kind.
49    pub kind: CoreKind,
50    /// Linux `cpu_capacity`, 0 to 1024.
51    pub capacity: Option<u16>,
52    /// The NUMA node it is in.
53    pub numa_node: Option<u32>,
54}
55
56/// What kind of core this is.
57#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
58#[non_exhaustive]
59pub enum CoreKind {
60    /// A big core on a hybrid processor.
61    Performance,
62    /// A little core on a hybrid processor.
63    Efficiency,
64    /// Every core on this processor is alike.
65    Uniform,
66    /// The OS does not say.
67    Unknown,
68}
69
70/// A CPU cache.
71#[derive(Clone, Debug, PartialEq, Eq)]
72#[non_exhaustive]
73pub struct Cache {
74    /// 1 for L1, and so on.
75    pub level: u8,
76    /// What it holds.
77    pub kind: CacheKind,
78    /// Its size.
79    pub size: Bytes,
80    /// Its line size in bytes.
81    pub line: u32,
82    /// The logical CPUs sharing this cache instance.
83    pub shared_by: Vec<u32>,
84}
85
86/// What a cache holds.
87#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
88#[non_exhaustive]
89pub enum CacheKind {
90    /// Data.
91    Data,
92    /// Instructions.
93    Instruction,
94    /// Both.
95    Unified,
96}
97
98/// A NUMA node.
99#[derive(Clone, Debug, PartialEq, Eq)]
100#[non_exhaustive]
101pub struct NumaNode {
102    /// Its id.
103    pub id: u32,
104    /// The logical CPUs in it.
105    pub cpus: Vec<u32>,
106    /// The memory attached to it.
107    pub memory: Option<Bytes>,
108}
109
110fn facts() -> &'static TopologyFacts {
111    static FACTS: OnceLock<TopologyFacts> = OnceLock::new();
112    FACTS.get_or_init(|| {
113        let mut f = crate::sys::cpu_topology();
114        f.topology.packages.sort_by_key(|p| p.id);
115        f.topology.cores.sort_by_key(|c| (c.package, c.id));
116        f.caches
117            .sort_by_key(|c| (c.level, c.shared_by.first().copied()));
118        f.numa.sort_by_key(|n| n.id);
119        f
120    })
121}
122
123/// Packages and cores. Empty where the OS hides them.
124#[must_use]
125pub fn topology() -> &'static Topology {
126    &facts().topology
127}
128
129/// The caches, one entry per instance, sorted by level.
130#[must_use]
131pub fn caches() -> &'static [Cache] {
132    &facts().caches
133}
134
135/// The cache line size in bytes, from the first level 1 data cache; 64 when
136/// unknown, 128 on Apple silicon.
137///
138/// ```
139/// assert!(sys_lib::cpu::cache_line().is_power_of_two());
140/// ```
141#[must_use]
142pub fn cache_line() -> usize {
143    let line = caches()
144        .iter()
145        .find(|c| c.level == 1 && c.kind != CacheKind::Instruction)
146        .map(|c| c.line as usize)
147        .filter(|l| l.is_power_of_two() && (16..=1024).contains(l));
148    line.unwrap_or(
149        if cfg!(all(target_vendor = "apple", target_arch = "aarch64")) {
150            128
151        } else {
152            64
153        },
154    )
155}
156
157/// The NUMA nodes, sorted by id. macOS reports one node with every CPU.
158#[must_use]
159pub fn numa_nodes() -> &'static [NumaNode] {
160    &facts().numa
161}
162
163/// Whether the processor has more than one kind of core.
164#[must_use]
165pub fn is_hybrid() -> bool {
166    let cores = &topology().cores;
167    cores.iter().any(|c| c.kind == CoreKind::Performance)
168        && cores.iter().any(|c| c.kind == CoreKind::Efficiency)
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174
175    #[test]
176    fn test_cpu_topology_live_is_consistent() {
177        assert!(cache_line().is_power_of_two());
178        let t = topology();
179        assert!(std::ptr::eq(t, topology()));
180        for c in &t.cores {
181            assert!(!c.logical.is_empty());
182            assert!(t.packages.iter().any(|p| p.id == c.package));
183        }
184        for pair in t.packages.windows(2) {
185            assert!(pair[0].id < pair[1].id);
186        }
187        for pair in numa_nodes().windows(2) {
188            assert!(pair[0].id < pair[1].id);
189        }
190    }
191}