use std::fs::File;
use crate::cpu::Thread;
use crate::finding::{Finding, Role, Severity};
use crate::host::{Host, ReadError};
use crate::quota::read_from_start;
const T19_EVIDENCE: &str = "Linux proc(5) (/proc/<pid>/task/<tid>/stat: minflt, field 10; \
majflt, field 12); not measured here";
const BUF: usize = 1024;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Faults {
pub minor: u64,
pub major: u64,
}
impl Faults {
#[must_use]
pub const fn since(&self, earlier: &Self) -> Self {
Self {
minor: self.minor.saturating_sub(earlier.minor),
major: self.major.saturating_sub(earlier.major),
}
}
}
fn parse_faults(text: &str) -> Result<Faults, &'static str> {
let (_, after_comm) = text.rsplit_once(')').ok_or("no command name")?;
let mut f = after_comm.split_whitespace().skip(10 - 3);
let mut number = || -> Result<u64, &'static str> {
f.next()
.ok_or("fewer fields than a stat line has")?
.parse()
.map_err(|_| "a fault counter that is not a number")
};
let minor = number()?;
let _children_minor = number()?;
let major = number()?;
Ok(Faults { minor, major })
}
#[derive(Debug)]
pub struct FaultWatch {
path: String,
file: File,
buf: Vec<u8>,
role: Role,
last: Faults,
failed: bool,
}
impl FaultWatch {
pub fn open(host: &Host, thread: Thread, role: Role) -> Result<Self, ReadError> {
Self::open_path(host, thread.file("stat"), role)
}
pub fn open_task(host: &Host, pid: u32, tid: u32, role: Role) -> Result<Self, ReadError> {
Self::open_path(host, format!("/proc/{pid}/task/{tid}/stat"), role)
}
fn open_path(host: &Host, path: String, role: Role) -> Result<Self, ReadError> {
let file = host.open(&path)?;
let mut watch = Self {
path,
file,
buf: vec![0; BUF],
role,
last: Faults::default(),
failed: false,
};
watch.last = watch.sample()?;
Ok(watch)
}
#[must_use]
pub fn path(&self) -> &str {
&self.path
}
#[must_use]
pub const fn last(&self) -> Faults {
self.last
}
pub fn sample(&mut self) -> Result<Faults, ReadError> {
let n = read_from_start(&self.file, &mut self.buf)
.map_err(|e| ReadError::io(&self.path, &e))?;
let malformed = |detail| ReadError::Malformed {
path: self.path.clone(),
detail,
};
let text = std::str::from_utf8(&self.buf[..n]).map_err(|_| malformed("not text"))?;
parse_faults(text).map_err(malformed)
}
pub fn check(&mut self) -> Option<Finding> {
let now = match self.sample() {
Ok(f) => f,
Err(e) => {
if self.failed {
return None;
}
self.failed = true;
return Some(Finding::unknown(
"T19",
Severity::Warn,
T19_EVIDENCE,
format!("cannot read the {} thread's page faults", self.role.name()),
e,
));
}
};
self.failed = false;
let (before, d) = (self.last, now.since(&self.last));
self.last = now;
if d == Faults::default() {
return None;
}
Some(Finding::found(
"T19",
Severity::Warn,
T19_EVIDENCE,
format!(
"the {} thread ({}) took {} minor and {} major page faults since the last check \
(minflt {} → {}, majflt {} → {}): each stops the thread while the kernel maps \
the page in, and a major one waits for I/O too (not measured here). Fix: touch \
and lock its memory before the loop (`mlockall(MCL_CURRENT | MCL_FUTURE)`, every \
buffer written once), and keep the kernel from moving its pages: T3 (THP), T5 \
(NUMA balancing), T14 (compaction), T17 (KSM)",
self.role.name(),
self.path,
d.minor,
d.major,
before.minor,
now.minor,
before.major,
now.major
),
))
}
}