use std::fs;
use std::path::Path;
const SYSFS_DIR: &str = "/sys/kernel/sched_ext";
pub struct KernelState {
pub state: String,
pub ops: Option<String>,
}
impl KernelState {
pub fn enabled(&self) -> bool {
self.state == "enabled"
}
pub fn matches(&self, loader_name: &str) -> bool {
let stripped = loader_name.strip_prefix("scx_").unwrap_or(loader_name);
self.ops.as_deref().is_some_and(|ops| {
ops == loader_name
|| ops == stripped
|| ops
.strip_prefix(stripped)
.is_some_and(|rest| rest.starts_with('_'))
})
}
}
pub fn read() -> Option<KernelState> {
let dir = Path::new(SYSFS_DIR);
if !dir.is_dir() {
return None;
}
let state = fs::read_to_string(dir.join("state"))
.ok()?
.trim()
.to_owned();
let ops = fs::read_to_string(dir.join("root/ops"))
.ok()
.map(|s| s.trim().to_owned())
.filter(|s| !s.is_empty());
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 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"));
}
}