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
//! GPU monitoring and control

use crate::error::{IronError, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// GPU type identifier
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum GpuType {
    /// Integrated GPU (e.g., Jetson)
    Integrated,
    /// Discrete GPU (e.g., desktop)
    Discrete,
    /// Not read. The Windows path used to make every GPU it could not
    /// classify `Discrete`.
    Unknown,
}

/// GPU frequency information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GpuFrequency {
    /// Current frequency in MHz, or `None` where no clock was read.
    ///
    /// **All three of these were bare `u32`, and this struct undid the first
    /// fix this sweep ever made.** `gpu::GpuClocks::graphics` was made `Option`
    /// so that an unreadable clock could not read as 0 MHz; the Windows reader
    /// then built this struct with `di.clocks.graphics.or(..).unwrap_or(0)`,
    /// flattening it straight back. NVML's clock calls went through
    /// `.ok().unwrap_or(0)`, and two readers set `min: 0` beside a comment
    /// saying no minimum is reported -- the comment right, the field wrong.
    pub current: Option<u32>,
    /// Minimum frequency in MHz, or `None` where the source reports none.
    ///
    /// NVML and every Windows vendor adapter expose no minimum clock at all,
    /// so on those paths this is always `None`. Only the Linux iGPU devfreq
    /// path reads one.
    pub min: Option<u32>,
    /// Maximum frequency in MHz, or `None` where not read.
    pub max: Option<u32>,
    /// Frequency governor, or `None` where none was read. NVML and Windows
    /// adapters have no governor; the field used to hold the driver name.
    pub governor: Option<String>,
    /// GPC frequencies for Orin/Thor series (optional)
    pub gpc: Option<Vec<u32>>,
}

/// GPU status information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GpuStatus {
    /// GPU load percentage (0.0 - 100.0)
    /// Utilization percentage, or `None` where the device reports no
    /// utilization counter.
    ///
    /// A GPU at 0% and a GPU whose counter could not be read are the same
    /// number and different facts. This was `f32` and took whichever one the
    /// backend happened to produce.
    pub load: Option<f32>,
    /// Railgate status (Jetson only)
    pub railgate: Option<bool>,
    /// Raw TPC power-gating mask (Jetson only), as the driver exposes it.
    pub tpc_pg_mask: Option<u32>,
    /// 3D scaling enabled (Jetson only)
    pub scaling_3d: Option<bool>,
    /// Memory used in bytes
    pub memory_used: Option<u64>,
    /// Total memory in bytes
    pub memory_total: Option<u64>,
    /// Free memory in bytes
    pub memory_free: Option<u64>,
    /// Temperature in Celsius
    pub temperature: Option<f32>,
    /// Power draw in watts
    pub power_draw: Option<f32>,
    /// Power limit in watts
    pub power_limit: Option<f32>,
}

/// Complete GPU information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GpuInfo {
    /// GPU type
    pub gpu_type: GpuType,
    /// GPU status
    pub status: GpuStatus,
    /// Frequency information
    pub frequency: GpuFrequency,
    /// Power control method, or `None` where none was read. The value used to be
    /// the driver name ("nvml", "sysfs"), which names a source, not a method.
    pub power_control: Option<String>,
}

/// GPU statistics container
#[derive(Debug, Default)]
pub struct GpuStats {
    /// Map of GPU name to GPU information
    gpus: HashMap<String, GpuInfo>,
}

impl GpuStats {
    /// Create a new GPU stats instance
    pub fn new() -> Self {
        Self {
            gpus: HashMap::new(),
        }
    }

    /// Get all GPUs
    pub fn gpus(&self) -> &HashMap<String, GpuInfo> {
        &self.gpus
    }

    /// Get a specific GPU by name
    pub fn get_gpu(&self, name: &str) -> Option<&GpuInfo> {
        self.gpus.get(name)
    }

    /// Get mutable reference to GPUs
    pub fn gpus_mut(&mut self) -> &mut HashMap<String, GpuInfo> {
        &mut self.gpus
    }

    /// Set 3D scaling for a GPU (Jetson only)
    pub fn set_3d_scaling(&mut self, name: &str, enabled: bool) -> Result<()> {
        if !self.gpus.contains_key(name) {
            return Err(IronError::DeviceNotFound(format!(
                "GPU '{}' not found",
                name
            )));
        }

        #[cfg(target_os = "linux")]
        {
            use crate::platform::linux::jetson::set_gpu_3d_scaling;
            set_gpu_3d_scaling(name, enabled)
        }

        #[cfg(not(target_os = "linux"))]
        {
            let _ = enabled; // Suppress unused warning
            Err(IronError::UnsupportedPlatform(
                "3D scaling control only available on Linux Jetson devices".to_string(),
            ))
        }
    }

    /// Set railgate for a GPU (Jetson only)
    pub fn set_railgate(&mut self, name: &str, enabled: bool) -> Result<()> {
        if !self.gpus.contains_key(name) {
            return Err(IronError::DeviceNotFound(format!(
                "GPU '{}' not found",
                name
            )));
        }

        #[cfg(target_os = "linux")]
        {
            use crate::platform::linux::jetson::set_gpu_railgate;
            set_gpu_railgate(name, enabled)
        }

        #[cfg(not(target_os = "linux"))]
        {
            let _ = enabled; // Suppress unused warning
            Err(IronError::UnsupportedPlatform(
                "Railgate control only available on Linux Jetson devices".to_string(),
            ))
        }
    }
}