ergon-tune 0.1.45

Start-up and housekeeping checks of a host's low-latency settings (CPU isolation, NIC interrupts, transparent hugepages, the Aeron directory, NUMA, scheduling policy, SMT siblings, a CPU quota and its throttling, how CLOCK_REALTIME is kept and the kernel's clock source, background noise on the hot CPUs (unbound workqueues, compaction, other processes' tasks, kernel instrumentation, KSM, steal), a hot thread's page faults, the IRQ CPUs' idle depth and TCP autocorking, and with `nic` the NIC's moderation, deferral, VF and ring): pure functions returning findings, with no threads or statics, and one audited unsafe call (a read-only adjtimex)
Documentation
//! T26: the host's CPU layout and the caller's pinning map match the
//! declared instance family, so a map built for one family is not measured
//! on another.
//!
//! Reads `/proc/cpuinfo`, `/sys/class/dmi` and `/sys/devices/system/cpu`
//! only (unprivileged, visible from a pod).

use std::fmt::Write as _;

use crate::cpu::{busy_on, sqpoll_with_loop};
use crate::cpuset::CpuSet;
use crate::finding::{Finding, HotSet, Severity};
use crate::host::{Host, ReadError};
use crate::platform::{Platform, Vendor};

const T26_EVIDENCE: &str = "AWS instance-type families (ThreadsPerCore, one thread per core \
     on c7a and Graviton); kernel ABI/testing/sysfs-devices-system-cpu (thread_siblings_list); \
     not measured here";

/// How many hardware threads one core has, as a family's launch options
/// allow.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Threads {
    /// Exactly one: c7a (AMD, no SMT) and every Graviton family.
    One,
    /// One or two: c7i. `CpuOptions` `ThreadsPerCore: 1` gives one; the
    /// default gives two.
    OneOrTwo,
}

/// The vendor and thread layout a declared instance family requires.
fn family_spec(family: &str) -> Option<(Vendor, Threads)> {
    match family {
        "c7i" => Some((Vendor::Intel, Threads::OneOrTwo)),
        "c7a" => Some((Vendor::Amd, Threads::One)),
        "c8g" | "c9g" => Some((Vendor::Arm, Threads::One)),
        _ => None,
    }
}

/// The family part of a DMI product name (`c7i.2xlarge` → `c7i`), or the
/// name itself when it has no size.
fn family_of(product: &str) -> &str {
    product.split('.').next().unwrap_or(product)
}

fn siblings_path(cpu: u32) -> String {
    format!("/sys/devices/system/cpu/cpu{cpu}/topology/thread_siblings_list")
}

/// The online CPUs' layout: hardware threads per core (the largest
/// `thread_siblings_list`) and one CPU per physical core (each list's
/// lowest).
fn layout(host: &Host, online: &CpuSet) -> Result<(u32, CpuSet), ReadError> {
    let mut tpc = 1u32;
    let mut per_core = CpuSet::new();
    for cpu in online.iter() {
        let siblings = host.read_cpu_list(&siblings_path(cpu))?;
        tpc = tpc.max(siblings.len().try_into().unwrap_or(u32::MAX));
        per_core.insert(siblings.iter().next().unwrap_or(cpu));
    }
    Ok((tpc, per_core))
}

/// The busy CPUs of `map` that share a physical core, as `CPU 1 (loop) and
/// CPU 5 (sender)` pairs: a map that treats SMT siblings as two cores. The
/// roles are T8's: a housekeeping thread on a sibling, or an SQPOLL thread
/// on its loop's sibling, is not a wrong map.
fn sibling_pairs(host: &Host, map: &HotSet) -> Result<Vec<String>, ReadError> {
    let mut pairs: Vec<(u32, u32)> = Vec::new();
    for cpu in map.spinning().iter() {
        let siblings = host.read_cpu_list(&siblings_path(cpu))?;
        for s in siblings.iter().filter(|s| *s != cpu) {
            let pair = (cpu.min(s), cpu.max(s));
            if busy_on(map, s) && !pairs.contains(&pair) && !sqpoll_with_loop(map, cpu, s) {
                pairs.push(pair);
            }
        }
    }
    Ok(pairs
        .iter()
        .map(|(a, b)| format!("{} and {}", map.describe(*a), map.describe(*b)))
        .collect())
}

const fn mismatch(message: String) -> Finding {
    Finding::found("T26", Severity::Warn, T26_EVIDENCE, message)
}

/// The fix when the host is not the declared family.
fn host_fix(declared: &str, threads: Threads) -> String {
    let launch = match threads {
        Threads::One => "no CpuOptions: one thread per core is the family's only layout",
        Threads::OneOrTwo => "\"CpuOptions\": {\"ThreadsPerCore\": 1}",
    };
    format!(
        "Fix: declare this host's own family, or run on a {declared} host ({launch}). \
         Kubernetes: select the node by its instance type (nodeSelector \
         `node.kubernetes.io/instance-type`) and set CpuOptions in the node group's launch \
         template; node settings, never the pod's"
    )
}

