use super::*;
use crate::error::{Error, Result};
use std::collections::HashMap;
use std::process::Command;
pub struct AppleSiliconMonitor {
soc_info: SocInfo,
}
#[derive(Debug, Clone)]
#[allow(dead_code)]
struct SocInfo {
name: String,
e_core_count: Option<u32>,
p_core_count: Option<u32>,
}
#[derive(Debug, Default)]
pub struct PowermetricsData {
pub e_cluster_freq_mhz: u32,
pub e_cluster_active: u8,
pub p_cluster_freq_mhz: u32,
pub p_cluster_active: u8,
pub e_cores: HashMap<u32, (u32, u8)>, pub p_cores: HashMap<u32, (u32, u8)>,
pub gpu_freq_mhz: u32,
pub gpu_active: u8,
pub cpu_power_mw: u32,
pub gpu_power_mw: u32,
pub ane_power_mw: u32,
pub package_power_mw: u32,
pub thermal_pressure: String,
}
impl AppleSiliconMonitor {
pub fn new() -> Result<Self> {
let soc_info = Self::detect_soc_info()?;
Ok(Self { soc_info })
}
fn detect_soc_info() -> Result<SocInfo> {
let output = Command::new("sysctl")
.args(["-n", "machdep.cpu.brand_string"])
.output()
.map_err(|e| Error::CommandExecutionFailed(format!("sysctl: {}", e)))?;
let name = String::from_utf8_lossy(&output.stdout).trim().to_string();
let e_cores = Self::get_sysctl_value("hw.perflevel1.logicalcpu");
let p_cores = Self::get_sysctl_value("hw.perflevel0.logicalcpu");
Ok(SocInfo {
name,
e_core_count: e_cores,
p_core_count: p_cores,
})
}
fn get_sysctl_value(key: &str) -> Option<u32> {
let output = Command::new("sysctl").args(["-n", key]).output().ok()?;
String::from_utf8_lossy(&output.stdout).trim().parse().ok()
}
pub fn parse_powermetrics(&self) -> Result<PowermetricsData> {
Err(crate::error::IronError::PermissionDenied(
"live Apple Silicon CPU, GPU and ANE figures come from powermetrics, \
which requires root; IronMonitor does not elevate itself"
.into(),
))
}
}
impl SiliconMonitor for AppleSiliconMonitor {
fn cpu_info(&self) -> Result<(Vec<CpuCore>, Vec<CpuCluster>)> {
let data = self.parse_powermetrics()?;
let mut cores = Vec::new();
let mut clusters = Vec::new();
for (id, (freq, util)) in &data.e_cores {
cores.push(CpuCore {
id: *id,
cluster: CpuClusterType::Efficiency,
frequency_mhz: Some(*freq),
utilization: Some(*util),
temperature: None,
});
}
for (id, (freq, util)) in &data.p_cores {
cores.push(CpuCore {
id: *id,
cluster: CpuClusterType::Performance,
frequency_mhz: Some(*freq),
utilization: Some(*util),
temperature: None,
});
}
clusters.push(CpuCluster {
cluster_type: CpuClusterType::Efficiency,
core_ids: self.soc_info.e_core_count.map(|n| (0..n).collect()),
frequency_mhz: Some(data.e_cluster_freq_mhz),
utilization: Some(data.e_cluster_active),
power_watts: None,
});
clusters.push(CpuCluster {
cluster_type: CpuClusterType::Performance,
core_ids: self.soc_info.p_core_count.map(|n| (0..n).collect()),
frequency_mhz: Some(data.p_cluster_freq_mhz),
utilization: Some(data.p_cluster_active),
power_watts: None,
});
Ok((cores, clusters))
}
fn npu_info(&self) -> Result<Vec<NpuInfo>> {
let count = read_neural_engines().map_err(crate::error::IronError::DeviceNotFound)?;
let power_watts = (count == 1)
.then(|| self.parse_powermetrics().ok())
.flatten()
.map(|data| data.ane_power_mw as f32 / 1000.0);
Ok((0..count)
.map(|_| NpuInfo {
name: "Apple Neural Engine".to_string(),
vendor: Some("Apple".to_string()),
cores: None,
utilization: None,
power_watts,
frequency_mhz: None,
})
.collect())
}
fn io_info(&self) -> Result<Vec<IoController>> {
let mut controllers = Vec::new();
if let Ok(output) = Command::new("iostat").args(["-d", "-c", "1"]).output() {
let text = String::from_utf8_lossy(&output.stdout);
for line in text.lines().skip(2) {
if let Some((name, mbps)) = parse_iostat_row(line) {
controllers.push(IoController {
controller_type: if name.starts_with("disk") {
"NVMe".to_string()
} else {
"Storage".to_string()
},
name,
bandwidth_mbps: mbps,
max_bandwidth_mbps: None,
power_watts: None,
});
}
}
}
if let Ok(output) = Command::new("system_profiler")
.args(["-detailLevel", "mini", "SPThunderboltDataType"])
.output()
{
let text = String::from_utf8_lossy(&output.stdout);
let mut tb_count = 0u32;
for line in text.lines() {
if (line.trim().starts_with("Speed:") || line.trim().contains("Thunderbolt"))
&& line.contains("Up to")
{
tb_count += 1;
controllers.push(IoController {
controller_type: "Thunderbolt".to_string(),
name: format!("Thunderbolt Port {}", tb_count),
bandwidth_mbps: None,
max_bandwidth_mbps: None,
power_watts: None,
});
}
}
}
Ok(controllers)
}
fn network_info(&self) -> Result<Vec<NetworkSilicon>> {
let mut networks = Vec::new();
if let Ok(output) = Command::new("ifconfig").output() {
let text = String::from_utf8_lossy(&output.stdout);
let mut current_iface = String::new();
let mut is_up = false;
for line in text.lines() {
if !line.starts_with('\t') && !line.starts_with(' ') && line.contains(':') {
let iface = line.split(':').next().unwrap_or("").to_string();
if !current_iface.is_empty() && is_up && !current_iface.starts_with("lo") {
networks.push(NetworkSilicon {
interface: current_iface.clone(),
link_speed_mbps: None,
rx_bandwidth_mbps: None,
tx_bandwidth_mbps: None,
packet_rate: None,
power_state: Some("active".to_string()),
});
}
current_iface = iface;
is_up = line.contains("UP");
}
}
if !current_iface.is_empty() && is_up && !current_iface.starts_with("lo") {
networks.push(NetworkSilicon {
interface: current_iface.clone(),
link_speed_mbps: None,
rx_bandwidth_mbps: None,
tx_bandwidth_mbps: None,
packet_rate: None,
power_state: Some("active".to_string()),
});
}
}
Ok(networks)
}
}
fn parse_iostat_row(line: &str) -> Option<(String, Option<f64>)> {
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() < 4 {
return None;
}
Some((parts[0].to_string(), parts[3].parse::<f64>().ok()))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PerfLevel {
pub index: u32,
pub name: Option<String>,
pub physical_cores: Option<u32>,
pub logical_cores: Option<u32>,
pub l2_cache_bytes: Option<u64>,
pub cores_per_l2: Option<u32>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AppleGpuCounters {
pub model: Option<String>,
pub core_count: Option<u32>,
pub device_utilization: Option<u8>,
pub renderer_utilization: Option<u8>,
pub tiler_utilization: Option<u8>,
pub in_use_system_memory: Option<u64>,
pub allocated_system_memory: Option<u64>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct UnifiedMemory {
pub total_bytes: Option<u64>,
pub memory_type: Option<String>,
pub manufacturer: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AppleSocInventory {
pub chip: Option<String>,
pub perf_levels: std::result::Result<Vec<PerfLevel>, String>,
pub gpus: std::result::Result<Vec<AppleGpuCounters>, String>,
pub neural_engines: std::result::Result<u32, String>,
pub unified_memory: UnifiedMemory,
}
const ANE_IOKIT_CLASS: &str = "H11ANEIn";
fn command_text(program: &str, args: &[&str]) -> std::result::Result<String, String> {
let output = Command::new(program)
.args(args)
.env("LC_ALL", "C")
.output()
.map_err(|e| format!("{program} could not be run: {e}"))?;
if !output.status.success() {
return Err(format!(
"{program} exited with {}: {}",
output.status,
String::from_utf8_lossy(&output.stderr).trim()
));
}
Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}
fn ioreg_value<'a>(line: &'a str, key: &str) -> Option<&'a str> {
let rest = line.trim().strip_prefix('"')?.strip_prefix(key)?;
let value = rest
.strip_prefix('"')?
.trim_start()
.strip_prefix('=')?
.trim();
let value = value.trim_start_matches('<').trim_end_matches('>');
Some(value.trim_matches('"'))
}
fn ioreg_int_dict(dict: &str) -> HashMap<String, u64> {
let mut entries = HashMap::new();
let inner = dict.trim().trim_start_matches('{').trim_end_matches('}');
let mut rest = inner;
while let Some(start) = rest.find('"') {
let after = &rest[start + 1..];
let Some(end) = after.find('"') else { break };
let key = &after[..end];
let tail = &after[end + 1..];
let Some(tail) = tail.trim_start().strip_prefix('=') else {
rest = tail;
continue;
};
let stop = tail.find([',', '}']).unwrap_or(tail.len());
if let Ok(value) = tail[..stop].trim().parse::<u64>() {
entries.insert(key.to_string(), value);
}
rest = &tail[stop..];
}
entries
}
fn percent(stats: &HashMap<String, u64>, key: &str) -> Option<u8> {
stats
.get(key)
.copied()
.filter(|v| *v <= 100)
.map(|v| v as u8)
}
pub fn parse_ioreg_accelerators(text: &str) -> Vec<AppleGpuCounters> {
let mut gpus: Vec<AppleGpuCounters> = Vec::new();
for line in text.lines() {
if line.trim_start().starts_with("+-o ") {
gpus.push(AppleGpuCounters::default());
continue;
}
let Some(gpu) = gpus.last_mut() else {
continue;
};
if let Some(model) = ioreg_value(line, "model") {
gpu.model = Some(model.to_string()).filter(|m| !m.is_empty());
} else if let Some(count) = ioreg_value(line, "gpu-core-count") {
gpu.core_count = count.parse().ok().filter(|n| *n > 0);
} else if let Some(dict) = ioreg_value(line, "PerformanceStatistics") {
let stats = ioreg_int_dict(dict);
gpu.device_utilization = percent(&stats, "Device Utilization %");
gpu.renderer_utilization = percent(&stats, "Renderer Utilization %");
gpu.tiler_utilization = percent(&stats, "Tiler Utilization %");
gpu.in_use_system_memory = stats.get("In use system memory").copied();
gpu.allocated_system_memory = stats.get("Alloc system memory").copied();
}
}
gpus
}
pub fn count_ioreg_objects(text: &str) -> u32 {
text.lines()
.filter(|line| line.trim_start().starts_with("+-o "))
.count() as u32
}
pub fn read_gpu_counters() -> std::result::Result<Vec<AppleGpuCounters>, String> {
command_text(
"ioreg",
&["-r", "-d", "1", "-w", "0", "-c", "IOAccelerator"],
)
.map(|text| parse_ioreg_accelerators(&text))
}
pub fn read_neural_engines() -> std::result::Result<u32, String> {
let text = command_text(
"ioreg",
&["-r", "-d", "1", "-w", "0", "-c", ANE_IOKIT_CLASS],
)?;
match count_ioreg_objects(&text) {
0 => Err(format!(
"IOKit lists no {ANE_IOKIT_CLASS} object, the Neural Engine driver's class"
)),
n => Ok(n),
}
}
pub fn read_perf_levels() -> std::result::Result<Vec<PerfLevel>, String> {
use crate::platform::macos::{sysctl_string, sysctl_u64};
let count = sysctl_u64("hw.nperflevels")
.ok_or_else(|| "sysctl hw.nperflevels could not be read".to_string())?;
Ok((0..count as u32)
.map(|index| {
let key = |field: &str| format!("hw.perflevel{index}.{field}");
let small = |field: &str| sysctl_u64(&key(field)).and_then(|v| u32::try_from(v).ok());
PerfLevel {
index,
name: sysctl_string(&key("name")).filter(|n| !n.is_empty()),
physical_cores: small("physicalcpu"),
logical_cores: small("logicalcpu"),
l2_cache_bytes: sysctl_u64(&key("l2cachesize")),
cores_per_l2: small("cpusperl2"),
}
})
.collect())
}
pub fn read_unified_memory() -> UnifiedMemory {
use crate::memory_topology::{FormFactor, MemoryTopologyMonitor, MemoryType};
let package = MemoryTopologyMonitor::new().ok().and_then(|monitor| {
monitor
.topology()
.dimms
.iter()
.find(|d| d.form_factor == FormFactor::OnPackage)
.cloned()
});
UnifiedMemory {
total_bytes: crate::platform::macos::sysctl_u64("hw.memsize").filter(|b| *b > 0),
memory_type: package
.as_ref()
.filter(|d| d.memory_type != MemoryType::Unknown)
.map(|d| d.memory_type.to_string()),
manufacturer: package.map(|d| d.manufacturer).filter(|m| !m.is_empty()),
}
}
pub fn read_soc_inventory() -> AppleSocInventory {
AppleSocInventory {
chip: crate::platform::macos::sysctl_string("machdep.cpu.brand_string")
.filter(|c| !c.is_empty()),
perf_levels: read_perf_levels(),
gpus: read_gpu_counters(),
neural_engines: read_neural_engines(),
unified_memory: read_unified_memory(),
}
}
#[cfg(test)]
mod tests {
#[allow(unused_imports)]
use super::*;
#[test]
fn live_figures_are_refused_with_the_reason_not_zeroed() {
let monitor = AppleSiliconMonitor {
soc_info: SocInfo {
name: "Apple M2".into(),
e_core_count: Some(4),
p_core_count: Some(4),
},
};
let err = monitor.parse_powermetrics().expect_err("no sample exists");
assert!(
matches!(err, crate::error::IronError::PermissionDenied(ref why) if why.contains("root")),
"{err:?}"
);
assert!(monitor.cpu_info().is_err());
if let Ok(npus) = monitor.npu_info() {
assert!(npus.iter().all(|npu| npu.power_watts.is_none()), "{npus:?}");
}
}
const IOREG_AGX: &str = r#"+-o AGXAcceleratorG13G <class AGXAcceleratorG13G, id 0x1000004b8, registered, matched, active, busy 0 (0 ms), retain 49>
{
"IOClass" = "AGXAcceleratorG13G"
"gpu-core-count" = 8
"model" = "Apple M1"
"PerformanceStatistics" = {"In use system memory (driver)"=0,"Alloc system memory"=1012334592,"Tiler Utilization %"=7,"recoveryCount"=0,"lastRecoveryTime"=0,"Renderer Utilization %"=11,"TiledSceneBytes"=1638400,"Device Utilization %"=12,"SplitSceneCount"=0,"Allocated PB Size"=168820736,"In use system memory"=423624704}
"IOMatchedAtBoot" = Yes
}
"#;
#[test]
fn ioreg_accelerator_counters_are_read_by_name() {
let gpus = parse_ioreg_accelerators(IOREG_AGX);
assert_eq!(gpus.len(), 1);
let gpu = &gpus[0];
assert_eq!(gpu.model.as_deref(), Some("Apple M1"));
assert_eq!(gpu.core_count, Some(8));
assert_eq!(gpu.device_utilization, Some(12));
assert_eq!(gpu.renderer_utilization, Some(11));
assert_eq!(gpu.tiler_utilization, Some(7));
assert_eq!(gpu.in_use_system_memory, Some(423_624_704));
assert_eq!(gpu.allocated_system_memory, Some(1_012_334_592));
}
#[test]
fn missing_or_impossible_gpu_counters_are_unread() {
let gpus = parse_ioreg_accelerators(concat!(
"+-o AGXAcceleratorG14X <class AGXAcceleratorG14X>\n",
" \"PerformanceStatistics\" = {\"Device Utilization %\"=140,",
"\"Renderer Utilization %\"=bad}\n",
"+-o AppleParavirtGPU <class AppleParavirtGPU>\n",
));
assert_eq!(gpus.len(), 2);
assert_eq!(gpus[0].device_utilization, None);
assert_eq!(gpus[0].renderer_utilization, None);
assert_eq!(gpus[0].core_count, None);
assert_eq!(gpus[1], AppleGpuCounters::default());
assert!(parse_ioreg_accelerators("").is_empty());
}
#[test]
fn ioreg_objects_are_counted_by_their_tree_lines() {
let ane = concat!(
"+-o H11ANEIn <class H11ANEIn, id 0x100000254, registered>\n",
" {\n",
" \"IOClass\" = \"H11ANEIn\"\n",
" }\n",
);
assert_eq!(count_ioreg_objects(ane), 1);
assert_eq!(count_ioreg_objects(""), 0);
}
#[test]
fn iostat_rows_keep_an_unparsed_rate_as_none() {
assert_eq!(
parse_iostat_row("disk0 26.04 1342 34.07"),
Some(("disk0".to_string(), Some(34.07)))
);
assert_eq!(
parse_iostat_row("disk0 26.04 1342 -"),
Some(("disk0".to_string(), None))
);
assert_eq!(parse_iostat_row("KB/t tps"), None);
}
#[test]
#[cfg(target_os = "macos")]
fn test_detect_soc() {
let soc = AppleSiliconMonitor::detect_soc_info();
if let Ok(soc_info) = soc {
println!("Detected SOC: {}", soc_info.name);
println!(
"E-cores: {:?}, P-cores: {:?}",
soc_info.e_core_count, soc_info.p_core_count
);
}
}
}