Skip to main content

nmbrs_runtime/sysmon/
mem.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Memory utilization from `/proc/meminfo`, and memory bandwidth from
5//! resctrl (SRD-118 §3.3, §3.4).
6
7/// The three `/proc/meminfo` fields the two utilization measures need,
8/// in kB as the kernel reports them.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub struct MemInfo {
11    pub total_kb: u64,
12    pub free_kb: u64,
13    pub available_kb: u64,
14}
15
16pub fn parse_meminfo(text: &str) -> Option<MemInfo> {
17    let mut total = None;
18    let mut free = None;
19    let mut available = None;
20    for line in text.lines() {
21        let mut t = line.split_whitespace();
22        match t.next() {
23            Some("MemTotal:") => total = t.next()?.parse().ok(),
24            Some("MemFree:") => free = t.next()?.parse().ok(),
25            Some("MemAvailable:") => available = t.next()?.parse().ok(),
26            _ => {}
27        }
28    }
29    Some(MemInfo {
30        total_kb: total?,
31        free_kb: free?,
32        available_kb: available?,
33    })
34}
35
36/// The two memory measures: (committed, everything-including-page-cache).
37pub fn mem_utils(m: MemInfo) -> (f64, f64) {
38    if m.total_kb == 0 {
39        return (0.0, 0.0);
40    }
41    let committed = (m.total_kb.saturating_sub(m.available_kb)) as f64 / m.total_kb as f64;
42    let cached = (m.total_kb.saturating_sub(m.free_kb)) as f64 / m.total_kb as f64;
43    (committed.clamp(0.0, 1.0), cached.clamp(0.0, 1.0))
44}
45
46/// Sum of resctrl MBM total-bytes counters across mon_data groups, when the
47/// resctrl filesystem is mounted with monitoring. `None` when unavailable.
48pub(super) fn read_membw_bytes() -> Option<u64> {
49    let root = std::path::Path::new("/sys/fs/resctrl/mon_data");
50    let entries = std::fs::read_dir(root).ok()?;
51    let mut sum: u64 = 0;
52    let mut seen = false;
53    for e in entries.flatten() {
54        let f = e.path().join("mbm_total_bytes");
55        if let Ok(text) = std::fs::read_to_string(&f)
56            && let Ok(v) = text.trim().parse::<u64>()
57        {
58            sum += v;
59            seen = true;
60        }
61    }
62    seen.then_some(sum)
63}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68
69    /// The two memory measures diverge exactly by reclaimable cache.
70    #[test]
71    fn committed_and_cached_measures_are_distinct() {
72        let m =
73            parse_meminfo("MemTotal: 1000 kB\nMemFree: 100 kB\nMemAvailable: 600 kB\n").unwrap();
74        let (committed, cached) = mem_utils(m);
75        assert!((committed - 0.4).abs() < 1e-9, "claimed = 1 - avail/total");
76        assert!((cached - 0.9).abs() < 1e-9, "touched = 1 - free/total");
77    }
78}