use std::{ collections::{HashMap, HashSet}, fs, iter::Sum, ops::Add, time::Instant, }; use super::{Gpu, GpuMachine, mb}; #[derive(Clone, Copy, Default)] struct Group { busy: u64, cycles: u64, } impl Add for Group { type Output = Self; fn add(self, other: Self) -> Self { Self { busy: self.busy + other.busy, cycles: self.cycles + other.cycles, } } } #[derive(Clone, Copy, Default)] struct Totals { gfx: Group, video: Group, vram_kib: u64, } impl Add for Totals { type Output = Self; fn add(self, other: Self) -> Self { Self { gfx: self.gfx + other.gfx, video: self.video + other.video, vram_kib: self.vram_kib + other.vram_kib, } } } impl Sum for Totals { fn sum>(iter: I) -> Self { iter.fold(Self::default(), Add::add) } } struct Client { id: Option, pdev: String, totals: Totals, } #[derive(Clone)] struct Snapshot { at: Instant, pdev: String, own: Totals, machine: HashMap, } impl Snapshot { fn read() -> Option { let own = dedupe(own_clients()); let pdev = own.first()?.pdev.clone(); let own: Totals = own .iter() .filter(|client| client.pdev == pdev) .map(|client| client.totals) .sum(); let machine = machine_clients(&pdev) .into_iter() .filter_map(|client| Some((client.id?, client.totals))) .collect(); Some(Self { at: Instant::now(), pdev, own, machine, }) } } #[derive(Default)] pub struct Sampler { previous: Option, model: Option, } impl Sampler { pub fn sample(&mut self) -> Option { let current = Snapshot::read()?; let previous = self.previous.replace(current.clone())?; let wall = current.at.duration_since(previous.at).as_nanos() as f32; let model = self .model .get_or_insert_with(|| read_gpu_model(¤t.pdev)) .clone(); let machine_now: Totals = current.machine.values().copied().sum(); let machine_before: Totals = current .machine .iter() .map(|(id, now)| previous.machine.get(id).copied().unwrap_or(*now)) .sum(); Some(Gpu { model, gfx: percent(current.own.gfx, previous.own.gfx, wall), video: percent(current.own.video, previous.own.video, wall), vram_mb: mb(current.own.vram_kib << 10), machine: GpuMachine { gfx: percent(machine_now.gfx, machine_before.gfx, wall), video: percent(machine_now.video, machine_before.video, wall), vram_used_mb: mb(machine_now.vram_kib << 10), vram_total_mb: vram_total_mb(¤t.pdev), }, }) } } fn percent(now: Group, before: Group, wall: f32) -> f32 { let busy = now.busy.saturating_sub(before.busy) as f32; let span = if now.cycles == 0 { wall } else { now.cycles.saturating_sub(before.cycles) as f32 }; (busy / span.max(1.) * 100.).clamp(0., 100.) } fn dedupe(clients: Vec) -> Vec { let mut seen = HashSet::new(); clients .into_iter() .filter(|client| client.id.is_none_or(|id| seen.insert(id))) .collect() } fn own_clients() -> Vec { fs::read_dir("/proc/self/fdinfo") .into_iter() .flatten() .flatten() .filter_map(|entry| client(&fs::read_to_string(entry.path()).ok()?)) .collect() } fn machine_clients(pdev: &str) -> Vec { let mut clients = Vec::new(); for process in fs::read_dir("/proc").into_iter().flatten().flatten() { let name = process.file_name(); if !name.to_string_lossy().bytes().all(|b| b.is_ascii_digit()) { continue; } let path = process.path(); for fd in fs::read_dir(path.join("fd")) .into_iter() .flatten() .flatten() { let Ok(target) = fs::read_link(fd.path()) else { continue; }; if !target.starts_with("/dev/dri/") { continue; } let Ok(info) = fs::read_to_string(path.join("fdinfo").join(fd.file_name())) else { continue; }; if let Some(client) = client(&info) && client.pdev == pdev { clients.push(client); } } } clients } fn client(info: &str) -> Option { let fields: HashMap<&str, &str> = info .lines() .filter(|line| line.starts_with("drm-")) .filter_map(|line| line.split_once(':')) .map(|(key, value)| (key.trim(), value.trim())) .collect(); Some(Client { id: value(&fields, "drm-client-id"), pdev: fields.get("drm-pdev")?.to_string(), totals: Totals { gfx: group(&fields, &["gfx", "render"], &["rcs"]), video: group( &fields, &["enc", "dec", "video", "video-enhance"], &["vcs", "vecs"], ), vram_kib: ["drm-memory-vram", "drm-total-vram0", "drm-total-local0"] .iter() .find_map(|key| value(&fields, key)) .unwrap_or(0), }, }) } fn value(fields: &HashMap<&str, &str>, key: &str) -> Option { let mut parts = fields.get(key)?.split_whitespace(); let number: u64 = parts.next()?.parse().ok()?; Some(match parts.next() { Some("MiB") => number * 1024, _ => number, }) } fn group(fields: &HashMap<&str, &str>, engines: &[&str], classes: &[&str]) -> Group { let cycles: Vec<(u64, u64)> = classes .iter() .filter_map(|class| { Some(( value(fields, &format!("drm-cycles-{class}"))?, value(fields, &format!("drm-total-cycles-{class}"))?, )) }) .collect(); if cycles.is_empty() { let busy: u64 = engines .iter() .filter_map(|engine| { let busy = value(fields, &format!("drm-engine-{engine}"))?; let capacity = value(fields, &format!("drm-engine-capacity-{engine}")).unwrap_or(1); Some(busy / capacity.max(1)) }) .sum(); return Group { busy, cycles: 0 }; } Group { busy: cycles.iter().map(|(busy, _)| busy).sum(), cycles: cycles.iter().map(|(_, total)| total).sum(), } } fn vram_total_mb(pdev: &str) -> u32 { device_file(pdev, "mem_info_vram_total") .and_then(|value| value.parse::().ok()) .map_or(0, mb) } fn device_file(pdev: &str, name: &str) -> Option { fs::read_to_string(format!("/sys/bus/pci/devices/{pdev}/{name}")) .ok() .map(|value| value.trim().to_string()) } fn read_gpu_model(pdev: &str) -> String { let id = |name: &str| { device_file(pdev, name).map(|value| value.trim_start_matches("0x").to_lowercase()) }; let (Some(vendor), Some(device)) = (id("vendor"), id("device")) else { return String::new(); }; pci_name(&vendor, &device).unwrap_or_else(|| format!("{vendor}:{device}")) } fn pci_name(vendor: &str, device: &str) -> Option { let ids = ["/usr/share/hwdata/pci.ids", "/usr/share/misc/pci.ids"] .iter() .find_map(|path| fs::read_to_string(path).ok())?; let prefix = format!("{vendor} "); let mut lines = ids.lines().skip_while(|line| !line.starts_with(&prefix)); let vendor_name = lines.next()?.get(prefix.len()..)?.trim(); let vendor_name = vendor_name .split_once('[') .map_or(vendor_name, |(_, rest)| rest) .split([' ', '/', ']']) .next() .unwrap_or(vendor_name); let device_name = lines .filter(|line| !line.starts_with('#')) .take_while(|line| line.starts_with('\t')) .find_map(|line| line.strip_prefix('\t')?.strip_prefix(device))? .trim(); let device_name = device_name .split_once('[') .and_then(|(_, rest)| rest.split_once(']')) .map_or(device_name, |(inner, _)| inner); Some(format!("{vendor_name} {device_name}")) }