use serde::{Deserialize, Serialize};
use crate::error::IronError;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum CacheLevel {
L1,
L2,
L3,
L4,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CacheType {
Data,
Instruction,
Unified,
Unknown,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CpuCacheInfo {
pub level: CacheLevel,
pub cache_type: CacheType,
pub size_kb: u64,
pub line_size: Option<u32>,
pub associativity: Option<u32>,
pub sets: Option<u64>,
pub partitions: Option<u32>,
pub shared_cpu_list: String,
pub index: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CpuCacheTopology {
pub caches: Vec<CpuCacheInfo>,
pub total_l1d_kb: u64,
pub total_l1i_kb: u64,
pub total_l2_kb: u64,
pub total_l3_kb: u64,
}
pub struct CpuCacheMonitor {
topology: CpuCacheTopology,
}
#[cfg(target_os = "windows")]
fn affinity_mask_to_list(mask: usize) -> String {
let cpus: Vec<u32> = (0..usize::BITS)
.filter(|bit| mask & (1usize << bit) != 0)
.collect();
if cpus.is_empty() {
return String::new();
}
let mut parts = Vec::new();
let mut start = cpus[0];
let mut prev = cpus[0];
for &cpu in &cpus[1..] {
if cpu != prev + 1 {
parts.push(if start == prev {
start.to_string()
} else {
format!("{start}-{prev}")
});
start = cpu;
}
prev = cpu;
}
parts.push(if start == prev {
start.to_string()
} else {
format!("{start}-{prev}")
});
parts.join(",")
}
impl CpuCacheMonitor {
pub fn new() -> Result<Self, IronError> {
let mut monitor = Self {
topology: CpuCacheTopology {
caches: Vec::new(),
total_l1d_kb: 0,
total_l1i_kb: 0,
total_l2_kb: 0,
total_l3_kb: 0,
},
};
monitor.refresh()?;
Ok(monitor)
}
pub fn refresh(&mut self) -> Result<(), IronError> {
self.topology.caches.clear();
#[cfg(target_os = "linux")]
self.refresh_linux()?;
#[cfg(target_os = "windows")]
self.refresh_windows()?;
#[cfg(target_os = "macos")]
self.refresh_macos()?;
self.compute_totals();
Ok(())
}
pub fn caches(&self) -> &[CpuCacheInfo] {
&self.topology.caches
}
pub fn topology(&self) -> &CpuCacheTopology {
&self.topology
}
pub fn total_l1d_kb(&self) -> u64 {
self.topology.total_l1d_kb
}
pub fn total_l2_kb(&self) -> u64 {
self.topology.total_l2_kb
}
pub fn total_l3_kb(&self) -> u64 {
self.topology.total_l3_kb
}
pub fn caches_at_level(&self, level: CacheLevel) -> Vec<&CpuCacheInfo> {
self.topology
.caches
.iter()
.filter(|c| c.level == level)
.collect()
}
fn compute_totals(&mut self) {
let mut seen_l3: std::collections::HashSet<String> = std::collections::HashSet::new();
self.topology.total_l1d_kb = 0;
self.topology.total_l1i_kb = 0;
self.topology.total_l2_kb = 0;
self.topology.total_l3_kb = 0;
for cache in &self.topology.caches {
match (cache.level, cache.cache_type) {
(CacheLevel::L1, CacheType::Data) => {
self.topology.total_l1d_kb += cache.size_kb;
}
(CacheLevel::L1, CacheType::Instruction) => {
self.topology.total_l1i_kb += cache.size_kb;
}
(CacheLevel::L2, _) => {
self.topology.total_l2_kb += cache.size_kb;
}
(CacheLevel::L3, _) if seen_l3.insert(cache.shared_cpu_list.clone()) => {
self.topology.total_l3_kb += cache.size_kb;
}
_ => {}
}
}
}
#[cfg(target_os = "linux")]
fn refresh_linux(&mut self) -> Result<(), IronError> {
let cpu_base = std::path::Path::new("/sys/devices/system/cpu/cpu0/cache");
if !cpu_base.exists() {
return Ok(());
}
{
let entries = std::fs::read_dir(cpu_base)
.map_err(|e| IronError::System(format!("cannot read {cpu_base:?}: {e}")))?;
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
if !name.starts_with("index") {
continue;
}
let idx: u32 = name
.strip_prefix("index")
.and_then(|s| s.parse().ok())
.unwrap_or(0);
let base = entry.path();
let level_str = Self::read_trimmed(&base.join("level"));
let level = match level_str.as_str() {
"1" => CacheLevel::L1,
"2" => CacheLevel::L2,
"3" => CacheLevel::L3,
"4" => CacheLevel::L4,
_ => continue,
};
let type_str = Self::read_trimmed(&base.join("type"));
let cache_type = match type_str.to_lowercase().as_str() {
"data" => CacheType::Data,
"instruction" => CacheType::Instruction,
"unified" => CacheType::Unified,
_ => CacheType::Unknown,
};
let size_str = Self::read_trimmed(&base.join("size"));
let size_kb = Self::parse_size_kb(&size_str);
let line_size: Option<u32> = Self::read_trimmed(&base.join("coherency_line_size"))
.parse()
.ok();
let associativity: Option<u32> =
Self::read_trimmed(&base.join("ways_of_associativity"))
.parse()
.ok();
let sets: Option<u64> = Self::read_trimmed(&base.join("number_of_sets"))
.parse()
.ok();
let partitions: Option<u32> =
Self::read_trimmed(&base.join("physical_line_partition"))
.parse()
.ok();
let shared_cpu_list = Self::read_trimmed(&base.join("shared_cpu_list"));
self.topology.caches.push(CpuCacheInfo {
level,
cache_type,
size_kb,
line_size,
associativity,
sets,
partitions,
shared_cpu_list,
index: idx,
});
}
}
self.topology.caches.sort_by_key(|c| (c.level, c.index));
Ok(())
}
#[cfg(target_os = "linux")]
fn read_trimmed(path: &std::path::Path) -> String {
std::fs::read_to_string(path)
.unwrap_or_default()
.trim()
.to_string()
}
#[cfg(target_os = "linux")]
fn parse_size_kb(s: &str) -> u64 {
let s = s.trim();
if let Some(kb) = s.strip_suffix('K') {
kb.parse().unwrap_or(0)
} else if let Some(mb) = s.strip_suffix('M') {
mb.parse::<u64>().unwrap_or(0) * 1024
} else {
s.parse().unwrap_or(0)
}
}
#[cfg(target_os = "windows")]
fn refresh_windows_logical_processor_info(&mut self) -> Result<bool, IronError> {
use windows::Win32::System::SystemInformation::{
CacheData, CacheInstruction, GetLogicalProcessorInformationEx, RelationCache,
LOGICAL_PROCESSOR_RELATIONSHIP, SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX,
};
let mut needed = 0u32;
let _ = unsafe { GetLogicalProcessorInformationEx(RelationCache, None, &mut needed) };
if needed == 0 {
return Ok(false);
}
let mut buf = vec![0u8; needed as usize];
if unsafe {
GetLogicalProcessorInformationEx(
RelationCache,
Some(buf.as_mut_ptr() as *mut SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX),
&mut needed,
)
}
.is_err()
{
return Ok(false);
}
const HEADER_BYTES: usize =
std::mem::size_of::<LOGICAL_PROCESSOR_RELATIONSHIP>() + std::mem::size_of::<u32>();
let mut offset = 0usize;
let mut index = 0u32;
while offset + HEADER_BYTES <= buf.len() {
let record = unsafe {
&*(buf.as_ptr().add(offset) as *const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX)
};
let size = record.Size as usize;
if size == 0 || offset + size > buf.len() {
break;
}
if record.Relationship == RelationCache {
let cache = unsafe { &record.Anonymous.Cache };
let level = match cache.Level {
1 => CacheLevel::L1,
2 => CacheLevel::L2,
3 => CacheLevel::L3,
4 => CacheLevel::L4,
_ => {
offset += size;
continue;
}
};
let cache_type = match cache.Type {
t if t == CacheData => CacheType::Data,
t if t == CacheInstruction => CacheType::Instruction,
_ => CacheType::Unified,
};
let associativity = (cache.Associativity != 0xFF && cache.Associativity != 0)
.then_some(cache.Associativity as u32);
let mask = unsafe { cache.Anonymous.GroupMask };
let shared = affinity_mask_to_list(mask.Mask);
self.topology.caches.push(CpuCacheInfo {
level,
cache_type,
size_kb: (cache.CacheSize as u64) / 1024,
line_size: (cache.LineSize > 0).then_some(cache.LineSize as u32),
associativity,
sets: None,
partitions: None,
shared_cpu_list: shared,
index,
});
index += 1;
}
offset += size;
}
Ok(index > 0)
}
#[cfg(target_os = "windows")]
fn refresh_windows(&mut self) -> Result<(), IronError> {
if self.refresh_windows_logical_processor_info()? {
return Ok(());
}
const QUERY: &str = concat!(
"Get-CimInstance Win32_CacheMemory | Select-Object Purpose, ",
"InstalledSize, CacheSpeed, Level, Associativity, LineSize, ",
"NumberOfBlocks, Status | ConvertTo-Json -Compress"
);
let Some(val) =
crate::core::command::capture_json("powershell", &["-NoProfile", "-Command", QUERY])?
else {
return Ok(());
};
for (i, item) in crate::core::command::json_items(&val).iter().enumerate() {
let purpose = item["Purpose"].as_str().unwrap_or("");
let wmi_level = item["Level"].as_u64().unwrap_or(0);
let level = match wmi_level {
3 => CacheLevel::L1,
4 => CacheLevel::L2,
5 => CacheLevel::L3,
_ => {
let p = purpose.to_lowercase();
if p.contains("l1") {
CacheLevel::L1
} else if p.contains("l2") {
CacheLevel::L2
} else if p.contains("l3") {
CacheLevel::L3
} else {
CacheLevel::L2
}
}
};
let cache_type = {
let p = purpose.to_lowercase();
if p.contains("data") {
CacheType::Data
} else if p.contains("instruction") || p.contains("code") {
CacheType::Instruction
} else {
CacheType::Unified
}
};
let size_kb = item["InstalledSize"].as_u64().unwrap_or(0);
let line_size = item["LineSize"].as_u64().map(|v| v as u32);
let assoc = item["Associativity"].as_u64().map(|v| v as u32);
self.topology.caches.push(CpuCacheInfo {
level,
cache_type,
size_kb,
line_size,
associativity: assoc,
sets: None,
partitions: None,
shared_cpu_list: String::new(),
index: i as u32,
});
}
Ok(())
}
#[cfg(target_os = "macos")]
fn refresh_macos(&mut self) -> Result<(), IronError> {
let read_sysctl = |name: &str| -> Option<u64> {
crate::core::command::capture("sysctl", &["-n", name])
.ok()
.and_then(|s| s.trim().parse().ok())
};
let line_size = read_sysctl("hw.cachelinesize").map(|v| v as u32);
if let Some(l1d) = read_sysctl("hw.l1dcachesize").filter(|v| *v > 0) {
self.topology.caches.push(CpuCacheInfo {
level: CacheLevel::L1,
cache_type: CacheType::Data,
size_kb: l1d / 1024,
line_size,
associativity: None,
sets: None,
partitions: None,
shared_cpu_list: String::new(),
index: 0,
});
}
if let Some(l1i) = read_sysctl("hw.l1icachesize").filter(|v| *v > 0) {
self.topology.caches.push(CpuCacheInfo {
level: CacheLevel::L1,
cache_type: CacheType::Instruction,
size_kb: l1i / 1024,
line_size,
associativity: None,
sets: None,
partitions: None,
shared_cpu_list: String::new(),
index: 1,
});
}
if let Some(l2) = read_sysctl("hw.l2cachesize").filter(|v| *v > 0) {
self.topology.caches.push(CpuCacheInfo {
level: CacheLevel::L2,
cache_type: CacheType::Unified,
size_kb: l2 / 1024,
line_size,
associativity: None,
sets: None,
partitions: None,
shared_cpu_list: String::new(),
index: 2,
});
}
if let Some(l3) = read_sysctl("hw.l3cachesize").filter(|v| *v > 0) {
self.topology.caches.push(CpuCacheInfo {
level: CacheLevel::L3,
cache_type: CacheType::Unified,
size_kb: l3 / 1024,
line_size,
associativity: None,
sets: None,
partitions: None,
shared_cpu_list: String::new(),
index: 3,
});
}
Ok(())
}
}
impl Default for CpuCacheMonitor {
fn default() -> Self {
Self::new().unwrap_or(Self {
topology: CpuCacheTopology {
caches: Vec::new(),
total_l1d_kb: 0,
total_l1i_kb: 0,
total_l2_kb: 0,
total_l3_kb: 0,
},
})
}
}
impl std::fmt::Display for CacheLevel {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::L1 => write!(f, "L1"),
Self::L2 => write!(f, "L2"),
Self::L3 => write!(f, "L3"),
Self::L4 => write!(f, "L4"),
}
}
}
impl std::fmt::Display for CacheType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Data => write!(f, "Data"),
Self::Instruction => write!(f, "Instruction"),
Self::Unified => write!(f, "Unified"),
Self::Unknown => write!(f, "Unknown"),
}
}
}
#[cfg(all(test, target_os = "windows"))]
mod affinity_tests {
use super::affinity_mask_to_list;
#[test]
fn a_mask_renders_as_a_linux_style_cpu_list() {
assert_eq!(affinity_mask_to_list(0b11), "0-1");
assert_eq!(affinity_mask_to_list(0b1100), "2-3");
assert_eq!(affinity_mask_to_list(0b1), "0");
assert_eq!(affinity_mask_to_list(0b1_0000_0011), "0-1,8");
assert_eq!(affinity_mask_to_list(0b1010), "1,3");
assert_eq!(affinity_mask_to_list(0), "");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_cache_monitor_creation() {
match CpuCacheMonitor::new() {
Ok(_monitor) => {}
Err(e) => {
let why = e.to_string();
assert!(
why.len() > 10,
"enumeration failed without saying why: {why:?}"
);
}
}
}
#[test]
fn test_cache_monitor_default() {
let monitor = CpuCacheMonitor::default();
let _ = monitor.caches();
let _ = monitor.topology();
}
#[test]
fn test_cache_level_display() {
assert_eq!(CacheLevel::L1.to_string(), "L1");
assert_eq!(CacheLevel::L3.to_string(), "L3");
}
#[test]
fn test_cache_serialization() {
let cache = CpuCacheInfo {
level: CacheLevel::L2,
cache_type: CacheType::Unified,
size_kb: 256,
line_size: Some(64),
associativity: Some(8),
sets: Some(512),
partitions: Some(1),
shared_cpu_list: "0-1".into(),
index: 0,
};
let json = serde_json::to_string(&cache).unwrap();
assert!(json.contains("256"));
let _: CpuCacheInfo = serde_json::from_str(&json).unwrap();
}
#[test]
fn test_topology_serialization() {
let topo = CpuCacheTopology {
caches: Vec::new(),
total_l1d_kb: 128,
total_l1i_kb: 128,
total_l2_kb: 1024,
total_l3_kb: 8192,
};
let json = serde_json::to_string(&topo).unwrap();
assert!(json.contains("8192"));
}
#[test]
fn cache_geometry_is_absent_rather_than_assumed() {
let unread = CpuCacheInfo {
level: CacheLevel::L1,
cache_type: CacheType::Data,
size_kb: 64,
line_size: None,
associativity: None,
sets: None,
partitions: None,
shared_cpu_list: String::new(),
index: 0,
};
assert!(unread.line_size.is_none());
let fully = CpuCacheInfo {
associativity: Some(0),
..unread.clone()
};
assert_ne!(fully.associativity, unread.associativity);
}
}