sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use super::*;

use std::collections::HashMap;
use std::os::fd::FromRawFd;
use std::time::Instant;

use super::{GpuInfo, ProcDir, ProcessBuffers, Wrap};
use crate::{Pid, Process, ProcessRefreshKind};
use std::mem::MaybeUninit;

const DRM_MAJOR: u32 = 226; // Devices under `/dev/dri/*`.
const ACCEL_MAJOR: u32 = 261; // Devices under `/dev/accel/*`.

// The `unshare` function can give a thread a different fd table from its parent.
pub(super) fn same_fd_table(pid1: Pid, pid2: Pid) -> bool {
    // FIXME: Remove once `libc` defines this constant.
    const KCMP_FILES: libc::c_int = 2;

    unsafe { libc::syscall(libc::SYS_kcmp, pid1.0, pid2.0, KCMP_FILES, 0, 0) == 0 }
}

// Threads that share their parent's fd table are not refreshed separately, since the result would be a duplicate.
pub(super) fn update_threads_gpu_info(
    proc_list: &mut HashMap<Pid, Process>,
    refresh_kind: ProcessRefreshKind,
    now: Instant,
    buffers: &mut ProcessBuffers,
) {
    // As in `refresh_procs`, `proc_list` must be accessed from two places at once.
    let proc_list = Wrap(UnsafeCell::new(proc_list));
    for p in proc_list.get().values_mut() {
        let p = &mut p.inner;
        if !p.updated || !p.gpu_info.share_parent_fd_table {
            continue;
        }
        let parent_info = p
            .parent
            .filter(|parent| *parent != p.pid)
            .and_then(|parent| proc_list.get().get(&parent))
            .filter(|parent| parent.inner.updated)
            .map(|parent| {
                (
                    parent.inner.gpu_info.gpu_usage,
                    parent.inner.gpu_info.memory,
                )
            });
        let gpu_info = &mut p.gpu_info;
        if let Some((gpu_usage, memory)) = parent_info {
            if refresh_kind.gpu_usage() {
                gpu_info.gpu_usage = gpu_usage;
            }
            if refresh_kind.gpu_memory() {
                gpu_info.memory = memory;
            }
        } else {
            let path = to_c_string(p.proc_path.clone());
            compute_gpu_usage(
                &mut ProcDir::new(&path),
                gpu_info,
                now,
                refresh_kind,
                buffers,
            );
        }
    }
}

#[inline(always)]
#[allow(clippy::unnecessary_cast)]
fn is_gpu_device(
    dir: &Dir,
    file_name: &[libc::c_char],
    stat: &mut MaybeUninit<libc::stat>,
) -> bool {
    unsafe {
        // Flags must be 0 so that the target of the `/proc/<pid>/fd` symlink is inspected.
        if libc::fstatat(dir.dir_fd, file_name.as_ptr(), stat.as_mut_ptr(), 0) != 0 {
            return false;
        }

        let stat = stat.assume_init_ref();
        ((stat.st_mode as u32) & libc::S_IFMT as u32) == libc::S_IFCHR as u32
            && matches!(
                libc::major(stat.st_rdev as libc::dev_t) as u32,
                DRM_MAJOR | ACCEL_MAJOR
            )
    }
}

struct Dir {
    dir_fd: libc::c_int,
}

impl Dir {
    fn open(proc_dir: &mut ProcDir<'_>, name: &CStr) -> Option<Self> {
        let proc_dir_fd = proc_dir.dir_fd()?;
        unsafe {
            let dir_fd = retry_eintr!(libc::openat(
                proc_dir_fd.as_raw_fd(),
                name.as_ptr(),
                libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_DIRECTORY | libc::O_CLOEXEC,
            ));
            if dir_fd < 0 {
                None
            } else {
                Some(Self { dir_fd })
            }
        }
    }

    fn update_dents_buf(&self, buf: &mut [u8]) -> Result<Option<usize>, ()> {
        unsafe {
            let read = libc::syscall(
                libc::SYS_getdents64,
                self.dir_fd,
                buf.as_mut_ptr() as *mut _,
                buf.len() as libc::c_int,
            );
            if read < 0 {
                sinf_debug!("getdents64 failed");
                Err(())
            } else if read == 0 {
                Ok(None)
            } else {
                Ok(Some(read as usize))
            }
        }
    }

