ironmonitor 7.1.0

IronMonitor: hardware monitoring for CPUs, GPUs, NPUs, memory, I/O and network silicon on Linux, Windows and macOS, which reports what it cannot read as well as what it can
Documentation
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (c) 2024 NervoSys

//! NVMe Identify Controller and SMART/Health log retrieval on Windows.
//!
//! `IOCTL_STORAGE_QUERY_PROPERTY` with `StorageDeviceProtocolSpecificProperty`
//! asks the storage driver to issue an NVMe admin command and hand back the raw
//! structure, which [`super::nvme_log`] then parses.
//!
//! **This needs no elevation**, which is worth stating plainly because the
//! documentation for 3.0.0 assumed the opposite and left every one of these fields
//! `None`. The handle must be opened with a desired access of *zero*; that is now
//! [`super::windows_device::Device`]'s job, and its comment explains why.
//!
//! Verified against four physical drives: three NVMe (Samsung 9100 PRO, 990 PRO,
//! 970 EVO Plus) and one USB enclosure, unelevated.

use super::nvme_log::{HealthLog, IdentifyController};
use super::traits::Error;
use super::windows_device::Device;
use windows::Win32::Foundation::ERROR_INVALID_PARAMETER;
use windows::Win32::System::Ioctl::{
    NVMeDataTypeFeature, NVMeDataTypeIdentify, NVMeDataTypeLogPage, PropertyStandardQuery,
    ProtocolTypeNvme, StorageDeviceProtocolSpecificProperty, IOCTL_STORAGE_QUERY_PROPERTY,
    STORAGE_PROPERTY_QUERY, STORAGE_PROTOCOL_DATA_DESCRIPTOR, STORAGE_PROTOCOL_SPECIFIC_DATA,
};
use windows::Win32::System::IO::DeviceIoControl;

/// NVMe SMART/Health Information log page identifier.
const NVME_LOG_PAGE_HEALTH: u32 = 0x02;
/// Identify Controller data structure (CNS 0x01).
const NVME_IDENTIFY_CNS_CONTROLLER: u32 = 0x01;
/// Get Features feature identifier for Power Management.
const NVME_FEATURE_POWER_MANAGEMENT: u32 = 0x02;
/// The health log page is 512 bytes; Identify structures are 4096.
const HEALTH_LOG_LEN: usize = 512;
const IDENTIFY_LEN: usize = 4096;

/// What the controller answered. Either half can be absent: a drive may serve
/// Identify while refusing the log page, and the caller still wants the identity.
pub(crate) struct NvmeData {
    pub identify: Option<IdentifyController>,
    pub health: Option<HealthLog>,
    /// Current power state, from Get Features. `None` when the controller did not
    /// answer — a state of 0 is a real, and common, reading.
    pub power_state: Option<u8>,
}

