sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use std::collections::HashMap;
use std::fs::read_dir;

use crate::{Gpu, PCI};

mod sysfs;

use self::sysfs::*;

pub(crate) struct GpusInner {
    pub(crate) gpus: Vec<Gpu>,
    nvm_lib: Option<self::nvidia::NvmlLib>,
    vulkan_lib: Option<self::vulkan::Vulkan>,
    // The key is the vendor ID.
    device_map: HashMap<u32, Devices>,
    filled_device_map: bool,
}

struct Devices {
    name: String,
    // One ID can map to multiple devices; these are ignored.
    devices: HashMap<u32, String>,
}

impl Devices {
    fn new(name: &str) -> Self {
        Self {
            name: name.to_owned(),
            devices: HashMap::new(),
        }
    }
}

pub(crate) struct GpuInner {
    total_memory: Option<u64>,
    used_memory: Option<u64>,
    usage: Option<f32>,
    model: Option<String>,
    vendor: String,
    pci: PCI,
    pub(crate) updated: bool,
}

impl GpuInner {
    fn new(pci: PCI, vendor: &str, model: Option<&String>) -> Self {
        Self {
            total_memory: None,
            used_memory: None,
            usage: None,
            model: model.cloned(),
            vendor: vendor.to_owned(),
            pci,
            updated: false,
        }
    }

    pub(crate) fn pci(&self) -> &PCI {
        &self.pci
    }
    pub(crate) fn vendor(&self) -> Option<&str> {
        Some(self.vendor.as_str())
    }
    pub(crate) fn model(&self) -> Option<&str> {
        self.model.as_deref()
    }
    pub(crate) fn usage(&self) -> Option<f32> {
        self.usage
    }
    pub(crate) fn total_memory(&self) -> Option<u64> {
        self.total_memory
    }
    pub(crate) fn used_memory(&self) -> Option<u64> {
        self.used_memory
    }
}

impl GpusInner {
    pub(crate) fn new() -> Result<Self, crate::Error> {
        Ok(Self {
            gpus: Vec::new(),
            nvm_lib: None,
            device_map: HashMap::new(),
            vulkan_lib: None,
            filled_device_map: false,
        })
    }

    /// Returns the vendor name and the vendor's known devices.
    fn get_vendor_and_devices(
        &self,
        vendor_id: u32,
    ) -> Option<(&str, Option<&HashMap<u32, String>>)> {
        match self.device_map.get(&vendor_id) {
            Some(devices) => Some((&devices.name, Some(&devices.devices))),
            None => crate::gpu::gpu_vendor_name(vendor_id).map(|vendor| (vendor, None)),
        }
    }

    pub(crate) fn refresh(&mut self) {
        let mut need_vulkan = Vec::new();
        let mut need_nvidia = Vec::new();
        self.get_non_nvidia_gpus(&mut need_vulkan, &mut need_nvidia);
        if !need_nvidia.is_empty() {
            self.nvm_lib = unsafe { self::nvidia::NvmlLib::load() };
            if let Some(nvml) = &self.nvm_lib {
                nvml.get_nvidia_gpus(&mut self.gpus);
            }
            // If the NVML library is unavailable, or an NVIDIA GPU was not updated for some reason, add it to the list of GPUs that need the Vulkan API.
            need_vulkan.extend(need_nvidia.into_iter().filter(|pci| {
                self.gpus
                    .iter()
                    .any(|gpu| !gpu.inner.updated && gpu.inner.pci == *pci)
            }));
        }
        if !need_vulkan.is_empty() {
            if self.vulkan_lib.is_none() {
                self.vulkan_lib = vulkan::Vulkan::load();
            }
            if let Some(ref vulkan) = self.vulkan_lib {
                vulkan.get_vulkan_info(&mut self.gpus);
            }
            // These GPUs are still present, so they must be kept even if their information cannot be retrieved.
            for gpu in self.gpus.iter_mut() {
                if need_vulkan.contains(&gpu.inner.pci) {
                    gpu.inner.updated = true;
                }
            }
        }
    }

    fn get_non_nvidia_gpus(&mut self, need_vulkan: &mut Vec<PCI>, need_nvidia: &mut Vec<PCI>) {
        let drm_path = "/sys/class/drm";
        let Ok(items) = read_dir(drm_path) else {
            sinf_debug!("failed to read `{drm_path}`");
            return;
        };
        let mut buffer = String::new();
        for entry in items.flatten() {
            let name = entry.file_name();
            if !name.as_encoded_bytes().starts_with(b"card")
                || name.as_encoded_bytes().contains(&b'-')
            {
                continue;
            }
            let device = entry.path().join("device");
            let Some(pci) = device
                .read_link()
                .ok()
                .and_then(|path| path.file_name()?.to_string_lossy().parse::<PCI>().ok())
            else {
                continue;
            };
            // If this GPU is already in the GPU list, it does not need to be re-added.
            if let Some(gpu) = self.gpus.iter_mut().find(|gpu| gpu.inner.pci == pci) {
                if gpu.inner.vendor.contains("AMD") {
                    get_amd_info(&mut gpu.inner, &mut buffer, &device);
                } else if gpu.inner.vendor.contains("NVIDIA") {
                    need_nvidia.push(pci);
                } else {
                    need_vulkan.push(pci);
                }
                continue;
            }
            // Filter out everything that is not a GPU.
            if read_file(device.join("class"), &mut buffer).is_err() {
                continue;
            }
            if !buffer.trim().starts_with("0x03") {
                // Not a GPU.
                continue;
            }
            if read_file(device.join("vendor"), &mut buffer).is_err() {
                continue;
            }
            let Some(vendor) = buffer
                .trim()
                .strip_prefix("0x")
                .and_then(|buf| u32::from_str_radix(buf, 16).ok())
            else {
                continue;
            };
            if !self.filled_device_map {
                fill_device_map(&mut self.device_map, &mut buffer);
                self.filled_device_map = true;
            }
            if let Some((vendor, devices)) = self.get_vendor_and_devices(vendor) {
                if vendor.contains("NVIDIA") {
                    // NVIDIA GPUs are retrieved elsewhere.
                    need_nvidia.push(pci);
                    continue;
                }
                let model = devices.and_then(|devices| {
                    read_file(device.join("device"), &mut buffer)
                        .ok()
                        .and_then(|_| {
                            u32::from_str_radix(buffer.trim().strip_prefix("0x")?, 16).ok()
                        })
                        .and_then(|device_id| devices.get(&device_id))
                });
                let mut gpu = GpuInner::new(pci.clone(), vendor, model);
                if vendor.contains("AMD") {
                    // AMD is special-cased because its information can be retrieved through sysfs alone.
                    get_amd_info(&mut gpu, &mut buffer, &device);
                } else {
                    need_vulkan.push(pci);
                }
                self.gpus.push(Gpu { inner: gpu });
            }
        }
    }
}

macro_rules! load_sym {
    ($lib_handle:ident, $sym_name:literal, $cast_into:ty $(,)?) => {{
        let sym_name = $sym_name;
        let sym = libc::dlsym($lib_handle, sym_name.as_ptr());
        if sym.is_null() {
            sinf_debug!("Failed to find symbol: {sym_name:?}");
            None
        } else {
            Some(std::mem::transmute::<*mut c_void, $cast_into>(sym))
        }
    }};
}

mod nvidia;
mod vulkan;