use crate::error::IronError;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum IoSchedulerType {
MqDeadline,
Bfq,
Kyber,
None,
Cfq,
Deadline,
Noop,
Unknown,
}
impl std::fmt::Display for IoSchedulerType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::MqDeadline => write!(f, "mq-deadline"),
Self::Bfq => write!(f, "bfq"),
Self::Kyber => write!(f, "kyber"),
Self::None => write!(f, "none"),
Self::Cfq => write!(f, "cfq"),
Self::Deadline => write!(f, "deadline"),
Self::Noop => write!(f, "noop"),
Self::Unknown => write!(f, "unknown"),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct IoStats {
pub reads_completed: Option<u64>,
pub reads_merged: Option<u64>,
pub sectors_read: Option<u64>,
pub read_time_ms: Option<u64>,
pub writes_completed: Option<u64>,
pub writes_merged: Option<u64>,
pub sectors_written: Option<u64>,
pub write_time_ms: Option<u64>,
pub in_flight: Option<u64>,
pub io_time_ms: Option<u64>,
pub weighted_io_time_ms: Option<u64>,
pub discards_completed: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BlockDeviceIo {
pub name: String,
pub scheduler: Option<IoSchedulerType>,
pub available_schedulers: Option<Vec<IoSchedulerType>>,
pub rotational: Option<bool>,
pub queue_depth: Option<u32>,
pub logical_block_size: Option<u32>,
pub physical_block_size: Option<u32>,
pub discard_support: Option<bool>,
pub stats: IoStats,
pub size_bytes: Option<u64>,
pub model: Option<String>,
}
impl BlockDeviceIo {
pub fn read_iops_from_stats(&self) -> Option<f64> {
let (reads, time_ms) = (self.stats.reads_completed?, self.stats.read_time_ms?);
if time_ms == 0 {
return None;
}
Some(reads as f64 / (time_ms as f64 / 1000.0))
}
pub fn write_iops_from_stats(&self) -> Option<f64> {
let (writes, time_ms) = (self.stats.writes_completed?, self.stats.write_time_ms?);
if time_ms == 0 {
return None;
}
Some(writes as f64 / (time_ms as f64 / 1000.0))
}
pub fn read_throughput_mbs(&self) -> Option<f64> {
let (sectors, time_ms) = (self.stats.sectors_read?, self.stats.read_time_ms?);
if time_ms == 0 {
return None;
}
Some((sectors as f64 * 512.0) / (time_ms as f64 / 1000.0) / 1_000_000.0)
}
pub fn scheduler_optimal(&self) -> Option<bool> {
let scheduler = self.scheduler?;
let optimal = if self.rotational? {
matches!(
scheduler,
IoSchedulerType::Bfq | IoSchedulerType::MqDeadline
)
} else {
matches!(
scheduler,
IoSchedulerType::None | IoSchedulerType::MqDeadline | IoSchedulerType::Kyber
)
};
Some(optimal)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IoSchedulerOverview {
pub devices: Vec<BlockDeviceIo>,
pub total_devices: u32,
pub non_optimal_count: u32,
pub recommendations: Vec<String>,
}
pub struct IoSchedulerMonitor {
overview: IoSchedulerOverview,
}
impl IoSchedulerMonitor {
pub fn new() -> Result<Self, IronError> {
let overview = Self::scan()?;
Ok(Self { overview })
}
pub fn refresh(&mut self) -> Result<(), IronError> {
self.overview = Self::scan()?;
Ok(())
}
pub fn overview(&self) -> &IoSchedulerOverview {
&self.overview
}
pub fn devices(&self) -> &[BlockDeviceIo] {
&self.overview.devices
}
pub fn device(&self, name: &str) -> Option<&BlockDeviceIo> {
self.overview.devices.iter().find(|d| d.name == name)
}
#[cfg(target_os = "linux")]
fn scan() -> Result<IoSchedulerOverview, IronError> {
let block_path = std::path::Path::new("/sys/block");
let mut devices = Vec::new();
if !block_path.exists() {
return Err(IronError::UnsupportedPlatform(
"`/sys/block` is not present, so block devices cannot be enumerated here".into(),
));
}
let entries = std::fs::read_dir(block_path).map_err(IronError::Io)?;
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
if name.starts_with("loop") || name.starts_with("ram") || name.starts_with("dm-") {
continue;
}
let dev_path = entry.path();
let queue_path = dev_path.join("queue");
if !queue_path.exists() {
continue;
}
let (scheduler, available) = Self::read_scheduler(&queue_path);
let rotational = Self::read_sysfs_u32(&queue_path.join("rotational")).map(|v| v == 1);
let queue_depth = Self::read_sysfs_u32(&queue_path.join("nr_requests"));
let logical_block_size = Self::read_sysfs_u32(&queue_path.join("logical_block_size"));
let physical_block_size = Self::read_sysfs_u32(&queue_path.join("physical_block_size"));
let discard_support =
Self::read_sysfs_u32(&queue_path.join("discard_max_bytes")).map(|v| v > 0);
let stats = Self::read_stats(&dev_path);
let size_bytes = Self::read_sysfs_u64(&dev_path.join("size")).map(|s| s * 512);
let model = std::fs::read_to_string(dev_path.join("device/model"))
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
devices.push(BlockDeviceIo {
name,
scheduler,
available_schedulers: available,
rotational,
queue_depth,
logical_block_size,
physical_block_size,
discard_support,
stats,
size_bytes,
model,
});
}
let total = devices.len() as u32;
let non_optimal = devices
.iter()
.filter(|d| d.scheduler_optimal() == Some(false))
.count() as u32;
let mut recommendations = Vec::new();
for dev in &devices {
if let (Some(false), Some(current)) = (dev.scheduler_optimal(), dev.scheduler) {
let rotational = dev.rotational == Some(true);
let suggested = if rotational { "bfq" } else { "none" };
recommendations.push(format!(
"{}: using '{}' scheduler; '{}' may be better for {} devices",
dev.name,
current,
suggested,
if rotational { "rotational" } else { "SSD/NVMe" }
));
}
}
Ok(IoSchedulerOverview {
devices,
total_devices: total,
non_optimal_count: non_optimal,
recommendations,
})
}
#[cfg(target_os = "linux")]
fn read_scheduler(
queue_path: &std::path::Path,
) -> (Option<IoSchedulerType>, Option<Vec<IoSchedulerType>>) {
let Ok(content) = std::fs::read_to_string(queue_path.join("scheduler")) else {
return (None, None);
};
let mut active = IoSchedulerType::Unknown;
let mut available = Vec::new();
for part in content.split_whitespace() {
let (name, is_active) = if part.starts_with('[') && part.ends_with(']') {
(part.trim_matches(|c| c == '[' || c == ']'), true)
} else {
(part, false)
};
let sched = match name {
"mq-deadline" => IoSchedulerType::MqDeadline,
"bfq" => IoSchedulerType::Bfq,
"kyber" => IoSchedulerType::Kyber,
"none" => IoSchedulerType::None,
"cfq" => IoSchedulerType::Cfq,
"deadline" => IoSchedulerType::Deadline,
"noop" => IoSchedulerType::Noop,
_ => IoSchedulerType::Unknown,
};
available.push(sched);
if is_active {
active = sched;
}
}
(Some(active), Some(available))
}
#[cfg(target_os = "linux")]
fn read_stats(dev_path: &std::path::Path) -> IoStats {
let Ok(content) = std::fs::read_to_string(dev_path.join("stat")) else {
return IoStats::default();
};
let parts: Vec<u64> = content
.split_whitespace()
.filter_map(|s| s.parse().ok())
.collect();
IoStats {
reads_completed: parts.first().copied(),
reads_merged: parts.get(1).copied(),
sectors_read: parts.get(2).copied(),
read_time_ms: parts.get(3).copied(),
writes_completed: parts.get(4).copied(),
writes_merged: parts.get(5).copied(),
sectors_written: parts.get(6).copied(),
write_time_ms: parts.get(7).copied(),
in_flight: parts.get(8).copied(),
io_time_ms: parts.get(9).copied(),
weighted_io_time_ms: parts.get(10).copied(),
discards_completed: parts.get(11).copied(),
}
}
#[cfg(target_os = "linux")]
fn read_sysfs_u32(path: &std::path::Path) -> Option<u32> {
std::fs::read_to_string(path)
.ok()
.and_then(|s| s.trim().parse().ok())
}
#[cfg(target_os = "linux")]
fn read_sysfs_u64(path: &std::path::Path) -> Option<u64> {
std::fs::read_to_string(path)
.ok()
.and_then(|s| s.trim().parse().ok())
}
#[cfg(target_os = "windows")]
fn scan() -> Result<IoSchedulerOverview, IronError> {
Err(IronError::UnsupportedPlatform(
"the block I/O scheduler is read from `/sys/block/*/queue/scheduler`, which Windows does not expose"
.into(),
))
}
#[cfg(target_os = "macos")]
fn scan() -> Result<IoSchedulerOverview, IronError> {
Err(IronError::UnsupportedPlatform(
"the block I/O scheduler is read from `/sys/block/*/queue/scheduler`, which macOS does not expose"
.into(),
))
}
#[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
fn scan() -> Result<IoSchedulerOverview, IronError> {
Err(IronError::UnsupportedPlatform(
"the block I/O scheduler is read from `/sys/block/*/queue/scheduler`, which this platform does not expose"
.into(),
))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_scheduler_display() {
assert_eq!(IoSchedulerType::MqDeadline.to_string(), "mq-deadline");
assert_eq!(IoSchedulerType::Bfq.to_string(), "bfq");
assert_eq!(IoSchedulerType::None.to_string(), "none");
}
#[test]
fn test_optimal_ssd() {
let dev = BlockDeviceIo {
name: "nvme0n1".into(),
scheduler: Some(IoSchedulerType::None),
available_schedulers: Some(vec![IoSchedulerType::None, IoSchedulerType::MqDeadline]),
rotational: Some(false),
queue_depth: Some(256),
logical_block_size: Some(512),
physical_block_size: Some(4096),
discard_support: Some(true),
stats: IoStats {
reads_completed: Some(0),
reads_merged: Some(0),
sectors_read: Some(0),
read_time_ms: Some(0),
writes_completed: Some(0),
writes_merged: Some(0),
sectors_written: Some(0),
write_time_ms: Some(0),
in_flight: Some(0),
io_time_ms: Some(0),
weighted_io_time_ms: Some(0),
discards_completed: Some(0),
},
size_bytes: Some(1_000_000_000_000),
model: Some("Samsung 990 Pro".into()),
};
assert_eq!(dev.scheduler_optimal(), Some(true));
}
#[test]
fn test_non_optimal_hdd() {
let dev = BlockDeviceIo {
name: "sda".into(),
scheduler: Some(IoSchedulerType::None),
available_schedulers: Some(vec![IoSchedulerType::None, IoSchedulerType::Bfq]),
rotational: Some(true),
queue_depth: Some(128),
logical_block_size: Some(512),
physical_block_size: Some(512),
discard_support: Some(false),
stats: IoStats {
reads_completed: Some(0),
reads_merged: Some(0),
sectors_read: Some(0),
read_time_ms: Some(0),
writes_completed: Some(0),
writes_merged: Some(0),
sectors_written: Some(0),
write_time_ms: Some(0),
in_flight: Some(0),
io_time_ms: Some(0),
weighted_io_time_ms: Some(0),
discards_completed: Some(0),
},
size_bytes: Some(2_000_000_000_000),
model: Some("WDC WD20EARS".into()),
};
assert_eq!(dev.scheduler_optimal(), Some(false));
}
#[test]
fn test_serialization() {
let stats = IoStats {
reads_completed: Some(1000),
reads_merged: Some(50),
sectors_read: Some(80000),
read_time_ms: Some(500),
writes_completed: Some(2000),
writes_merged: Some(100),
sectors_written: Some(160000),
write_time_ms: Some(800),
in_flight: Some(2),
io_time_ms: Some(1000),
weighted_io_time_ms: Some(1200),
discards_completed: Some(10),
};
let json = serde_json::to_string(&stats).unwrap();
assert!(json.contains("1000"));
let _: IoStats = serde_json::from_str(&json).unwrap();
}
#[test]
fn an_unread_rotational_flag_yields_no_verdict() {
let dev = BlockDeviceIo {
name: "sdz".into(),
scheduler: Some(IoSchedulerType::Bfq),
available_schedulers: Some(vec![IoSchedulerType::Bfq]),
rotational: None,
queue_depth: None,
logical_block_size: None,
physical_block_size: None,
discard_support: None,
stats: IoStats {
reads_completed: Some(0),
reads_merged: Some(0),
sectors_read: Some(0),
read_time_ms: Some(0),
writes_completed: Some(0),
writes_merged: Some(0),
sectors_written: Some(0),
write_time_ms: Some(0),
in_flight: Some(0),
io_time_ms: Some(0),
weighted_io_time_ms: Some(0),
discards_completed: Some(0),
},
size_bytes: Some(0),
model: None,
};
assert_eq!(dev.scheduler_optimal(), None);
}
#[cfg(target_os = "linux")]
#[test]
fn unread_scheduler_file_is_none_not_unknown() {
let dir = std::env::temp_dir().join(format!("ironmon-iosched-none-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let (active, available) = IoSchedulerMonitor::read_scheduler(&dir);
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(active, None);
assert_eq!(available, None);
}
#[cfg(target_os = "linux")]
#[test]
fn read_scheduler_takes_active_from_brackets() {
let dir = std::env::temp_dir().join(format!("ironmon-iosched-ok-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("scheduler"), "[mq-deadline] kyber bfq none\n").unwrap();
let (active, available) = IoSchedulerMonitor::read_scheduler(&dir);
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(active, Some(IoSchedulerType::MqDeadline));
assert_eq!(
available,
Some(vec![
IoSchedulerType::MqDeadline,
IoSchedulerType::Kyber,
IoSchedulerType::Bfq,
IoSchedulerType::None,
])
);
}
#[cfg(not(target_os = "linux"))]
#[test]
fn scan_is_unsupported_off_linux() {
assert!(matches!(
IoSchedulerMonitor::new(),
Err(IronError::UnsupportedPlatform(_))
));
}
}