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";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Threads {
One,
OneOrTwo,
}
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,
}
}
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")
}
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))
}
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)
}
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"
)
}
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"
)
}
#[must_use]
#[allow(clippy::too_many_lines)] 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
}