use std::mem::size_of;
use crate::DiskKind;
use crate::sys::utils::HandleWrapper;
use windows::Win32::Storage::FileSystem::{
BusType1394, BusTypeFileBackedVirtual, BusTypeMmc, BusTypeSd, BusTypeUsb,
};
use windows::Win32::System::IO::DeviceIoControl;
use windows::Win32::System::Ioctl::{
DEVICE_SEEK_PENALTY_DESCRIPTOR, DISK_PERFORMANCE, IOCTL_DISK_PERFORMANCE,
IOCTL_STORAGE_QUERY_PROPERTY, PropertyStandardQuery, STORAGE_DEVICE_DESCRIPTOR,
STORAGE_PROPERTY_QUERY, StorageDeviceProperty, StorageDeviceSeekPenaltyProperty,
};
pub(super) unsafe fn get_disk_kind(handle: &HandleWrapper) -> DiskKind {
let query = STORAGE_PROPERTY_QUERY {
PropertyId: StorageDeviceProperty,
QueryType: PropertyStandardQuery,
AdditionalParameters: [0],
};
let mut device_descriptor: STORAGE_DEVICE_DESCRIPTOR = unsafe { std::mem::zeroed() };
let mut dw_size = 0;
let ret = unsafe {
DeviceIoControl(
handle.0,
IOCTL_STORAGE_QUERY_PROPERTY,
Some(&query as *const STORAGE_PROPERTY_QUERY as *const _),
size_of::<STORAGE_PROPERTY_QUERY>() as _,
Some(&mut device_descriptor as *mut STORAGE_DEVICE_DESCRIPTOR as *mut _),
size_of::<STORAGE_DEVICE_DESCRIPTOR>() as _,
Some(&mut dw_size),
None,
)
.is_ok()
};
if ret {
#[allow(non_upper_case_globals)]
match device_descriptor.BusType {
BusTypeFileBackedVirtual => {
return DiskKind::DiskImage;
}
BusType1394 | BusTypeMmc | BusTypeSd | BusTypeUsb => {
return DiskKind::External;
}
_ => {}
}
}
let query = STORAGE_PROPERTY_QUERY {
PropertyId: StorageDeviceSeekPenaltyProperty,
QueryType: PropertyStandardQuery,
AdditionalParameters: [0],
};
let mut seek_penalty_descriptor: DEVICE_SEEK_PENALTY_DESCRIPTOR = unsafe { std::mem::zeroed() };
let mut dw_size = 0;
let ret = unsafe {
DeviceIoControl(
handle.0,
IOCTL_STORAGE_QUERY_PROPERTY,
Some(&query as *const STORAGE_PROPERTY_QUERY as *const _),
size_of::<STORAGE_PROPERTY_QUERY>() as _,
Some(&mut seek_penalty_descriptor as *mut DEVICE_SEEK_PENALTY_DESCRIPTOR as *mut _),
size_of::<DEVICE_SEEK_PENALTY_DESCRIPTOR>() as _,
Some(&mut dw_size),
None,
)
.is_ok()
};
if ret && dw_size == size_of::<DEVICE_SEEK_PENALTY_DESCRIPTOR>() as u32 {
#[allow(clippy::unnecessary_cast)]
let incurs_seek_penalty = seek_penalty_descriptor.IncursSeekPenalty as u8;
if incurs_seek_penalty != 0 {
DiskKind::HDD
} else {
DiskKind::SSD
}
} else {
DiskKind::Unknown(-1)
}
}
pub(super) fn get_disk_io(handle: HandleWrapper) -> Option<(u64, u64)> {
let mut disk_perf = DISK_PERFORMANCE::default();
let mut bytes_returned = 0;
unsafe {
DeviceIoControl(
handle.0,
IOCTL_DISK_PERFORMANCE,
None, 0,
Some(&mut disk_perf as *mut _ as _),
size_of::<DISK_PERFORMANCE>() as u32,
Some(&mut bytes_returned),
None,
)
}
.inspect_err(|_err| {
sinf_debug!(
"Error: DeviceIoControl(IOCTL_DISK_PERFORMANCE) = {:?}",
_err
);
})
.ok()?;
Some((
disk_perf.BytesRead.try_into().ok()?,
disk_perf.BytesWritten.try_into().ok()?,
))
}