    fn iter<'a>(&'a self, buf: &'a mut Vec<u8>) -> Result<Option<DirIter<'a>>, ()> {
        if let Some(read) = self.update_dents_buf(buf)? {
            Ok(Some(DirIter {
                read,
                pos: 0,
                dir: self,
                buf,
            }))
        } else {
            Ok(None)
        }
    }
}

impl Drop for Dir {
    fn drop(&mut self) {
        unsafe {
            libc::close(self.dir_fd);
        }
    }
}

struct DirIter<'a> {
    pos: usize,
    read: usize,
    dir: &'a Dir,
    // An array instead of a `Vec` causes unaligned memory errors while iterating the `dirent64` entries.
    buf: &'a mut Vec<u8>,
}

impl<'a> Iterator for DirIter<'a> {
    type Item = &'a [libc::c_char];

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            unsafe {
                if self.pos >= self.read {
                    if let Ok(Some(read)) = self.dir.update_dents_buf(self.buf) {
                        self.read = read;
                        self.pos = 0;
                    } else {
                        // Reached the end.
                        return None;
                    }
                }
                let dir_entry = self.buf.as_ptr().add(self.pos) as *const libc::dirent64;
                let dir_entry = &*dir_entry;
                self.pos += dir_entry.d_reclen as usize;

                // The name should contain only digits, but this filter also works well.
                if dir_entry.d_name[0] != b'.' as libc::c_char {
                    return Some(&dir_entry.d_name);
                }
            }
        }
    }
}

