1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
//! Linux disk monitoring via sysfs, ioctl, and procfs
use crate::disk::traits::*;
use std::fs;
use std::path::{Path, PathBuf};
/// Linux disk device implementation
pub struct LinuxDisk {
name: String,
device_path: PathBuf,
disk_type: DiskType,
}
impl LinuxDisk {
/// Create a new Linux disk device
pub fn new(name: String) -> Result<Self, Error> {
let device_path = PathBuf::from(format!("/dev/{}", name));
// Confirm the device exists before describing it. This used to also parse
// the major:minor pair into two fields that nothing ever read, and it
// indexed `parts[1]` directly — a panic on any `dev` file without a colon,
// reached through a `.unwrap_or(0)` that looked like it was handling the
// error. The existence check is the part that was doing work.
let dev_path = format!("/sys/block/{}/dev", name);
fs::read_to_string(&dev_path)
.map_err(|e| Error::QueryFailed(format!("Failed to read {}: {}", dev_path, e)))?;
// Determine disk type
let disk_type = Self::detect_disk_type(&name)?;
Ok(Self {
name,
device_path,
disk_type,
})
}
fn detect_disk_type(name: &str) -> Result<DiskType, Error> {
// NVMe devices: nvme*
if name.starts_with("nvme") {
return Ok(DiskType::NvmeSsd);
}
// A USB stick reports `rotational` 0 like an SSD, and used to be typed as
// a SATA SSD. The bus is in the device's own sysfs path.
match Self::is_usb(name) {
Some(true) => return Ok(DiskType::Usb),
Some(false) => {}
// The path is what says which bus this is. Without it, the type is
// not known, and a flag cannot stand in for the bus.
None => return Ok(DiskType::Unknown),
}
// Check if it's a rotational device (HDD). An unreadable flag is not a
// solid-state drive: the `sd*` fallback that used to return SataSsd here
// is gone, and an unread flag is Unknown.
let rotational_path = format!("/sys/block/{}/queue/rotational", name);
match fs::read_to_string(&rotational_path)
.as_deref()
.map(str::trim)
{
Ok("1") => Ok(DiskType::SataHdd),
Ok("0") => Ok(DiskType::SataSsd),
_ => Ok(DiskType::Unknown),
}
}
/// Whether the kernel places this block device under the USB bus. `/sys/block/<name>`
/// is a link into the device tree, and a USB device's resolved path runs
/// through a `usbN` controller. `None` where the link could not be resolved.
fn is_usb(name: &str) -> Option<bool> {
fs::canonicalize(format!("/sys/block/{name}"))
.ok()
.map(|path| path.to_string_lossy().contains("/usb"))
}
fn read_sysfs_string(&self, attribute: &str) -> Result<String, Error> {
let path = format!("/sys/block/{}/{}", self.name, attribute);
fs::read_to_string(&path)
.map(|s| s.trim().to_string())
.map_err(|e| Error::QueryFailed(format!("Failed to read {}: {}", path, e)))
}
fn read_sysfs_u64(&self, attribute: &str) -> Result<u64, Error> {
self.read_sysfs_string(attribute)?
.parse()
.map_err(|e| Error::ParseError(format!("Failed to parse {}: {}", attribute, e)))
}
}
/// The NVMe controller a namespace belongs to: `nvme0n1` is on `nvme0`.
///
/// `None` for anything that is not an `nvme<N>n<M>` name.
fn nvme_controller(name: &str) -> Option<&str> {
let digits = name.strip_prefix("nvme")?;
let n = digits.bytes().take_while(u8::is_ascii_digit).count();
(n > 0).then(|| &name[..4 + n])
}
impl LinuxDisk {
/// This drive's entry from the SMART collector, matched on device path.
///
/// One collector run spawns `smartctl` once per drive, so picking one entry
/// out of it used to cost a full sweep per call — quadratic over a machine,
/// and the worst case of the two platforms. It now reads a run shared across
/// every drive and every accessor,
/// [`crate::smart::SmartMonitor::cached_disks`].
///
/// NVMe namespaces (`nvme0n1`) match the collector's entry for their
/// controller (`/dev/nvme0`), which is the device `nvme smart-log` is run on.
/// Matching the namespace path found nothing, so no NVMe drive ever had
/// SMART data.
fn smart_disk(&self) -> Option<crate::smart::SmartDiskInfo> {
let wanted = match nvme_controller(&self.name) {
Some(controller) => format!("/dev/{controller}"),
None => format!("/dev/{}", self.name),
};
crate::smart::SmartMonitor::cached_disks()
.iter()
.find(|d| d.device == wanted)
.cloned()
}
}
impl DiskDevice for LinuxDisk {
fn name(&self) -> &str {
&self.name
}
fn disk_type(&self) -> DiskType {
self.disk_type
}
fn info(&self) -> Result<DiskInfo, Error> {
// Read model. Unread is `None`, not the string "Unknown", which a
// consumer would display as if the drive had said so.
let model = self.read_sysfs_string("device/model").ok();
// Read vendor
let vendor = self.read_sysfs_string("device/vendor").ok();
// Read firmware
let firmware = self.read_sysfs_string("device/rev").ok();
// Read capacity (in 512-byte sectors).
//
// `.ok()` rather than `?`: a drive whose `size` attribute cannot be read
// is still a drive, and reporting it with an unknown capacity says more
// than dropping it from the enumeration entirely.
let capacity = self
.read_sysfs_u64("size")
.ok()
.map(|sectors| sectors * 512);
// Read queue info
// sysfs carries both; defaulting to 512 asserted a non-4Kn drive.
let logical_block_size = self
.read_sysfs_u64("queue/logical_block_size")
.ok()
.map(|v| v as u32);
let physical_block_size = self
.read_sysfs_u64("queue/physical_block_size")
.ok()
.map(|v| v as u32);
// Not read. sysfs `queue/rotational` is a 0/1 flag, not a speed, and
// this used to pass the flag through as the RPM: every hard disk
// spun at 1 RPM. The nominal rate is in the ATA IDENTIFY data, which
// needs an ioctl this reader does not make.
let rotation_rate = None;
Ok(DiskInfo {
name: self.name.clone(),
model,
serial: None, // Would need ioctl or smartctl
firmware,
capacity,
block_size: logical_block_size,
disk_type: self.disk_type,
// An unknown type has no interface to name. This used to be the
// string "Unknown", which is not an interface.
interface_type: match self.disk_type {
DiskType::NvmeSsd => Some("NVMe (PCIe)".to_string()),
DiskType::SataSsd | DiskType::SataHdd => Some("SATA".to_string()),
DiskType::Usb => Some("USB".to_string()),
DiskType::Scsi => Some("SCSI".to_string()),
DiskType::Virtual => Some("Virtual".to_string()),
DiskType::Unknown => None,
},
physical_sector_size: physical_block_size,
logical_sector_size: logical_block_size,
rotation_rate,
vendor,
})
}
fn io_stats(&self) -> Result<DiskIoStats, Error> {
let stat_path = format!("/sys/block/{}/stat", self.name);
let stat_content = fs::read_to_string(&stat_path)
.map_err(|e| Error::QueryFailed(format!("Failed to read {}: {}", stat_path, e)))?;
// Format: read_ios read_merges read_sectors read_ticks write_ios write_merges write_sectors write_ticks in_flight io_ticks time_in_queue
let parts: Vec<&str> = stat_content.split_whitespace().collect();
if parts.len() < 11 {
return Err(Error::ParseError("Invalid stat format".to_string()));
}
// `.ok()` rather than `.unwrap_or(0)`: a field of this line that does not
// parse is a field this kernel did not give us, and a counter of zero is
// a claim the device has served no I/O since boot. Those are different
// facts, and a consumer differentiating two samples cannot tell them
// apart once the second is written as the first.
let read_ops: Option<u64> = parts[0].parse().ok();
let read_sectors: Option<u64> = parts[2].parse().ok();
let read_time_ms: Option<u64> = parts[3].parse().ok();
let write_ops: Option<u64> = parts[4].parse().ok();
let write_sectors: Option<u64> = parts[6].parse().ok();
let write_time_ms: Option<u64> = parts[7].parse().ok();
let in_flight: Option<u32> = parts[8].parse().ok();
Ok(DiskIoStats {
read_bytes: read_sectors.map(|s| s * 512),
write_bytes: write_sectors.map(|s| s * 512),
read_ops,
write_ops,
read_time_ms,
write_time_ms,
queue_depth: in_flight,
avg_latency_us: None, // Would need to calculate from deltas
read_throughput: None, // Would need historical data
write_throughput: None,
})
}
fn temperature(&self) -> Result<Option<f32>, Error> {
// For NVMe devices, check hwmon
if self.disk_type == DiskType::NvmeSsd {
let hwmon_path = format!("/sys/block/{}/device/hwmon", self.name);
if let Ok(entries) = fs::read_dir(&hwmon_path) {
for entry in entries.flatten() {
let temp_path = entry.path().join("temp1_input");
if let Ok(temp_str) = fs::read_to_string(&temp_path) {
if let Ok(temp_millicelsius) = temp_str.trim().parse::<i32>() {
return Ok(Some(temp_millicelsius as f32 / 1000.0));
}
}
}
}
}
Ok(None)
}
fn health(&self) -> Result<DiskHealth, Error> {
// The device file existing says the kernel enumerated it, not that the
// drive is well. This is the drive's own SMART overall-health verdict
// (PASSED or FAILED) and nothing else. `SmartDiskInfo::health` is a score
// the collector computes from counters, and it used to be published here
// as a measured health value. Where the verdict was not read, this is
// Unknown, not Healthy.
match self.smart_disk().and_then(|disk| disk.smart_passed) {
Some(true) => Ok(DiskHealth::Healthy),
Some(false) => Ok(DiskHealth::Failed),
None => Ok(DiskHealth::Unknown),
}
}
fn smart_info(&self) -> Result<SmartInfo, Error> {
let Some(disk) = self.smart_disk() else {
return Err(Error::QueryFailed(format!(
"no SMART data for {}; `smartctl` or `nvme` may not be installed",
self.name
)));
};
Ok(SmartInfo {
// The drive's own verdict from `smartctl -H`, when that run printed
// one. The NVMe critical-warning byte is not this verdict.
passed: disk.smart_passed,
attributes: disk
.attributes
.iter()
.map(|a| SmartAttribute {
id: a.id.min(u8::MAX as u16) as u8,
name: a.name.clone(),
value: a.value.min(u8::MAX as u64) as u8,
worst: a.worst.min(u8::MAX as u64) as u8,
threshold: a.threshold.map(|t| t.min(u8::MAX as u64) as u8),
raw_value: a.raw_value,
critical: a.pre_fail,
})
.collect(),
temperature: disk.temperature_celsius.map(|t| t as f32),
power_on_hours: disk.power_on_hours,
power_cycle_count: disk.power_cycle_count,
reallocated_sectors: disk.reallocated_sectors,
pending_sectors: disk.pending_sectors,
uncorrectable_sectors: disk.uncorrectable_errors,
// `smartctl`/`nvme` output, parsed by the SMART collector -- the
// drive answered, but this reader did not ask it directly.
source: SmartSource::StorageStack,
})
}
fn nvme_info(&self) -> Result<NvmeInfo, Error> {
// Namespaces are named `nvme0n1`; the controller they belong to is
// `nvme0`, and that is what sysfs keys on. This used to split on every
// `n`, which takes `nvme0n1` to "" and returned NotSupported for every
// NVMe drive.
let Some(controller) = nvme_controller(&self.name) else {
return Err(Error::NotSupported);
};
let base = PathBuf::from("/sys/class/nvme").join(controller);
if !base.exists() {
return Err(Error::NotSupported);
}
let attr = |name: &str| {
fs::read_to_string(base.join(name))
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
};
// sysfs exposes identity, the controller id and the namespace list without
// root — more than Windows gives unelevated. The SMART/Health log page
// (temperature, wear, data units) still needs the admin ioctl, so those
// come from the SMART collector when `nvme` is installed, and stay None
// otherwise rather than becoming zero.
let smart = self.smart_disk();
let namespaces = fs::read_dir(&base).ok().map(|entries| {
entries
.flatten()
.filter(|e| {
e.file_name()
.to_string_lossy()
.starts_with(&format!("{controller}n"))
})
.count() as u32
});
Ok(NvmeInfo {
model: attr("model").unwrap_or_default(),
serial: attr("serial").unwrap_or_default(),
firmware: attr("firmware_rev").unwrap_or_default(),
nvme_version: attr("nvme_version"),
// Not read here. The sysfs `size` on this device is the namespace size, not
// the controller's total NVM capacity (Identify Controller TNVMCAP), which
// sysfs does not expose and this path has no admin command to fetch. This
// used to report the namespace size, multiplied by 512, as total capacity.
total_capacity: None,
unallocated_capacity: None,
controller_id: attr("cntlid").and_then(|v| v.parse().ok()),
num_namespaces: namespaces,
temperature_sensors: smart
.as_ref()
.and_then(|d| d.temperature_celsius)
.map(|t| vec![t as f32])
.unwrap_or_default(),
power_state: None,
available_power_states: Vec::new(),
percentage_used: smart.as_ref().and_then(|d| d.nvme_percentage_used),
// Bytes into NVMe data units of 1000 x 512 bytes, the same unit as the
// Windows controller path. Dividing by 512 gave a count 1000 times too large.
data_units_read: smart
.as_ref()
.and_then(|d| d.total_bytes_read)
.map(|b| b / (crate::disk::nvme_log::BYTES_PER_DATA_UNIT as u64)),
data_units_written: smart
.as_ref()
.and_then(|d| d.total_bytes_written)
.map(|b| b / (crate::disk::nvme_log::BYTES_PER_DATA_UNIT as u64)),
// The same `nvme smart-log` run as the wear and temperature fields
// above, parsed by the SMART collector. Absent keys stay None.
host_read_commands: smart.as_ref().and_then(|d| d.nvme_host_read_commands),
host_write_commands: smart.as_ref().and_then(|d| d.nvme_host_write_commands),
critical_warnings: smart.as_ref().and_then(|d| d.nvme_critical_warning),
available_spare: smart.as_ref().and_then(|d| d.nvme_available_spare),
available_spare_threshold: smart
.as_ref()
.and_then(|d| d.nvme_available_spare_threshold),
controller_busy_time_minutes: smart
.as_ref()
.and_then(|d| d.nvme_controller_busy_time_minutes),
unsafe_shutdowns: smart.as_ref().and_then(|d| d.nvme_unsafe_shutdowns),
})
}
fn device_path(&self) -> PathBuf {
self.device_path.clone()
}
fn filesystem_info(&self) -> Result<Vec<FilesystemInfo>, Error> {
let mut filesystems = Vec::new();
// Read /proc/mounts
let mounts = fs::read_to_string("/proc/mounts")
.map_err(|e| Error::QueryFailed(format!("Failed to read /proc/mounts: {}", e)))?;
for line in mounts.lines() {
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() < 4 {
continue;
}
let device = parts[0];
let mount_point = parts[1];
let fs_type = parts[2];
// Check if this mount is for our device or a partition
if device.contains(&self.name) || device == self.device_path.to_str().unwrap_or("") {
// Get filesystem stats using statvfs
if let Ok(stat) = nix::sys::statvfs::statvfs(mount_point) {
let total_size = stat.blocks() * stat.block_size();
let available_size = stat.blocks_available() * stat.block_size();
let free_size = stat.blocks_free() * stat.block_size();
let used_size = total_size - free_size;
// `statvfs` succeeded, so all three are readings. They are
// wrapped rather than optional-at-source because the
// Windows path cannot say the same.
filesystems.push(FilesystemInfo {
mount_point: PathBuf::from(mount_point),
fs_type: fs_type.to_string(),
total_size: Some(total_size),
used_size: Some(used_size),
available_size: Some(available_size),
total_inodes: Some(stat.files()),
used_inodes: Some(stat.files() - stat.files_free()),
read_only: Some(
stat.flags().contains(nix::sys::statvfs::FsFlags::ST_RDONLY),
),
});
}
}
}
Ok(filesystems)
}
}
/// Enumerate all block devices
pub fn enumerate() -> Result<Vec<Box<dyn DiskDevice>>, Error> {
let mut devices = Vec::new();
// Read /sys/block for all block devices
let sys_block = Path::new("/sys/block");
if !sys_block.exists() {
return Err(Error::NoDevicesFound);
}
for entry in fs::read_dir(sys_block)
.map_err(|e| Error::QueryFailed(format!("Failed to read /sys/block: {}", e)))?
{
let entry =
entry.map_err(|e| Error::QueryFailed(format!("Failed to read entry: {}", e)))?;
let name = entry.file_name().to_string_lossy().to_string();
// Skip loop devices, ram disks, etc.
if name.starts_with("loop") || name.starts_with("ram") || name.starts_with("dm-") {
continue;
}
// Create device
match LinuxDisk::new(name.clone()) {
Ok(disk) => devices.push(Box::new(disk) as Box<dyn DiskDevice>),
Err(e) => eprintln!("Warning: Failed to initialize disk {}: {}", name, e),
}
}
if devices.is_empty() {
return Err(Error::NoDevicesFound);
}
Ok(devices)
}
/// Get per-process I/O stats from /proc/[pid]/io
pub fn get_process_io(pid: u32) -> Result<ProcessDiskIo, Error> {
let io_path = format!("/proc/{}/io", pid);
let content = fs::read_to_string(&io_path)
.map_err(|e| Error::QueryFailed(format!("Failed to read {}: {}", io_path, e)))?;
let mut read_bytes = None;
let mut write_bytes = None;
let mut read_syscalls = None;
let mut write_syscalls = None;
let mut cancelled_write_bytes = None;
for line in content.lines() {
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() < 2 {
continue;
}
// A line that does not parse leaves its counter absent rather than
// zero, matching `cancelled_write_bytes`, which was already doing this
// by virtue of only existing when its line does.
let Ok(value) = parts[1].parse::<u64>() else {
continue;
};
match parts[0] {
"rchar:" => read_bytes = Some(value),
"wchar:" => write_bytes = Some(value),
"syscr:" => read_syscalls = Some(value),
"syscw:" => write_syscalls = Some(value),
"cancelled_write_bytes:" => cancelled_write_bytes = Some(value),
_ => {}
}
}
Ok(ProcessDiskIo {
pid,
read_bytes,
write_bytes,
read_syscalls,
write_syscalls,
cancelled_write_bytes,
})
}
#[cfg(test)]
mod tests {
use super::nvme_controller;
#[test]
fn a_namespace_is_on_its_controller() {
assert_eq!(nvme_controller("nvme0n1"), Some("nvme0"));
assert_eq!(nvme_controller("nvme12n3"), Some("nvme12"));
}
#[test]
fn names_that_are_not_nvme_namespaces_have_no_controller() {
assert_eq!(nvme_controller("sda"), None);
assert_eq!(nvme_controller("nvme"), None);
assert_eq!(nvme_controller("nvmeXn1"), None);
}
}