use super::*;
use libc::{c_char, c_int, c_uint, c_ulonglong, c_void};
use std::mem::MaybeUninit;
use std::ptr::null_mut;
#[repr(C)]
struct NvmlUtilization {
gpu: c_uint,
memory: c_uint,
}
#[repr(C)]
struct NvmlMemory {
total: c_ulonglong,
free: c_ulonglong,
used: c_ulonglong,
}
#[repr(C)]
struct NvmlPciInfo {
bus_id_legacy: [c_char; 16],
domain: c_uint,
bus: c_uint,
device: c_uint,
pci_device_id: c_uint,
pci_sub_system_id: c_uint,
bus_id: [c_char; 32],
}
type NvmlReturn = c_int;
type NvmlDeviceHandle = *mut c_void;
type NvmlInitFn = unsafe extern "C" fn() -> NvmlReturn;
type NvmlShutdownFn = unsafe extern "C" fn() -> NvmlReturn;
type NvmlDeviceGetCountFn = unsafe extern "C" fn(*mut c_uint) -> NvmlReturn;
type NvmlDeviceGetHandleByIndexFn =
unsafe extern "C" fn(c_uint, *mut NvmlDeviceHandle) -> NvmlReturn;
type NvmlDeviceGetNameFn =
unsafe extern "C" fn(NvmlDeviceHandle, *mut c_char, c_uint) -> NvmlReturn;
type NvmlDeviceGetUtilizationRatesFn =
unsafe extern "C" fn(NvmlDeviceHandle, *mut NvmlUtilization) -> NvmlReturn;
type NvmlDeviceGetMemoryInfoFn =
unsafe extern "C" fn(NvmlDeviceHandle, *mut NvmlMemory) -> NvmlReturn;
type NvmlDeviceGetPciInfo = unsafe extern "C" fn(NvmlDeviceHandle, *mut NvmlPciInfo) -> NvmlReturn;
const NVML_SUCCESS: NvmlReturn = 0;
const NVML_DEVICE_NAME_V2_BUFFER_SIZE: usize = 96;
unsafe impl Send for NvmlLib {}
unsafe impl Sync for NvmlLib {}
pub(crate) struct NvmlLib {
lib_handle: *mut c_void,
init: NvmlInitFn,
shutdown: NvmlShutdownFn,
get_count: NvmlDeviceGetCountFn,
get_handle: NvmlDeviceGetHandleByIndexFn,
get_name: NvmlDeviceGetNameFn,
get_utilization: NvmlDeviceGetUtilizationRatesFn,
get_memory_info: NvmlDeviceGetMemoryInfoFn,
get_pci_info: NvmlDeviceGetPciInfo,
}
impl NvmlLib {
pub(crate) unsafe fn load() -> Option<Self> {
let lib_name = c"libnvidia-ml.so.1";
unsafe {
let lib_handle = libc::dlopen(lib_name.as_ptr(), libc::RTLD_NOW);
if lib_handle.is_null() {
sinf_debug!("Failed to find or load {lib_name:?}");
return None;
}
match Self::load_symbols(lib_handle) {
Some(ret) => Some(ret),
None => {
libc::dlclose(lib_handle);
None
}
}
}
}
unsafe fn load_symbols(lib_handle: *mut c_void) -> Option<Self> {
unsafe {
Some(Self {
lib_handle,
init: load_sym!(lib_handle, c"nvmlInit_v2", NvmlInitFn)?,
shutdown: load_sym!(lib_handle, c"nvmlShutdown", NvmlShutdownFn)?,
get_count: load_sym!(lib_handle, c"nvmlDeviceGetCount_v2", NvmlDeviceGetCountFn,)?,
get_handle: load_sym!(
lib_handle,
c"nvmlDeviceGetHandleByIndex_v2",
NvmlDeviceGetHandleByIndexFn,
)?,
get_name: load_sym!(lib_handle, c"nvmlDeviceGetName", NvmlDeviceGetNameFn)?,
get_utilization: load_sym!(
lib_handle,
c"nvmlDeviceGetUtilizationRates",
NvmlDeviceGetUtilizationRatesFn,
)?,
get_memory_info: load_sym!(
lib_handle,
c"nvmlDeviceGetMemoryInfo",
NvmlDeviceGetMemoryInfoFn,
)?,
get_pci_info: load_sym!(
lib_handle,
c"nvmlDeviceGetPciInfo_v3",
NvmlDeviceGetPciInfo,
)?,
})
}
}
pub(crate) fn get_nvidia_gpus(&self, gpus: &mut Vec<Gpu>) {
unsafe {
if let Some(query) = NvmlLibQuery::new(self) {
query.query(gpus);
}
}
}
}
impl Drop for NvmlLib {
fn drop(&mut self) {
unsafe {
libc::dlclose(self.lib_handle);
}
}
}
struct NvmlLibQuery<'a> {
inner: &'a NvmlLib,
}
impl<'a> NvmlLibQuery<'a> {
fn new(inner: &'a NvmlLib) -> Option<Self> {
unsafe {
if (inner.init)() != NVML_SUCCESS {
sinf_debug!("Failed to initialize NVML context.");
return None;
}
Some(Self { inner })
}
}
unsafe fn query(&self, gpus: &mut Vec<Gpu>) {
unsafe {
let mut device_count: c_uint = 0;
if (self.inner.get_count)(&mut device_count) != NVML_SUCCESS {
sinf_debug!("Failed to retrieve device count.");
return;
}
for index in 0..device_count {
let mut device_handle: NvmlDeviceHandle = null_mut();
if (self.inner.get_handle)(index, &mut device_handle) != NVML_SUCCESS {
sinf_debug!("Failed to get handle for GPU {index}");
continue;
}
let mut pci_info = MaybeUninit::<NvmlPciInfo>::uninit();
if (self.inner.get_pci_info)(device_handle, pci_info.as_mut_ptr()) != NVML_SUCCESS {
sinf_debug!("Failed to get PCI for GPU {index}");
continue;
}
let pci_info = pci_info.assume_init();
let Some(pci) =
convert_to_str(&pci_info.bus_id).and_then(|pci| pci.parse::<PCI>().ok())
else {
continue;
};
let gpu = match gpus
.iter_mut()
.find(|gpu| !gpu.inner.updated && gpu.inner.pci == pci)
{
Some(gpu) => &mut gpu.inner,
None => {
let mut gpu = GpuInner::new(pci.to_owned(), "NVIDIA Corporation", None);
let mut name_buffer = [0 as c_char; NVML_DEVICE_NAME_V2_BUFFER_SIZE];
if (self.inner.get_name)(
device_handle,
name_buffer.as_mut_ptr(),
NVML_DEVICE_NAME_V2_BUFFER_SIZE as c_uint,
) == NVML_SUCCESS
{
gpu.model = convert_to_string(&name_buffer);
}
gpus.push(Gpu { inner: gpu });
&mut gpus.last_mut().unwrap().inner
}
};
let mut utilization = NvmlUtilization { gpu: 0, memory: 0 };
if (self.inner.get_utilization)(device_handle, &mut utilization) == NVML_SUCCESS {
gpu.usage = Some(utilization.gpu as f32);
}
let mut mem_info = NvmlMemory {
total: 0,
free: 0,
used: 0,
};
if (self.inner.get_memory_info)(device_handle, &mut mem_info) == NVML_SUCCESS {
gpu.total_memory = Some(mem_info.total);
gpu.used_memory = Some(mem_info.used);
}
gpu.updated = true;
}
}
}
}
impl<'a> Drop for NvmlLibQuery<'a> {
fn drop(&mut self) {
unsafe {
(self.inner.shutdown)();
}
}
}