/// The fix when the map does not fit the host's layout.
fn map_fix(declared: &str, threads: Threads, per_core: &CpuSet) -> String {
    let launch = match threads {
        Threads::One => "",
        Threads::OneOrTwo => ", or launch with \"CpuOptions\": {\"ThreadsPerCore\": 1}",
    };
    format!(
        "Fix: build the map for {declared} from one CPU per physical core ({per_core}), leaving \
         each core's other threads idle{launch}. Kubernetes: the kubelet's \
         `cpuManagerPolicyOptions: full-pcpus-only: \"true\"` on the node gives a pod whole \
         cores; the pod spec requests whole cores (Guaranteed QoS, integer CPUs) and the map \
         comes from the pod's own cpuset"
    )
}

/// T26: the host's CPU layout matches the declared instance family, and
/// the pinning map `map` fits that layout.
///
/// `family` is the instance family the caller declares (`c7i`, `c7a`,
/// `c8g`, `c9g`), with or without a size (`c7i.2xlarge`). A vendor or
/// thread-count mismatch, a map CPU that is not online, or a map that puts
/// two busy threads on SMT siblings warns (so `require` refuses): a wrong
/// map measures slow instead of failing. An unreadable vendor or layout, or
/// a family outside the table, is unknown, which also stops `require` (it
/// proves a property of this map).
#[must_use]
#[allow(clippy::too_many_lines)] // one finding path per mismatch kind
pub fn t26_family_layout(host: &Host, family: &str, map: &HotSet) -> Vec<Finding> {
    let id = "T26";
    let sev = Severity::Warn;
    let declared = family_of(family.trim());
    let Some((want_vendor, want_threads)) = family_spec(&declared.to_ascii_lowercase()) else {
        return vec![Finding::unknown(
            id,
            sev,
            T26_EVIDENCE,
            format!(
                "cannot check the layout: declared family {declared} is not one of c7i, c7a, \
                 c8g, c9g"
            ),
            "family not in the layout table",
        )];
    };
    let platform = Platform::detect(host);
    if platform.vendor == Vendor::Unknown {
        return vec![Finding::unknown(
            id,
            sev,
            T26_EVIDENCE,
            format!("cannot match this host's CPU vendor to {declared}"),
            "no GenuineIntel, AuthenticAMD or Arm CPU implementer in /proc/cpuinfo",
        )];
    }
    if platform.vendor != want_vendor {
        return vec![mismatch(format!(
            "declared family {declared} ({}) but this host's CPU is {}. {}",
            want_vendor.as_str(),
            platform.vendor.as_str(),
            host_fix(declared, want_threads)
        ))];
    }
    let layout = host
        .read_cpu_list("/sys/devices/system/cpu/online")
        .and_then(|online| layout(host, &online).map(|l| (online, l)));
    let (online, (tpc, per_core)) = match layout {
        Ok(l) => l,
        Err(e) => {
            return vec![Finding::unknown(
                id,
                sev,
                T26_EVIDENCE,
                format!("cannot tell the CPU layout for {declared}"),
                e,
            )];
        }
    };
    let mut out = Vec::new();
    match want_threads {
        Threads::One if tpc > 1 => {
            out.push(mismatch(format!(
                "declared family {declared} (one thread per core) but this host has {tpc} \
                 threads per core: a pinning map for {declared} counts those siblings as \
                 separate cores and measures slow. {}",
                host_fix(declared, want_threads)
            )));
        }
        Threads::OneOrTwo if tpc > 2 => {
            out.push(mismatch(format!(
                "declared family {declared} but this host has {tpc} threads per core (at most \
                 2). {}",
                host_fix(declared, want_threads)
            )));
        }
        _ => {}
    }
    let offline: Vec<String> = map
        .iter()
        .filter(|h| !online.contains(h.cpu))
        .map(|h| format!("CPU {}", h.cpu))
        .collect();
    if !offline.is_empty() {
        out.push(mismatch(format!(
            "pinning map for {declared} names {} not online on this host (online CPUs \
             ({online})): a map built for another core count. {}",
            offline.join(", "),
            map_fix(declared, want_threads, &per_core)
        )));
    }
    match sibling_pairs(host, map) {
        Ok(pairs) if !pairs.is_empty() => {
            out.push(mismatch(format!(
                "pinning map for {declared} treats SMT siblings as separate cores ({}): \
                 they share one core's execution units, so the map measures slow. {}",
                pairs.join("; "),
                map_fix(declared, want_threads, &per_core)
            )));
        }
        Ok(_) => {}
        Err(e) => out.push(Finding::unknown(
            id,
            sev,
            T26_EVIDENCE,
            format!("cannot tell whether the map for {declared} splits SMT siblings"),
            e,
        )),
    }
    if out.is_empty() {
        let map_part = if map.iter().next().is_none() {
            "no pinning map given (layout only)"
        } else {
            "map CPUs online, one busy thread per core"
        };
        let mut message = format!(
            "declared family {declared}: vendor {}, {tpc} thread(s) per core, {map_part}",
            platform.vendor.as_str()
        );
        if let Some(p) = &platform.product {
            let _ = write!(message, " (product {p})");
        }
        out.push(Finding::ok(id, sev, T26_EVIDENCE, message));
    }
    out
}