Skip to main content

all_smi/device/
cpu_linux.rs

1// Copyright 2025 Lablup Inc. and Jeongkyu Shin
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::{BTreeMap, HashSet};
16use std::fs;
17use std::path::Path;
18use std::sync::RwLock;
19use sysinfo::System;
20
21use chrono::Local;
22use once_cell::sync::Lazy;
23
24use crate::device::container_info::{ContainerInfo, parse_cpu_stat_with_container_limits};
25use crate::device::cpu_topology::{
26    self, CoreTier, decode_midr, group_cpus_by_capacity, parse_cpumask_list, tier_label_for_rank,
27    tier_of, tier_utilization,
28};
29use crate::device::{CoreType, CoreUtilization, CpuInfo, CpuReader, CpuSocketInfo, CpuTier};
30use crate::utils::system::get_hostname;
31
32mod cpuinfo;
33mod temperature;
34use cpuinfo::{FrequencySource, StaticCpuInfo};
35#[cfg_attr(not(feature = "cli"), allow(unused_imports))]
36pub(crate) use temperature::{ASUS_WMI_SENSORS_DRIVER, CpuTempResolution, TempRule};
37use temperature::{CPU_TEMP_SOURCE, CpuTempSource};
38
39/// The process-wide CPU temperature resolution plus a current reading, for
40/// `all-smi doctor`. Resolves through the same cached source the readers use,
41/// so calling it never adds a second sysfs scan.
42#[cfg_attr(not(feature = "cli"), allow(dead_code))]
43pub(crate) fn cpu_temp_status() -> (&'static CpuTempResolution, Option<u32>) {
44    (CPU_TEMP_SOURCE.resolution(), CPU_TEMP_SOURCE.read_celsius())
45}
46
47type CpuStatParseResult =
48    Result<(f64, Vec<CpuSocketInfo>, Vec<CoreUtilization>), Box<dyn std::error::Error>>;
49
50// Cache container detection result globally to avoid repeated filesystem operations
51static CONTAINER_INFO: Lazy<ContainerInfo> = Lazy::new(ContainerInfo::detect);
52
53/// Static CPU tier topology detected once per reader (issue #473).
54///
55/// `tiers` carries labels and core counts; only the per-tick utilization is
56/// refreshed. `tier_by_cpu` maps a **host** CPU id to its tier position, which
57/// is what the container path needs before it renumbers `core_id`
58/// sequentially.
59#[derive(Debug, Clone, Default)]
60struct CpuTopology {
61    tiers: Vec<CpuTier>,
62    tier_by_cpu: Vec<Option<u8>>,
63}
64
65/// Upper bound on detected tiers. Positions are stored as `u8` and the remote
66/// parser caps at the same value, so a machine with more distinct firmware
67/// capacities than this is truncated rather than risk an index overflow.
68const MAX_DETECTED_TIERS: usize = 64;
69
70/// Highest CPU id the tier map tracks.
71///
72/// `tier_by_cpu` is indexed by CPU id, so a single implausible id would size the
73/// vector to that id. A real machine numbers its logical CPUs in the low
74/// thousands, and this matches the cpumask expansion bound, so anything above
75/// it is treated as untiered instead of sizing an allocation from a file that a
76/// corrupted or attacker-controlled sysfs could supply.
77const MAX_TRACKED_CPU_ID: u32 = 8191;
78
79impl CpuTopology {
80    fn tier_index_for(&self, cpu_id: u32) -> Option<u8> {
81        self.tier_by_cpu.get(cpu_id as usize).copied().flatten()
82    }
83}
84
85/// Detect the CPU tier topology from sysfs.
86///
87/// Precedence, each step falling through when it cannot confirm at least two
88/// tiers:
89/// 1. Intel hybrid PMU cpumasks (`cpu_core/cpus` -> `P`, `cpu_atom/cpus` -> `E`).
90/// 2. arm64 `MIDR_EL1` part numbers mapped through [`tier_of`].
91/// 3. Firmware `cpu_capacity`, grouped descending and labelled through
92///    [`tier_label_for_rank`].
93/// 4. Empty (homogeneous or undetected).
94///
95/// `root` is `/sys` in production and a fixture directory in tests. `allowed`
96/// is the container cpuset; `None` means every CPU on the host participates.
97/// The function never fails: an unreadable source is skipped and the affected
98/// cores stay untiered.
99fn detect_cpu_tiers(root: &Path, allowed: Option<&[u32]>) -> CpuTopology {
100    let mut cpu_ids = enumerate_cpu_ids(root);
101    if let Some(allowed) = allowed {
102        let allowed: HashSet<u32> = allowed.iter().copied().collect();
103        cpu_ids.retain(|id| allowed.contains(id));
104    }
105    if cpu_ids.is_empty() {
106        return CpuTopology::default();
107    }
108
109    detect_intel_hybrid(root, &cpu_ids)
110        .or_else(|| detect_arm_midr(root, &cpu_ids))
111        .or_else(|| detect_capacity(root, &cpu_ids))
112        .unwrap_or_default()
113}
114
115/// Enumerate logical CPU ids from `devices/system/cpu/cpuN` directories,
116/// falling back to the kernel `possible` cpumask when the directory listing is
117/// unavailable.
118fn enumerate_cpu_ids(root: &Path) -> Vec<u32> {
119    let cpu_dir = root.join("devices/system/cpu");
120    let mut ids = Vec::new();
121
122    if let Ok(entries) = fs::read_dir(&cpu_dir) {
123        for entry in entries.flatten() {
124            let name = entry.file_name();
125            let name = name.to_string_lossy();
126            if let Some(suffix) = name.strip_prefix("cpu")
127                && let Ok(id) = suffix.parse::<u32>()
128            {
129                ids.push(id);
130            }
131        }
132    }
133
134    if ids.is_empty()
135        && let Ok(mask) = fs::read_to_string(cpu_dir.join("possible"))
136    {
137        ids = parse_cpumask_list(&mask);
138    }
139
140    // A directory entry or cpumask may name `cpuN` with an arbitrary `N`; the
141    // per-CPU tier map is indexed by id, so ignore ids beyond the tracked range
142    // rather than let one entry size an allocation proportional to it.
143    ids.retain(|id| *id <= MAX_TRACKED_CPU_ID);
144    ids.sort_unstable();
145    ids.dedup();
146    ids
147}
148
149/// Intel hybrid: map the `cpu_core` PMU cpumask to `P` and `cpu_atom` to `E`.
150///
151/// The kernel registers exactly two hybrid classes, so there is no third tier
152/// to invent. Requires at least one core in each class.
153fn detect_intel_hybrid(root: &Path, cpu_ids: &[u32]) -> Option<CpuTopology> {
154    let base = root.join("bus/event_source/devices");
155    let p_mask = fs::read_to_string(base.join("cpu_core/cpus")).ok()?;
156    let e_mask = fs::read_to_string(base.join("cpu_atom/cpus")).ok()?;
157
158    let allowed: HashSet<u32> = cpu_ids.iter().copied().collect();
159    let mut performance: Vec<u32> = parse_cpumask_list(&p_mask)
160        .into_iter()
161        .filter(|id| allowed.contains(id))
162        .collect();
163    let mut efficiency: Vec<u32> = parse_cpumask_list(&e_mask)
164        .into_iter()
165        .filter(|id| allowed.contains(id))
166        .collect();
167
168    if performance.is_empty() || efficiency.is_empty() {
169        return None;
170    }
171
172    performance.sort_unstable();
173    efficiency.sort_unstable();
174    Some(topology_from_labeled_groups(vec![
175        ("P".to_string(), performance),
176        ("E".to_string(), efficiency),
177    ]))
178}
179
180/// arm64: classify each CPU by its `MIDR_EL1` part number.
181///
182/// `Big` becomes `P`, `Mid` becomes `M` and `Little` becomes `E`. Unknown or
183/// unreadable parts stay untiered; fewer than two confirmed tiers falls
184/// through to the capacity fallback.
185fn detect_arm_midr(root: &Path, cpu_ids: &[u32]) -> Option<CpuTopology> {
186    let mut by_tier: BTreeMap<CoreTier, Vec<u32>> = BTreeMap::new();
187
188    for &cpu_id in cpu_ids {
189        let path = root.join(format!(
190            "devices/system/cpu/cpu{cpu_id}/regs/identification/midr_el1"
191        ));
192        let Ok(text) = fs::read_to_string(&path) else {
193            continue;
194        };
195        let Some(part) = decode_midr(&text) else {
196            continue;
197        };
198        let Some(tier) = tier_of(part) else {
199            continue;
200        };
201        by_tier.entry(tier).or_default().push(cpu_id);
202    }
203
204    if by_tier.len() < 2 {
205        return None;
206    }
207
208    // `BTreeMap` orders `Little < Mid < Big`; the tier list must be fastest
209    // first, so pull them explicitly.
210    let groups = [CoreTier::Big, CoreTier::Mid, CoreTier::Little]
211        .into_iter()
212        .filter_map(|tier| {
213            by_tier
214                .remove(&tier)
215                .map(|cores| (tier.label().to_string(), cores))
216        })
217        .collect();
218    Some(topology_from_labeled_groups(groups))
219}
220
221/// Firmware capacity fallback: group CPUs by `cpu_capacity`, order the groups
222/// by capacity descending, and emit them only when at least two distinct
223/// values exist.
224fn detect_capacity(root: &Path, cpu_ids: &[u32]) -> Option<CpuTopology> {
225    let mut capacities = Vec::new();
226    for &cpu_id in cpu_ids {
227        let path = root.join(format!("devices/system/cpu/cpu{cpu_id}/cpu_capacity"));
228        if let Ok(text) = fs::read_to_string(&path)
229            && let Ok(capacity) = text.trim().parse::<u32>()
230            && capacity > 0
231        {
232            capacities.push((cpu_id, capacity));
233        }
234    }
235
236    let mut groups = group_cpus_by_capacity(&capacities);
237    if groups.len() < 2 {
238        return None;
239    }
240    // Keep the fastest groups; cores in a truncated group stay untiered.
241    groups.truncate(MAX_DETECTED_TIERS);
242
243    Some(topology_from_labeled_groups(
244        groups
245            .into_iter()
246            .enumerate()
247            .map(|(position, (_, cores))| (tier_label_for_rank(position), cores))
248            .collect(),
249    ))
250}
251
252/// Build a topology from ordered `(label, cpu ids)` groups, fastest first.
253///
254/// The list is capped at [`MAX_DETECTED_TIERS`] so tier positions always fit
255/// a `u8`; callers pass groups already ordered fastest first, so the cap keeps
256/// the fastest ones.
257fn topology_from_labeled_groups(mut groups: Vec<(String, Vec<u32>)>) -> CpuTopology {
258    groups.truncate(MAX_DETECTED_TIERS);
259    // Defense in depth: an id beyond the tracked range would size `tier_by_cpu`
260    // to that id, so it is dropped here as well as in `enumerate_cpu_ids`.
261    for (_, cores) in &mut groups {
262        cores.retain(|id| *id <= MAX_TRACKED_CPU_ID);
263    }
264    let total = groups.len();
265    let max_cpu_id = groups
266        .iter()
267        .flat_map(|(_, cores)| cores.iter().copied())
268        .max()
269        .unwrap_or(0);
270    let mut tier_by_cpu = vec![None; max_cpu_id as usize + 1];
271    let mut tiers = Vec::with_capacity(total);
272
273    for (position, (label, cores)) in groups.into_iter().enumerate() {
274        for cpu_id in &cores {
275            if let Some(slot) = tier_by_cpu.get_mut(*cpu_id as usize) {
276                *slot = Some(position as u8);
277            }
278        }
279        tiers.push(CpuTier {
280            label,
281            core_type: cpu_topology::coarse_core_type(position, total),
282            core_count: cores.len() as u32,
283            utilization: 0.0,
284            frequency_mhz: None,
285            l2_cache_mb: None,
286        });
287    }
288
289    CpuTopology { tiers, tier_by_cpu }
290}
291
292pub struct LinuxCpuReader {
293    container_info: &'static ContainerInfo,
294    // System handle for CPU monitoring
295    system: RwLock<System>,
296    // Track if we've done the first refresh
297    first_refresh_done: RwLock<bool>,
298    /// Static tier topology, read from sysfs once at construction and never
299    /// per tick (issue #473).
300    topology: CpuTopology,
301    /// Process-wide CPU temperature source, shared by every reader instance.
302    temp_source: &'static CpuTempSource,
303    /// The kernel's machine string (`uname -m`), read once through
304    /// `uname(2)` instead of spawning `uname` every tick (issue #504). The
305    /// tick reads `architecture` from `static_info`; this copy is what the
306    /// test-only full parser runs with.
307    #[cfg_attr(not(test), allow(dead_code))]
308    machine: String,
309    /// Everything `/proc/cpuinfo` says that does not change per tick, read
310    /// once at construction (issue #504). `None` only when `/proc/cpuinfo`
311    /// could not be read, in which case every sample reports the error.
312    static_info: Option<StaticCpuInfo>,
313    /// Per-tick current-frequency source (issue #504).
314    frequency: FrequencySource,
315    /// Host CPU ids a container may use, intersected with the `cpuN` lines of
316    /// `/proc/stat`. Read once at construction: neither the cpuset nor the
317    /// CPU list changes per tick (issue #504). Empty outside a container.
318    container_active_cores: Vec<u32>,
319}
320
321impl Default for LinuxCpuReader {
322    fn default() -> Self {
323        Self::new()
324    }
325}
326
327impl LinuxCpuReader {
328    pub fn new() -> Self {
329        // Create system with minimal initialization - delay CPU refresh until needed
330        let system = crate::utils::system::new_system();
331        let container_info: &'static ContainerInfo = &CONTAINER_INFO;
332        let cpuset = container_info.cpuset_cpus.as_deref();
333
334        // Topology is static for the process lifetime, so it is read once here
335        // and never from the per-tick paths (issue #473).
336        let topology = detect_cpu_tiers(Path::new("/sys"), cpuset);
337
338        // Static CPU description, frequency source and the container's core
339        // list are likewise read once here (issue #504).
340        let machine = cpuinfo::machine_string();
341        let static_info = match fs::read_to_string("/proc/cpuinfo") {
342            Ok(content) => match StaticCpuInfo::load(&content, &machine, container_info) {
343                Ok(info) => Some(info),
344                Err(e) => {
345                    eprintln!("Error parsing /proc/cpuinfo: {e}");
346                    None
347                }
348            },
349            Err(e) => {
350                eprintln!("Error reading /proc/cpuinfo: {e}");
351                None
352            }
353        };
354        let frequency = FrequencySource::resolve(Path::new("/sys"), cpuset);
355        let container_active_cores = if container_info.is_container {
356            fs::read_to_string("/proc/stat")
357                .map(|stat| parse_cpu_stat_with_container_limits(&stat, container_info).1)
358                .unwrap_or_default()
359        } else {
360            Vec::new()
361        };
362
363        Self {
364            container_info,
365            system: RwLock::new(system),
366            first_refresh_done: RwLock::new(false),
367            topology,
368            temp_source: &CPU_TEMP_SOURCE,
369            machine,
370            static_info,
371            frequency,
372            container_active_cores,
373        }
374    }
375
376    /// Build a reader that resolves CPU temperature through `source` instead of
377    /// the process-wide `/sys` instance, so tests can count scans across readers.
378    #[cfg(test)]
379    fn with_temp_source(source: &'static CpuTempSource) -> Self {
380        Self {
381            temp_source: source,
382            ..Self::new()
383        }
384    }
385
386    /// Clone the static topology and refresh only the per-tick utilization.
387    fn resolved_tiers(&self, per_core: &[CoreUtilization]) -> Vec<CpuTier> {
388        let mut tiers = self.topology.tiers.clone();
389        for (position, tier) in tiers.iter_mut().enumerate() {
390            tier.utilization = tier_utilization(per_core, position);
391        }
392        tiers
393    }
394
395    /// Parse a full `/proc/cpuinfo` with this reader's machine string and
396    /// container view. Only construction and tests call it; the tick reads
397    /// the static result instead.
398    #[cfg(test)]
399    fn parse_cpuinfo(&self, content: &str) -> cpuinfo::CpuInfoParseResult {
400        cpuinfo::parse_cpuinfo(content, &self.machine, self.container_info)
401    }
402
403    /// The current base frequency for this tick (issue #504).
404    ///
405    /// `scaling_cur_freq` averaged over the CPUs that count when cpufreq
406    /// exists, so `/proc/cpuinfo` is not regenerated by the kernel every
407    /// tick; otherwise only the `cpu MHz` lines of `/proc/cpuinfo`; otherwise
408    /// the value computed at construction.
409    fn current_base_frequency(&self, static_base: u32) -> u32 {
410        let sampled = if self.frequency.is_empty() {
411            fs::read_to_string("/proc/cpuinfo")
412                .ok()
413                .and_then(|content| {
414                    cpuinfo::parse_cpu_mhz(&content, self.container_info.cpuset_cpus.as_deref())
415                })
416        } else {
417            self.frequency.sample()
418        };
419        sampled.unwrap_or(static_base)
420    }
421
422    fn get_cpu_info_from_proc(&self) -> Result<CpuInfo, Box<dyn std::error::Error>> {
423        let static_info = self
424            .static_info
425            .as_ref()
426            .ok_or("/proc/cpuinfo was unreadable when the CPU reader was built")?;
427
428        // OPTIMIZATION: Refresh CPU usage ONCE per collection cycle
429        // On first call, do initial refresh with delay to establish baseline
430        if !*self.first_refresh_done.read().unwrap() {
431            self.system.write().unwrap().refresh_cpu_usage();
432            // Minimal delay for initial measurement (only on first call)
433            std::thread::sleep(std::time::Duration::from_millis(10));
434            *self.first_refresh_done.write().unwrap() = true;
435        }
436        // Single refresh for current data
437        self.system.write().unwrap().refresh_cpu_usage();
438        let hostname = get_hostname();
439        let instance = hostname.clone();
440        let time = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
441
442        let base_frequency = self.current_base_frequency(static_info.base_frequency_mhz);
443        let total_cores = static_info.total_cores;
444        let total_threads = static_info.total_threads;
445
446        // Get overall CPU utilization from sysinfo
447        let overall_utilization = self.system.read().unwrap().global_cpu_usage() as f64;
448
449        // sysinfo's `refresh_cpu_usage` above already read `/proc/stat`; the
450        // container's core list was resolved at construction (issue #504).
451        let (per_socket_info, per_core_utilization) = if self.container_info.is_container {
452            let core_utils = self.container_core_utilization();
453            // Create socket info for container
454            let socket_info = vec![CpuSocketInfo {
455                socket_id: 0,
456                utilization: overall_utilization,
457                cores: total_cores,
458                threads: total_threads,
459                temperature: None,
460                frequency_mhz: base_frequency,
461            }];
462            (socket_info, core_utils)
463        } else {
464            let (_util, socket_info, core_utils) = self.parse_cpu_stat(static_info.socket_count)?;
465            (socket_info, core_utils)
466        };
467
468        // Try to get CPU temperature (may not be available on all systems)
469        let temperature = self.get_cpu_temperature();
470
471        // Power consumption is not readily available on most Linux systems
472        let power_consumption = None;
473
474        let cpu_tiers = self.resolved_tiers(&per_core_utilization);
475
476        Ok(CpuInfo {
477            index: 0,                  // Overwritten by AllSmi::get_cpu_info when flattening readers
478            host_id: hostname.clone(), // For local mode, host_id is just the hostname
479            hostname,
480            instance,
481            cpu_model: static_info.cpu_model.clone(),
482            architecture: static_info.architecture.clone(),
483            platform_type: static_info.platform_type.clone(),
484            socket_count: static_info.socket_count,
485            total_cores,
486            total_threads,
487            base_frequency_mhz: base_frequency,
488            max_frequency_mhz: static_info.max_frequency_mhz,
489            cache_size_mb: static_info.cache_size_mb,
490            utilization: overall_utilization,
491            temperature,
492            power_consumption,
493            per_socket_info,
494            apple_silicon_info: None, // Not applicable for Linux
495            cpu_tiers,
496            per_core_utilization,
497            time,
498        })
499    }
500
501    /// Per-core rows for a container: one per active host core, renumbered
502    /// sequentially for display, with utilization and tier read from the real
503    /// host CPU id.
504    fn container_core_utilization(&self) -> Vec<CoreUtilization> {
505        // Limit the number of cores displayed based on container limits
506        let max_cores_to_display = if self.container_info.cpuset_cpus.is_some() {
507            self.container_active_cores.len()
508        } else {
509            // If no cpuset, limit to effective CPU count
510            self.container_info.effective_cpu_count.ceil() as usize
511        };
512
513        // Use sysinfo to get accurate CPU utilization with delta calculation
514        let system = self.system.read().unwrap();
515        let cpus = system.cpus();
516
517        self.container_active_cores
518            .iter()
519            .take(max_cores_to_display)
520            .enumerate()
521            .map(|(idx, &core_id)| CoreUtilization {
522                core_id: idx as u32, // Sequential display id, read from the real core_id
523                core_type: CoreType::Standard,
524                utilization: cpus
525                    .get(core_id as usize)
526                    .map_or(0.0, |cpu| cpu.usage() as f64),
527                // Look up the real host CPU id before the display id is
528                // renumbered (issue #473).
529                tier_index: self.topology.tier_index_for(core_id),
530            })
531            .collect()
532    }
533
534    fn parse_cpu_stat(&self, socket_count: u32) -> CpuStatParseResult {
535        // OPTIMIZATION: Don't refresh here - caller (get_cpu_info_from_proc) already refreshed
536        // This avoids duplicate refresh_cpu_usage() calls which was causing high CPU usage
537        // However, for direct calls (e.g., tests), we need to ensure cpus() is populated
538        {
539            let system = self.system.read().unwrap();
540            if system.cpus().is_empty() {
541                drop(system);
542                // Fallback: refresh if not yet initialized (for direct test calls)
543                self.system.write().unwrap().refresh_cpu_usage();
544                std::thread::sleep(std::time::Duration::from_millis(10));
545                self.system.write().unwrap().refresh_cpu_usage();
546            }
547        }
548
549        let overall_utilization = self.system.read().unwrap().global_cpu_usage() as f64;
550        let mut per_socket_info = Vec::new();
551        let mut per_core_utilization = Vec::new();
552
553        // Use sysinfo to get per-core utilization
554        let system = self.system.read().unwrap();
555        let cpus = system.cpus();
556
557        for (core_id, cpu) in cpus.iter().enumerate() {
558            let utilization = cpu.usage() as f64;
559
560            // Check if this is a P-core or E-core based on CPU topology
561            // For now, we'll use Standard type for all Linux cores
562            let core_type = CoreType::Standard;
563
564            per_core_utilization.push(CoreUtilization {
565                core_id: core_id as u32,
566                core_type,
567                utilization,
568                // The host path's `core_id` is the host CPU id.
569                tier_index: self.topology.tier_index_for(core_id as u32),
570            });
571        }
572
573        // Sort cores by ID for consistent display
574        per_core_utilization.sort_by_key(|c| c.core_id);
575
576        // Create per-socket info (simplified - assumes even distribution across sockets)
577        for socket_id in 0..socket_count {
578            per_socket_info.push(CpuSocketInfo {
579                socket_id,
580                utilization: overall_utilization, // Simplified - same as overall
581                cores: 0,          // Will be calculated based on total_cores / socket_count
582                threads: 0,        // Will be calculated based on total_threads / socket_count
583                temperature: None, // Not easily available per socket
584                frequency_mhz: 0,  // Will be set from base frequency
585            });
586        }
587
588        Ok((overall_utilization, per_socket_info, per_core_utilization))
589    }
590
591    fn get_cpu_temperature(&self) -> Option<u32> {
592        // The sensor is resolved once per process on the first read; each sample
593        // then reads only the cached file (issue #492).
594        self.temp_source.read_celsius()
595    }
596
597    /// L3 (else L2) cache size from the process-wide cached `lscpu` output.
598    #[cfg(test)]
599    fn get_cache_size_from_lscpu(&self) -> Option<u32> {
600        cpuinfo::lscpu_output().and_then(cpuinfo::cache_size_from_lscpu)
601    }
602}
603
604impl CpuReader for LinuxCpuReader {
605    fn get_cpu_info(&self) -> Vec<CpuInfo> {
606        match self.get_cpu_info_from_proc() {
607            Ok(mut cpu_info) => {
608                // Fill in cores and threads per socket
609                let cores_per_socket = cpu_info.total_cores / cpu_info.socket_count;
610                let threads_per_socket = cpu_info.total_threads / cpu_info.socket_count;
611
612                for socket_info in &mut cpu_info.per_socket_info {
613                    socket_info.cores = cores_per_socket;
614                    socket_info.threads = threads_per_socket;
615                    socket_info.frequency_mhz = cpu_info.base_frequency_mhz;
616                }
617
618                // A quota-only container detects tiers across the whole host
619                // but emits only the cores it may use, so recount from the
620                // cores this payload actually carries (issue #473). Done here,
621                // in the reader, so every consumer sees the reconciled list:
622                // the local TUI and API loop call this trait method directly
623                // rather than going through `AllSmi::get_cpu_info`.
624                cpu_info.reconcile_cpu_tiers();
625
626                vec![cpu_info]
627            }
628            Err(e) => {
629                eprintln!("Error reading CPU info: {e}");
630                vec![]
631            }
632        }
633    }
634}
635
636#[cfg(test)]
637#[path = "cpu_linux/tests.rs"]
638mod tests;