// A future option is to compute total % usage for non-AMD, non-NVIDIA GPUs by summing all process GPU time.
pub(super) fn compute_gpu_usage(
    proc_dir: &mut ProcDir<'_>,
    gpu_info: &mut GpuInfo,
    now: Instant,
    refresh_kind: ProcessRefreshKind,
    buffers: &mut ProcessBuffers,
) {
    use std::fs::File;
    use std::io::Read;

    let Some(fd_dir) = Dir::open(proc_dir, c"fd") else {
        return;
    };
    // Most processes have no GPU file descriptor, so `fdinfo` is opened only after one is found.
    let mut fdinfo_dir: Option<Dir> = None;

    let mut total_time: u64 = 0;
    let mut total_memory: u64 = 0;
    let mut found_memory = false;
    if let Ok(Some(dir_iter)) = fd_dir.iter(&mut buffers.dents) {
        let mut stat = MaybeUninit::<libc::stat>::uninit();
        // `drm-pdev` is present only for PCI GPUs.
        let mut gpus: Vec<(Vec<u8>, Option<Vec<u8>>)> = Vec::new();

        for file_name in dir_iter {
            if !is_gpu_device(&fd_dir, file_name, &mut stat) {
                continue;
            }
            let fdinfo_dir_fd = match fdinfo_dir {
                Some(ref dir) => dir.dir_fd,
                None => {
                    let Some(dir) = Dir::open(proc_dir, c"fdinfo") else {
                        return;
                    };
                    fdinfo_dir.insert(dir).dir_fd
                }
            };
            let buf = unsafe {
                let fd = retry_eintr!(libc::openat(
                    fdinfo_dir_fd,
                    file_name.as_ptr(),
                    libc::O_RDONLY,
                ));
                if fd < 0 {
                    continue;
                }
                // 4096 is the limit used by htop.
                const BUF_SIZE: usize = 4096;
                let buf = &mut buffers.buf;
                if buf.len() < BUF_SIZE {
                    assert!(buf.capacity() > BUF_SIZE);
                    // SAFETY: `ProcessBuffers::buf` is created with a capacity of `16_384`, so the length stays within the allocation.
                    buf.set_len(BUF_SIZE);
                }
                if let mut file = File::from_raw_fd(fd)
                    // Pass a slice of at most `BUF_SIZE` so no more than necessary is read.
                    && let Ok(read) = file.read(&mut buf[..BUF_SIZE])
                {
                    &buf[..read]
                } else {
                    continue;
                }
            };
            let mut gpu_id = None;
            let mut pci = None;
            let mut gpu_time: Option<u64> = None;
            let mut gpu_memory: Option<u64> = None;
            // Every key is documented at <https://www.kernel.org/doc/html/latest/gpu/drm-usage-stats.html>.
            for line in buf
                .split(|c| *c == b'\n')
                .filter_map(|line| line.strip_prefix(b"drm-"))
            {
                if line.starts_with(b"client-id:") {
                    if let Some(id) = line.splitn(2, |c| *c == b':').nth(1) {
                        gpu_id = Some(id.trim_ascii().to_vec());
                    }
                } else if line.starts_with(b"pdev:") {
                    if let Some(dev) = line.splitn(2, |c| *c == b':').nth(1) {
                        pci = Some(dev.trim_ascii().to_vec());
                    }
                } else if let Some(line) = line.strip_prefix(b"engine-") {
                    if refresh_kind.gpu_usage()
                        && !line.starts_with(b"capacity-")
                        && let Some(line) = line.strip_suffix(b" ns")
                        && let Some(nb) = line.split(|c| *c == b':').nth(1)
                        && let Some(nb) = parse_ascii_checked_u64(nb.trim_ascii())
                    {
                        *gpu_time.get_or_insert(0) += nb;
                    }
                } else if let Some(line) = line.strip_prefix(b"total-") {
                    #[allow(clippy::collapsible_if)]
                    if refresh_kind.gpu_memory()
                        && let Some(nb) = line.splitn(2, |c| *c == b':').nth(1)
                        && let mut nb = nb
                            .split(|c| *c == b' ' || *c == b'\t')
                            .filter(|s| !s.is_empty())
                        && let Some(value) = nb.next()
                        && let Some(unit) = nb.next()
                        && !unit.is_empty()
                        && let Some(value) = parse_ascii_checked_u64(value.trim_ascii())
                    {
                        gpu_memory = match unit[0] {
                            b'K' | b'k' => Some(value * 1024),
                            b'M' | b'm' => Some(value * 1024 * 1024),
                            b'G' | b'g' => Some(value * 1024 * 1024 * 1024),
                            _ => {
                                eprintln!(
                                    "Unknown GPU memory unit {unit:?} in {:?}",
                                    proc_dir.path
                                );
                                None
                            }
                        };
                    }
                }
            }
            // Fallback for when GPU memory or time was not retrieved.
            if let Some(gpu_id) = gpu_id
                && !gpus
                    .iter()
                    .any(|(s_id, s_pci)| *s_id == gpu_id && *s_pci == pci)
            {
                gpus.push((gpu_id, pci));
                if let Some(gpu_time) = gpu_time {
                    total_time = total_time.saturating_add(gpu_time);
                }
                if let Some(gpu_memory) = gpu_memory {
                    total_memory = total_memory.saturating_add(gpu_memory);
                    found_memory = true;
                }
            }
        }
    }
    if found_memory {
        gpu_info.memory = Some(total_memory);
    } else {
        gpu_info.memory = None;
    }
    if total_time != 0 {
        let elapsed_time = if let Some(last_update) = gpu_info.last_update {
            now.duration_since(last_update).as_millis()
        } else {
            0
        };
        let gpu_time_delta = total_time.saturating_sub(gpu_info.gpu_time);

        if gpu_time_delta == 0 || elapsed_time == 0 {
            gpu_info.gpu_usage = None;
        } else {
            // Convert nanoseconds to milliseconds, hence the `/ 1_000_000.`.
            gpu_info.gpu_usage =
                Some(100. * (gpu_time_delta as f32) / 1_000_000. / (elapsed_time as f32));
        }
        gpu_info.last_update = Some(now);
        gpu_info.gpu_time = total_time;
    } else {
        gpu_info.gpu_usage = Some(0.);
    }
}

use super::refresh::{parse_ascii_checked_u64, to_c_string};