yumush
Clone
https://git.tahinli.com/Tahinli/yumush.git
0 watching·0 forks·Rust·AGPL-3.0·6.8 MiB·27ceb05·Tahinli·8 hours ago·399 commits
| 1 | use std::{ |
| 2 | collections::{HashMap, HashSet}, |
| 3 | fs, |
| 4 | sync::Arc, |
| 5 | time::Instant, |
| 6 | }; |
| 7 | |
| 8 | use super::{Gpu, GpuMachine}; |
| 9 | |
| 10 | #[derive(Clone, Copy, Default)] |
| 11 | struct Group { |
| 12 | busy: u64, |
| 13 | cycles: u64, |
| 14 | } |
| 15 | |
| 16 | impl Group { |
| 17 | fn add(self, other: Self) -> Self { |
| 18 | Self { |
| 19 | busy: self.busy + other.busy, |
| 20 | cycles: self.cycles + other.cycles, |
| 21 | } |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | struct Client { |
| 26 | id: Option<u64>, |
| 27 | pdev: String, |
| 28 | gfx: Group, |
| 29 | video: Group, |
| 30 | vram_kib: u64, |
| 31 | } |
| 32 | |
| 33 | #[derive(Clone, Copy, Default)] |
| 34 | struct Totals { |
| 35 | gfx: Group, |
| 36 | video: Group, |
| 37 | vram_kib: u64, |
| 38 | } |
| 39 | |
| 40 | impl Totals { |
| 41 | fn add(self, other: Self) -> Self { |
| 42 | Self { |
| 43 | gfx: self.gfx.add(other.gfx), |
| 44 | video: self.video.add(other.video), |
| 45 | vram_kib: self.vram_kib + other.vram_kib, |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | fn of<'a>(clients: impl Iterator<Item = &'a Client>) -> Self { |
| 50 | clients.fold(Self::default(), |sum, client| Self { |
| 51 | gfx: sum.gfx.add(client.gfx), |
| 52 | video: sum.video.add(client.video), |
| 53 | vram_kib: sum.vram_kib + client.vram_kib, |
| 54 | }) |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | #[derive(Clone)] |
| 59 | struct Snapshot { |
| 60 | at: Instant, |
| 61 | pdev: String, |
| 62 | own: Totals, |
| 63 | machine: HashMap<u64, Totals>, |
| 64 | } |
| 65 | |
| 66 | impl Snapshot { |
| 67 | fn read() -> Option<Self> { |
| 68 | let own = dedupe(own_clients()); |
| 69 | let pdev = own.first()?.pdev.clone(); |
| 70 | let own = Totals::of(own.iter().filter(|client| client.pdev == pdev)); |
| 71 | let machine = machine_clients(&pdev) |
| 72 | .into_iter() |
| 73 | .filter_map(|client| Some((client.id?, Totals::of([&client].into_iter())))) |
| 74 | .collect(); |
| 75 | Some(Self { |
| 76 | at: Instant::now(), |
| 77 | pdev, |
| 78 | own, |
| 79 | machine, |
| 80 | }) |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | #[derive(Default)] |
| 85 | pub struct Sampler { |
| 86 | previous: Option<Snapshot>, |
| 87 | model: Option<Arc<str>>, |
| 88 | } |
| 89 | |
| 90 | impl Sampler { |
| 91 | pub fn sample(&mut self) -> Option<Gpu> { |
| 92 | let current = Snapshot::read()?; |
| 93 | let previous = self.previous.replace(current.clone())?; |
| 94 | let wall = current.at.duration_since(previous.at).as_nanos() as f32; |
| 95 | let model = self |
| 96 | .model |
| 97 | .get_or_insert_with(|| read_gpu_model(¤t.pdev)) |
| 98 | .clone(); |
| 99 | let (machine_now, machine_before) = current.machine.iter().fold( |
| 100 | (Totals::default(), Totals::default()), |
| 101 | |(now_sum, before_sum), (id, now)| { |
| 102 | let before = previous.machine.get(id).copied().unwrap_or_default(); |
| 103 | (now_sum.add(*now), before_sum.add(before)) |
| 104 | }, |
| 105 | ); |
| 106 | Some(Gpu { |
| 107 | model: model.to_string(), |
| 108 | gfx: percent(current.own.gfx, previous.own.gfx, wall), |
| 109 | video: percent(current.own.video, previous.own.video, wall), |
| 110 | vram_mb: (current.own.vram_kib >> 10) as u32, |
| 111 | machine: GpuMachine { |
| 112 | gfx: percent(machine_now.gfx, machine_before.gfx, wall), |
| 113 | video: percent(machine_now.video, machine_before.video, wall), |
| 114 | vram_used_mb: (machine_now.vram_kib >> 10) as u32, |
| 115 | vram_total_mb: vram_total_mb(¤t.pdev), |
| 116 | }, |
| 117 | }) |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | fn percent(now: Group, before: Group, wall: f32) -> f32 { |
| 122 | let busy = now.busy.saturating_sub(before.busy) as f32; |
| 123 | let span = if now.cycles == 0 { |
| 124 | wall |
| 125 | } else { |
| 126 | now.cycles.saturating_sub(before.cycles) as f32 |
| 127 | }; |
| 128 | (busy / span.max(1.) * 100.).clamp(0., 100.) |
| 129 | } |
| 130 | |
| 131 | fn dedupe(clients: Vec<Client>) -> Vec<Client> { |
| 132 | let mut seen = HashSet::new(); |
| 133 | clients |
| 134 | .into_iter() |
| 135 | .filter(|client| client.id.is_none_or(|id| seen.insert(id))) |
| 136 | .collect() |
| 137 | } |
| 138 | |
| 139 | fn own_clients() -> Vec<Client> { |
| 140 | fs::read_dir("/proc/self/fdinfo") |
| 141 | .into_iter() |
| 142 | .flatten() |
| 143 | .flatten() |
| 144 | .filter_map(|entry| client(&fs::read_to_string(entry.path()).ok()?)) |
| 145 | .collect() |
| 146 | } |
| 147 | |
| 148 | fn machine_clients(pdev: &str) -> Vec<Client> { |
| 149 | let mut clients = Vec::new(); |
| 150 | for process in fs::read_dir("/proc").into_iter().flatten().flatten() { |
| 151 | let name = process.file_name(); |
| 152 | if !name.to_string_lossy().bytes().all(|b| b.is_ascii_digit()) { |
| 153 | continue; |
| 154 | } |
| 155 | let path = process.path(); |
| 156 | for fd in fs::read_dir(path.join("fd")) |
| 157 | .into_iter() |
| 158 | .flatten() |
| 159 | .flatten() |
| 160 | { |
| 161 | let Ok(target) = fs::read_link(fd.path()) else { |
| 162 | continue; |
| 163 | }; |
| 164 | if !target.starts_with("/dev/dri/") { |
| 165 | continue; |
| 166 | } |
| 167 | let Ok(info) = fs::read_to_string(path.join("fdinfo").join(fd.file_name())) else { |
| 168 | continue; |
| 169 | }; |
| 170 | if let Some(client) = client(&info) |
| 171 | && client.pdev == pdev |
| 172 | { |
| 173 | clients.push(client); |
| 174 | } |
| 175 | } |
| 176 | } |
| 177 | clients |
| 178 | } |
| 179 | |
| 180 | fn client(info: &str) -> Option<Client> { |
| 181 | let fields: HashMap<&str, &str> = info |
| 182 | .lines() |
| 183 | .filter(|line| line.starts_with("drm-")) |
| 184 | .filter_map(|line| line.split_once(':')) |
| 185 | .map(|(key, value)| (key.trim(), value.trim())) |
| 186 | .collect(); |
| 187 | Some(Client { |
| 188 | id: value(&fields, "drm-client-id"), |
| 189 | pdev: fields.get("drm-pdev")?.to_string(), |
| 190 | gfx: group(&fields, &["gfx", "render"], &["rcs"]), |
| 191 | video: group( |
| 192 | &fields, |
| 193 | &["enc", "dec", "video", "video-enhance"], |
| 194 | &["vcs", "vecs"], |
| 195 | ), |
| 196 | vram_kib: ["drm-memory-vram", "drm-total-vram0", "drm-total-local0"] |
| 197 | .iter() |
| 198 | .find_map(|key| value(&fields, key)) |
| 199 | .unwrap_or(0), |
| 200 | }) |
| 201 | } |
| 202 | |
| 203 | fn value(fields: &HashMap<&str, &str>, key: &str) -> Option<u64> { |
| 204 | let mut parts = fields.get(key)?.split_whitespace(); |
| 205 | let number: u64 = parts.next()?.parse().ok()?; |
| 206 | Some(match parts.next() { |
| 207 | Some("MiB") => number * 1024, |
| 208 | _ => number, |
| 209 | }) |
| 210 | } |
| 211 | |
| 212 | fn group(fields: &HashMap<&str, &str>, engines: &[&str], classes: &[&str]) -> Group { |
| 213 | let cycles: Vec<(u64, u64)> = classes |
| 214 | .iter() |
| 215 | .filter_map(|class| { |
| 216 | Some(( |
| 217 | value(fields, &format!("drm-cycles-{class}"))?, |
| 218 | value(fields, &format!("drm-total-cycles-{class}"))?, |
| 219 | )) |
| 220 | }) |
| 221 | .collect(); |
| 222 | if cycles.is_empty() { |
| 223 | let busy: u64 = engines |
| 224 | .iter() |
| 225 | .filter_map(|engine| { |
| 226 | let busy = value(fields, &format!("drm-engine-{engine}"))?; |
| 227 | let capacity = value(fields, &format!("drm-engine-capacity-{engine}")).unwrap_or(1); |
| 228 | Some(busy / capacity.max(1)) |
| 229 | }) |
| 230 | .sum(); |
| 231 | return Group { busy, cycles: 0 }; |
| 232 | } |
| 233 | Group { |
| 234 | busy: cycles.iter().map(|(busy, _)| busy).sum(), |
| 235 | cycles: cycles.iter().map(|(_, total)| total).sum(), |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | fn vram_total_mb(pdev: &str) -> u32 { |
| 240 | device_file(pdev, "mem_info_vram_total") |
| 241 | .and_then(|value| value.parse::<u64>().ok()) |
| 242 | .map_or(0, |bytes| (bytes >> 20) as u32) |
| 243 | } |
| 244 | |
| 245 | fn device_file(pdev: &str, name: &str) -> Option<String> { |
| 246 | fs::read_to_string(format!("/sys/bus/pci/devices/{pdev}/{name}")) |
| 247 | .ok() |
| 248 | .map(|value| value.trim().to_string()) |
| 249 | } |
| 250 | |
| 251 | fn read_gpu_model(pdev: &str) -> Arc<str> { |
| 252 | let id = |name: &str| { |
| 253 | device_file(pdev, name).map(|value| value.trim_start_matches("0x").to_lowercase()) |
| 254 | }; |
| 255 | let (Some(vendor), Some(device)) = (id("vendor"), id("device")) else { |
| 256 | return Arc::from(""); |
| 257 | }; |
| 258 | pci_name(&vendor, &device) |
| 259 | .unwrap_or_else(|| format!("{vendor}:{device}")) |
| 260 | .into() |
| 261 | } |
| 262 | |
| 263 | fn pci_name(vendor: &str, device: &str) -> Option<String> { |
| 264 | let ids = ["/usr/share/hwdata/pci.ids", "/usr/share/misc/pci.ids"] |
| 265 | .iter() |
| 266 | .find_map(|path| fs::read_to_string(path).ok())?; |
| 267 | let prefix = format!("{vendor} "); |
| 268 | let mut lines = ids.lines().skip_while(|line| !line.starts_with(&prefix)); |
| 269 | let vendor_name = lines.next()?.get(prefix.len()..)?.trim(); |
| 270 | let vendor_name = vendor_name |
| 271 | .split_once('[') |
| 272 | .map_or(vendor_name, |(_, rest)| rest) |
| 273 | .split([' ', '/', ']']) |
| 274 | .next() |
| 275 | .unwrap_or(vendor_name); |
| 276 | let device_name = lines |
| 277 | .filter(|line| !line.starts_with('#')) |
| 278 | .take_while(|line| line.starts_with('\t')) |
| 279 | .find_map(|line| line.strip_prefix('\t')?.strip_prefix(device))? |
| 280 | .trim(); |
| 281 | let device_name = device_name |
| 282 | .split_once('[') |
| 283 | .and_then(|(_, rest)| rest.split_once(']')) |
| 284 | .map_or(device_name, |(inner, _)| inner); |
| 285 | Some(format!("{vendor_name} {device_name}")) |
| 286 | } |