nmbrs-runtime 0.7.2

Workload execution runtime for nmbrs
Documentation
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! Memory utilization from `/proc/meminfo`, and memory bandwidth from
//! resctrl (SRD-118 §3.3, §3.4).

/// The three `/proc/meminfo` fields the two utilization measures need,
/// in kB as the kernel reports them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MemInfo {
    pub total_kb: u64,
    pub free_kb: u64,
    pub available_kb: u64,
}

pub fn parse_meminfo(text: &str) -> Option<MemInfo> {
    let mut total = None;
    let mut free = None;
    let mut available = None;
    for line in text.lines() {
        let mut t = line.split_whitespace();
        match t.next() {
            Some("MemTotal:") => total = t.next()?.parse().ok(),
            Some("MemFree:") => free = t.next()?.parse().ok(),
            Some("MemAvailable:") => available = t.next()?.parse().ok(),
            _ => {}
        }
    }
    Some(MemInfo {
        total_kb: total?,
        free_kb: free?,
        available_kb: available?,
    })
}

/// The two memory measures: (committed, everything-including-page-cache).
pub fn mem_utils(m: MemInfo) -> (f64, f64) {
    if m.total_kb == 0 {
        return (0.0, 0.0);
    }
    let committed = (m.total_kb.saturating_sub(m.available_kb)) as f64 / m.total_kb as f64;
    let cached = (m.total_kb.saturating_sub(m.free_kb)) as f64 / m.total_kb as f64;
    (committed.clamp(0.0, 1.0), cached.clamp(0.0, 1.0))
}

/// Sum of resctrl MBM total-bytes counters across mon_data groups, when the
/// resctrl filesystem is mounted with monitoring. `None` when unavailable.
pub(super) fn read_membw_bytes() -> Option<u64> {
    let root = std::path::Path::new("/sys/fs/resctrl/mon_data");
    let entries = std::fs::read_dir(root).ok()?;
    let mut sum: u64 = 0;
    let mut seen = false;
    for e in entries.flatten() {
        let f = e.path().join("mbm_total_bytes");
        if let Ok(text) = std::fs::read_to_string(&f)
            && let Ok(v) = text.trim().parse::<u64>()
        {
            sum += v;
            seen = true;
        }
    }
    seen.then_some(sum)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The two memory measures diverge exactly by reclaimable cache.
    #[test]
    fn committed_and_cached_measures_are_distinct() {
        let m =
            parse_meminfo("MemTotal: 1000 kB\nMemFree: 100 kB\nMemAvailable: 600 kB\n").unwrap();
        let (committed, cached) = mem_utils(m);
        assert!((committed - 0.4).abs() < 1e-9, "claimed = 1 - avail/total");
        assert!((cached - 0.9).abs() < 1e-9, "touched = 1 - free/total");
    }
}