use std::fmt;
use crate::finding::{Finding, Severity};
use crate::host::{Host, ReadError};
use crate::platform::{Arch, arch_of};
pub const CLOCKSOURCE: &str = "/sys/devices/system/clocksource/clocksource0/current_clocksource";
const T12_EVIDENCE: &str = "Linux lib/vdso/gettimeofday.c (the system-call fallback for a clock \
source with no vDSO mode), kernel/time/clocksource.c (the watchdog), \
Documentation/admin-guide/kernel-parameters.txt (clocksource=, tsc=reliable); not measured \
here";
const PARAVIRT: [&str; 3] = ["kvm-clock", "hyperv_clocksource_tsc_page", "xen"];
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ClocksourceKind {
Counter,
Paravirt,
Other,
}
impl ClocksourceKind {
#[must_use]
pub fn of(name: &str) -> Self {
match name.trim() {
"tsc" | "arch_sys_counter" => Self::Counter,
n if PARAVIRT.contains(&n) => Self::Paravirt,
_ => Self::Other,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Clocksource {
pub name: Result<String, ReadError>,
pub arch: Arch,
pub invariant_tsc: Option<bool>,
}
impl Clocksource {
#[must_use]
pub fn read(host: &Host) -> Self {
let name = host.read_line(CLOCKSOURCE).and_then(|n| {
if n.is_empty() {
Err(ReadError::Malformed {
path: CLOCKSOURCE.to_owned(),
detail: "empty",
})
} else {
Ok(n)
}
});
let cpuinfo = host.read("/proc/cpuinfo").ok();
Self {
name,
arch: cpuinfo.as_deref().map_or(Arch::Unknown, arch_of),
invariant_tsc: cpuinfo.as_deref().and_then(invariant_tsc),
}
}
#[must_use]
pub fn kind(&self) -> Option<ClocksourceKind> {
self.name.as_deref().ok().map(ClocksourceKind::of)
}
#[must_use]
pub fn finding(&self) -> Finding {
let name = match &self.name {
Ok(n) => n.trim(),
Err(e) => {
return Finding::unknown(
"T12",
Severity::Warn,
T12_EVIDENCE,
"the kernel's clock source".to_owned(),
e,
);
}
};
match ClocksourceKind::of(name) {
ClocksourceKind::Counter => Finding::ok(
"T12",
Severity::Warn,
T12_EVIDENCE,
format!("clocksource {name}: the hardware counter, read through the vDSO"),
),
ClocksourceKind::Paravirt => Finding::found(
"T12",
Severity::Info,
T12_EVIDENCE,
format!(
"clocksource {name} is a hypervisor's scaled view of the counter, read \
through the vDSO where the hypervisor marks it stable"
),
),
ClocksourceKind::Other if self.arch == Arch::Unknown => Finding::unknown(
"T12",
Severity::Warn,
T12_EVIDENCE,
"the kernel's clock source".to_owned(),
format!(
"clocksource {name} on an architecture other than x86-64 or 64-bit Arm, or \
with no /proc/cpuinfo to tell: whether it is read through the vDSO is not \
known here"
),
),
ClocksourceKind::Other => Finding::found(
"T12",
Severity::Warn,
T12_EVIDENCE,
format!(
"clocksource {name} is not the counter and has no vDSO read mode: every \
CLOCK_REALTIME and CLOCK_MONOTONIC read (each UTC stamp, Aeron's clocks) is \
a system call, which costs more than a vDSO read (not measured here). The \
kernel leaves the counter when its watchdog marks it unstable (`dmesg | grep \
-i clocksource` says why); a clock that reads the counter itself (quanta) \
is not told. {}",
self.fix()
),
),
}
}
const fn fix(&self) -> &'static str {
match (self.arch, self.invariant_tsc) {
(Arch::X86_64, Some(false)) => {
"The TSC is not invariant here (no `constant_tsc nonstop_tsc` in /proc/cpuinfo), \
so the kernel's choice stands and forcing the TSC would be wrong."
}
(Arch::X86_64, _) => {
"Do not force it as a fix: `constant_tsc nonstop_tsc` say the TSC will not stop \
or drift, not that it agrees across cores, and `tsc=reliable` turns off the \
kernel's TSC checks. Force `clocksource=tsc tsc=reliable` on the node only on \
hardware qualified as the same across cores against a PTP/PHC reference, and \
never on a VM."
}
(Arch::Aarch64, _) => {
"On the node, boot with `clocksource=arch_sys_counter`, the generic timer the \
vDSO reads."
}
_ => {
"Find why the kernel left the counter (`dmesg | grep -i clocksource`) before \
changing it on the node."
}
}
}
}
fn invariant_tsc(cpuinfo: &str) -> Option<bool> {
let flags = cpuinfo.lines().find_map(|line| {
let (key, value) = line.split_once(':')?;
(key.trim() == "flags").then_some(value)
})?;
let has = |flag: &str| flags.split_whitespace().any(|f| f == flag);
Some(has("constant_tsc") && has("nonstop_tsc"))
}
#[must_use]
pub fn t12_clocksource(host: &Host) -> Finding {
Clocksource::read(host).finding()
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct ClocksourceName {
bytes: [u8; 32],
len: u8,
}
impl ClocksourceName {
#[must_use]
pub fn new(name: &str) -> Option<Self> {
let name = name.trim();
let len = u8::try_from(name.len())
.ok()
.filter(|n| (1..=32).contains(n))?;
let mut bytes = [0_u8; 32];
bytes
.get_mut(..name.len())?
.copy_from_slice(name.as_bytes());
Some(Self { bytes, len })
}
#[must_use]
pub fn as_str(&self) -> &str {
std::str::from_utf8(self.bytes.get(..usize::from(self.len)).unwrap_or_default())
.unwrap_or_default()
}
}
impl fmt::Debug for ClocksourceName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "ClocksourceName({:?})", self.as_str())
}
}
impl fmt::Display for ClocksourceName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn clock_sources_are_classified_by_name() {
assert_eq!(ClocksourceKind::of("tsc\n"), ClocksourceKind::Counter);
assert_eq!(
ClocksourceKind::of("arch_sys_counter"),
ClocksourceKind::Counter
);
assert_eq!(ClocksourceKind::of("kvm-clock"), ClocksourceKind::Paravirt);
assert_eq!(ClocksourceKind::of("hpet"), ClocksourceKind::Other);
assert_eq!(
ClocksourceKind::of("arch_mem_counter"),
ClocksourceKind::Other
);
}
#[test]
fn an_invariant_tsc_needs_both_flags() {
assert_eq!(
invariant_tsc("flags\t\t: fpu tsc constant_tsc nonstop_tsc\n"),
Some(true)
);
assert_eq!(invariant_tsc("flags\t: tsc constant_tsc\n"), Some(false));
assert_eq!(
invariant_tsc("flags\t: tsc constant_tsc_x nonstop_tsc\n"),
Some(false)
);
assert_eq!(invariant_tsc("Features\t: fp asimd\n"), None);
}
#[test]
fn a_name_is_held_inline() {
assert_eq!(
ClocksourceName::new("tsc\n").map(|n| n.to_string()),
Some("tsc".to_owned())
);
assert_eq!(ClocksourceName::new(" "), None);
assert_eq!(ClocksourceName::new(&"x".repeat(33)), None);
assert!(ClocksourceName::new(&"x".repeat(32)).is_some());
}
}