Skip to main content

qualia_core_db/net/qdnf/cells/
hardware.rs

1//! Process RSS and NUMA observation (E10.5).
2//!
3//! Sentinel pass accounting is not RSS. Idle joules stay unmeasured unless a
4//! RAPL energy counter is sampled as a delta, which this library does not do.
5
6use super::scaling::HardwareObservation;
7
8/// Linux `/proc/self/status` VmRSS, converted to bytes.
9pub fn rss_bytes() -> Result<u64, HardwareObservation> {
10    #[cfg(target_os = "linux")]
11    {
12        parse_vmrss_bytes(&read_limited("/proc/self/status")?)
13            .ok_or(HardwareObservation::Unmeasured)
14    }
15    #[cfg(not(target_os = "linux"))]
16    {
17        Err(HardwareObservation::Unsupported)
18    }
19}
20
21/// First NUMA node that holds pages for this process, else the first present node.
22pub fn numa_node() -> Result<u32, HardwareObservation> {
23    #[cfg(target_os = "linux")]
24    {
25        if let Ok(maps) = read_limited("/proc/self/numa_maps") {
26            if let Some(n) = parse_numa_maps_node(&maps) {
27                return Ok(n);
28            }
29        }
30        first_sysfs_node().ok_or(HardwareObservation::Unmeasured)
31    }
32    #[cfg(not(target_os = "linux"))]
33    {
34        Err(HardwareObservation::Unsupported)
35    }
36}
37
38/// Idle energy is a duration delta. A RAPL counter snapshot is not idle joules.
39pub fn idle_joules() -> Result<u64, HardwareObservation> {
40    let _ = rapl_energy_uj();
41    Err(HardwareObservation::Unmeasured)
42}
43
44/// RAPL energy counter if present. Not an idle-energy measurement.
45pub fn rapl_energy_uj() -> Result<u64, HardwareObservation> {
46    #[cfg(target_os = "linux")]
47    {
48        parse_u64_file("/sys/class/powercap/intel-rapl:0/energy_uj")
49            .or_else(|| parse_u64_file("/sys/class/powercap/intel-rapl/intel-rapl:0/energy_uj"))
50            .ok_or(HardwareObservation::Unsupported)
51    }
52    #[cfg(not(target_os = "linux"))]
53    {
54        Err(HardwareObservation::Unsupported)
55    }
56}
57
58#[inline]
59/// `?::rss_measured`.
60pub fn rss_measured() -> bool {
61    rss_bytes().is_ok()
62}
63
64#[inline]
65/// `?::numa_measured`.
66pub fn numa_measured() -> bool {
67    numa_node().is_ok()
68}
69
70#[inline]
71/// `?::idle_energy_measured`.
72pub const fn idle_energy_measured() -> bool {
73    false
74}
75
76#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
77const PROC_CAP: usize = 8192;
78
79#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
80fn read_limited(path: &str) -> Result<String, HardwareObservation> {
81    let bytes = std::fs::read(path).map_err(|_| HardwareObservation::Unmeasured)?;
82    if bytes.len() > PROC_CAP {
83        return Err(HardwareObservation::Unmeasured);
84    }
85    String::from_utf8(bytes).map_err(|_| HardwareObservation::Unmeasured)
86}
87
88#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
89fn parse_vmrss_bytes(status: &str) -> Option<u64> {
90    for line in status.lines() {
91        let Some(rest) = line.strip_prefix("VmRSS:") else {
92            continue;
93        };
94        let mut parts = rest.split_whitespace();
95        let n = parts.next()?.parse::<u64>().ok()?;
96        return Some(n.saturating_mul(1024));
97    }
98    None
99}
100
101#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
102fn parse_numa_maps_node(maps: &str) -> Option<u32> {
103    let mut best_node = 0u32;
104    let mut best_pages = 0u64;
105    let mut found = false;
106    for line in maps.lines() {
107        let mut rest = line;
108        while let Some(i) = rest.find('N') {
109            rest = &rest[i + 1..];
110            let digits_end = rest
111                .find(|c: char| !c.is_ascii_digit())
112                .unwrap_or(rest.len());
113            if digits_end == 0 {
114                continue;
115            }
116            if !rest[digits_end..].starts_with('=') {
117                continue;
118            }
119            let Ok(node) = rest[..digits_end].parse::<u32>() else {
120                rest = &rest[digits_end..];
121                continue;
122            };
123            let after_eq = &rest[digits_end + 1..];
124            let val_end = after_eq
125                .find(|c: char| !c.is_ascii_digit())
126                .unwrap_or(after_eq.len());
127            let pages: u64 = after_eq[..val_end].parse().unwrap_or(0);
128            if !found || pages > best_pages {
129                best_node = node;
130                best_pages = pages;
131                found = true;
132            }
133            rest = &rest[digits_end..];
134        }
135    }
136    if found {
137        Some(best_node)
138    } else {
139        None
140    }
141}
142
143#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
144fn first_sysfs_node() -> Option<u32> {
145    let mut n = 0u32;
146    while n < 8 {
147        let mut path = [0u8; 40];
148        let s = format_node_path(&mut path, n)?;
149        if std::path::Path::new(s).is_dir() {
150            return Some(n);
151        }
152        n = n + 1;
153    }
154    None
155}
156
157#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
158fn format_node_path<'a>(buf: &'a mut [u8], n: u32) -> Option<&'a str> {
159    let prefix = b"/sys/devices/system/node/node";
160    if buf.len() < prefix.len() + 2 {
161        return None;
162    }
163    buf[..prefix.len()].copy_from_slice(prefix);
164    if n > 9 {
165        return None;
166    }
167    buf[prefix.len()] = b'0' + n as u8;
168    core::str::from_utf8(&buf[..prefix.len() + 1]).ok()
169}
170
171#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
172fn parse_u64_file(path: &str) -> Option<u64> {
173    let raw = std::fs::read_to_string(path).ok()?;
174    raw.trim().parse().ok()
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180    use crate::net::qdnf::cells::pass_budget::pass_maps_process_rss;
181
182    #[test]
183    fn vmrss_parser_reads_kib_as_bytes() {
184        let sample = "Name:\tinit\nVmRSS:\t   42 kB\n";
185        assert_eq!(parse_vmrss_bytes(sample), Some(42 * 1024));
186        assert_eq!(parse_vmrss_bytes("Name:\tinit\n"), None);
187    }
188
189    #[test]
190    fn numa_maps_parser_picks_largest_node() {
191        let maps = "00400000 default file=/bin/a N0=3 N1=9\n";
192        assert_eq!(parse_numa_maps_node(maps), Some(1));
193        assert_eq!(parse_numa_maps_node("00400000 default\n"), None);
194    }
195
196    #[test]
197    fn linux_rss_and_numa_are_sampled_or_unmeasured() {
198        assert!(!pass_maps_process_rss());
199        assert!(!idle_energy_measured());
200        assert_eq!(idle_joules(), Err(HardwareObservation::Unmeasured));
201        #[cfg(target_os = "linux")]
202        {
203            match rss_bytes() {
204                Ok(n) => {
205                    assert!(n > 0);
206                    assert!(rss_measured());
207                }
208                Err(HardwareObservation::Unmeasured) => assert!(!rss_measured()),
209                Err(other) => panic!("linux RSS must not be {:?}", other),
210            }
211            match numa_node() {
212                Ok(_) => assert!(numa_measured()),
213                Err(HardwareObservation::Unmeasured) => assert!(!numa_measured()),
214                Err(other) => panic!("linux NUMA must not be {:?}", other),
215            }
216            match rapl_energy_uj() {
217                Ok(_) | Err(HardwareObservation::Unsupported) => {}
218                Err(other) => panic!("RAPL snapshot must not be {:?}", other),
219            }
220        }
221        #[cfg(not(target_os = "linux"))]
222        {
223            assert_eq!(rss_bytes(), Err(HardwareObservation::Unsupported));
224            assert_eq!(numa_node(), Err(HardwareObservation::Unsupported));
225            assert!(!rss_measured());
226            assert!(!numa_measured());
227        }
228    }
229}