use super::ata_smart::{AtaSmartData, STRUCTURE_LEN};
use super::traits::Error;
use super::windows_device::Device;
use windows::Win32::Foundation::{ERROR_INVALID_FUNCTION, ERROR_INVALID_PARAMETER};
use windows::Win32::System::Ioctl::{IOCTL_STORAGE_PREDICT_FAILURE, STORAGE_PREDICT_FAILURE};
use windows::Win32::System::IO::DeviceIoControl;
pub(crate) struct AtaHealth {
pub predict_failure: Option<bool>,
pub smart: Option<AtaSmartData>,
}
pub(crate) fn query(index: u32) -> Result<AtaHealth, Error> {
let device = Device::open(index)?;
let mut out = STORAGE_PREDICT_FAILURE::default();
let mut returned = 0u32;
unsafe {
DeviceIoControl(
device.0,
IOCTL_STORAGE_PREDICT_FAILURE,
None,
0,
Some(&mut out as *mut _ as *mut _),
std::mem::size_of::<STORAGE_PREDICT_FAILURE>() as u32,
Some(&mut returned),
None,
)
}
.map_err(|e| {
let code = e.code();
if code == ERROR_INVALID_FUNCTION.to_hresult()
|| code == ERROR_INVALID_PARAMETER.to_hresult()
{
Error::NotSupported
} else {
Error::QueryFailed(format!("predict failure query on drive {index}: {e}"))
}
})?;
let (predict_failure, smart) = decode_reply(returned, out.PredictFailure, &out.VendorSpecific);
Ok(AtaHealth {
predict_failure,
smart,
})
}
fn decode_reply(
returned: u32,
predict_failure: u32,
vendor_specific: &[u8],
) -> (Option<bool>, Option<AtaSmartData>) {
let returned = returned as usize;
let verdict = (returned >= std::mem::size_of::<u32>()).then_some(predict_failure != 0);
let smart = if returned >= std::mem::size_of::<STORAGE_PREDICT_FAILURE>() {
vendor_specific
.get(..STRUCTURE_LEN)
.and_then(AtaSmartData::parse)
} else {
None
};
(verdict, smart)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_empty_reply_gives_no_verdict() {
let (verdict, smart) = decode_reply(0, 0, &[0u8; 512]);
assert_eq!(verdict, None);
assert!(smart.is_none());
}
#[test]
fn a_reply_too_short_for_the_verdict_gives_none() {
let (verdict, _) = decode_reply(3, 1, &[0u8; 512]);
assert_eq!(verdict, None);
}
#[test]
fn a_prediction_without_the_structure_is_still_a_reading() {
let (verdict, smart) = decode_reply(4, 0, &[0u8; 512]);
assert_eq!(verdict, Some(false));
assert!(smart.is_none(), "the 512 bytes were not written");
let (verdict, _) = decode_reply(4, 1, &[0u8; 512]);
assert_eq!(verdict, Some(true));
}
#[test]
fn a_full_reply_with_a_failure_prediction_is_read() {
let (verdict, _) = decode_reply(
std::mem::size_of::<STORAGE_PREDICT_FAILURE>() as u32,
0x40,
&[0u8; 512],
);
assert_eq!(verdict, Some(true));
}
}