impl Device {
    /// What one protocol-specific query returned.
    ///
    /// Log pages and Identify answer in `data`. Get Features answers in `fixed`,
    /// which carries completion queue entry dword 0 — there is no payload to read,
    /// so a caller that only looked at `data` would find it empty and conclude the
    /// command had failed.
    fn query(
        &self,
        data_type: i32,
        request_value: u32,
        data_len: usize,
    ) -> Result<ProtocolReply, Error> {
        let header = std::mem::size_of::<STORAGE_PROPERTY_QUERY>()
            + std::mem::size_of::<STORAGE_PROTOCOL_SPECIFIC_DATA>();
        let mut buf = vec![0u8; header + data_len];

        unsafe {
            let query = buf.as_mut_ptr() as *mut STORAGE_PROPERTY_QUERY;
            (*query).PropertyId = StorageDeviceProtocolSpecificProperty;
            (*query).QueryType = PropertyStandardQuery;

            let protocol = std::ptr::addr_of_mut!((*query).AdditionalParameters)
                as *mut STORAGE_PROTOCOL_SPECIFIC_DATA;
            (*protocol).ProtocolType = ProtocolTypeNvme;
            (*protocol).DataType = data_type as u32;
            (*protocol).ProtocolDataRequestValue = request_value;
            (*protocol).ProtocolDataRequestSubValue = 0;
            (*protocol).ProtocolDataOffset =
                std::mem::size_of::<STORAGE_PROTOCOL_SPECIFIC_DATA>() as u32;
            (*protocol).ProtocolDataLength = data_len as u32;

            let mut returned = 0u32;
            DeviceIoControl(
                self.0,
                IOCTL_STORAGE_QUERY_PROPERTY,
                Some(buf.as_ptr() as *const _),
                buf.len() as u32,
                Some(buf.as_mut_ptr() as *mut _),
                buf.len() as u32,
                Some(&mut returned),
                None,
            )
            .map_err(|e| {
                // A non-NVMe device — a USB enclosure, a SATA disk — rejects the
                // NVMe protocol type with ERROR_INVALID_PARAMETER. That is the
                // device answering "not me", not a failure to ask properly.
                if e.code() == ERROR_INVALID_PARAMETER.to_hresult() {
                    Error::NotSupported
                } else {
                    Error::QueryFailed(format!("NVMe query: {e}"))
                }
            })?;

            // The payload is at ProtocolDataOffset *from the embedded
            // ProtocolSpecificData*, not from the buffer start and not at the
            // offset the request used — those differ by four bytes here. Reading
            // from the wrong one yields shifted-but-plausible data rather than an
            // error: model strings come back missing their first characters.
            let descriptor = buf.as_ptr() as *const STORAGE_PROTOCOL_DATA_DESCRIPTOR;
            let embedded = std::ptr::addr_of!((*descriptor).ProtocolSpecificData) as usize
                - buf.as_ptr() as usize;
            let offset = (*descriptor).ProtocolSpecificData.ProtocolDataOffset as usize;
            let length = (*descriptor).ProtocolSpecificData.ProtocolDataLength as usize;

            let fixed = (*descriptor).ProtocolSpecificData.FixedProtocolReturnData;

            let start = embedded.saturating_add(offset);
            let end = start.saturating_add(length);

            // A Get Features reply carries no payload, so an empty or
            // out-of-bounds range is not an error for it — `fixed` is the answer.
            let data = if length == 0 || end > buf.len() {
                Vec::new()
            } else {
                buf[start..end].to_vec()
            };

            Ok(ProtocolReply { data, fixed })
        }
    }

    /// Issue Get Features and return completion dword 0.
    fn feature(&self, feature_id: u32) -> Result<u32, Error> {
        self.query(NVMeDataTypeFeature.0, feature_id, IDENTIFY_LEN)
            .map(|reply| reply.fixed)
    }
}

/// The two ways a protocol query can answer.
struct ProtocolReply {
    data: Vec<u8>,
    fixed: u32,
}

/// Read Identify Controller and the SMART/Health log for a physical drive.
///
/// Returns [`Error::NotSupported`] when the device is not NVMe. Either half of the
/// result may be `None` if the controller served one structure but not the other.
pub(crate) fn query(index: u32) -> Result<NvmeData, Error> {
    let device = Device::open(index)?;

    let identify = device.query(
        NVMeDataTypeIdentify.0,
        NVME_IDENTIFY_CNS_CONTROLLER,
        IDENTIFY_LEN,
    );

    // If Identify says "not NVMe", so will everything else — report that rather
    // than a half-empty result the caller has to interpret.
    if matches!(identify, Err(Error::NotSupported)) {
        return Err(Error::NotSupported);
    }

    let health = device.query(NVMeDataTypeLogPage.0, NVME_LOG_PAGE_HEALTH, HEALTH_LOG_LEN);

    // Power state is bits 4:0 of completion dword 0. Get Features is optional for
    // a controller to implement, so a failure here is not a failure of the query
    // as a whole.
    let power_state = device
        .feature(NVME_FEATURE_POWER_MANAGEMENT)
        .ok()
        .map(|cdw0| (cdw0 & 0x1F) as u8);

    Ok(NvmeData {
        identify: identify
            .ok()
            .and_then(|r| IdentifyController::parse(&r.data)),
        health: health.ok().and_then(|r| HealthLog::parse(&r.data)),
        power_state,
    })
}