use std::fs;
use std::path::Path;
use anyhow::{Context, Result};
const SYSFS_DIR: &str = "/sys/kernel/sched_ext";
#[derive(Debug, Clone, PartialEq)]
pub struct KernelState {
pub state: String,
pub ops: Option<String>,
}
impl KernelState {
pub fn enabled(&self) -> bool {
self.state == "enabled"
}
pub fn matches(&self, sched_name: &str) -> bool {
let stripped = sched_name.strip_prefix("scx_").unwrap_or(sched_name);
self.ops.as_deref().is_some_and(|ops| {
ops == sched_name
|| ops == stripped
|| ops
.strip_prefix(sched_name)
.is_some_and(|rest| rest.starts_with('_'))
|| ops
.strip_prefix(stripped)
.is_some_and(|rest| rest.starts_with('_'))
})
}
}
pub fn read() -> Result<Option<KernelState>> {
let dir = Path::new(SYSFS_DIR);
if !dir.is_dir() {
return Ok(None);
}
let state = fs::read_to_string(dir.join("state"))
.with_context(|| format!("cannot read {}/state", dir.display()))?
.trim()
.to_owned();
let ops = match fs::read_to_string(dir.join("root/ops")) {
Ok(s) => Some(s.trim().to_owned()).filter(|s| !s.is_empty()),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => None,
Err(err) => {
return Err(err).with_context(|| format!("cannot read {}/root/ops", dir.display()));
}
};
Ok(Some(KernelState { state, ops }))
}
#[cfg(test)]
mod tests {
use super::*;
fn enabled_with(ops: Option<&str>) -> KernelState {
KernelState {
state: "enabled".to_owned(),
ops: ops.map(str::to_owned),
}
}
#[test]
fn matches_stripped_ops_name() {
assert!(enabled_with(Some("lavd")).matches("scx_lavd"));
}
#[test]
fn matches_full_ops_name() {
assert!(enabled_with(Some("scx_lavd")).matches("scx_lavd"));
}
#[test]
fn matches_versioned_ops_suffix() {
assert!(
enabled_with(Some("bpfland_1.1.2_x86_64_unknown_linux_gnu")).matches("scx_bpfland")
);
}
#[test]
fn matches_versioned_ops_suffix_with_prefix() {
assert!(enabled_with(Some("scx_flow_3.1.1_x86_64_unknown_linux_gnu")).matches("scx_flow"));
}
#[test]
fn rejects_full_name_prefix_without_separator() {
assert!(!enabled_with(Some("scx_flowmatic_1.0")).matches("scx_flow"));
}
#[test]
fn rejects_a_different_scheduler() {
assert!(!enabled_with(Some("flow_1.0")).matches("scx_flash"));
}
#[test]
fn rejects_prefix_without_separator() {
assert!(!enabled_with(Some("bpflandish")).matches("scx_bpfland"));
}
#[test]
fn no_ops_never_matches() {
assert!(!enabled_with(None).matches("scx_lavd"));
}
}