1use super::aggregate::ProcessFigures;
19use crate::backend::rpc_types::GpuAdapterKind;
20use std::collections::HashMap;
21use std::time::Duration;
22
23pub const VENDOR_INTEL: u32 = 0x8086;
24pub const VENDOR_AMD: u32 = 0x1002;
25pub const VENDOR_NVIDIA: u32 = 0x10de;
26
27#[derive(Debug, Clone, PartialEq, Default)]
29pub struct DrmClient {
30 pub driver: String,
31 pub pdev: Option<String>,
33 pub id: Option<u64>,
35 pub engines: Vec<(String, u64)>,
37 pub dedicated: Option<u64>,
39 pub shared: Option<u64>,
41}
42
43fn amount(value: &str) -> Option<u64> {
45 let mut parts = value.split_whitespace();
46 let n: u64 = parts.next()?.parse().ok()?;
47 let scale: u64 = match parts.next().map(str::to_ascii_lowercase).as_deref() {
48 None | Some("b") | Some("ns") => 1,
49 Some("kib") => 1 << 10,
50 Some("mib") => 1 << 20,
51 Some("gib") => 1 << 30,
52 Some("tib") => 1 << 40,
53 Some(_) => return None,
54 };
55 n.checked_mul(scale)
56}
57
58#[derive(Clone, Copy, PartialEq, Eq)]
61enum Placement {
62 Dedicated,
63 Shared,
64 Neither,
65}
66
67fn placement(region: &str) -> Placement {
68 if region.starts_with("vram") || region.starts_with("local") {
70 Placement::Dedicated
71 } else if region.starts_with("gtt") || region.starts_with("system") {
72 Placement::Shared
73 } else {
74 Placement::Neither
75 }
76}
77
78#[derive(Default)]
80struct Region {
81 resident: Option<u64>,
82 memory: Option<u64>,
83 total: Option<u64>,
84}
85
86pub fn parse_fdinfo(text: &str) -> Option<DrmClient> {
88 let mut client = DrmClient::default();
89 let mut seen_driver = false;
90 let mut regions: HashMap<String, Region> = HashMap::new();
91 for line in text.lines() {
92 let Some((key, value)) = line.split_once(':') else { continue };
93 let value = value.trim();
94 match key {
95 "drm-driver" => {
96 client.driver = value.to_string();
97 seen_driver = true;
98 }
99 "drm-pdev" => client.pdev = Some(value.to_ascii_lowercase()),
100 "drm-client-id" => client.id = value.parse().ok(),
101 _ => {
102 if let Some(engine) = key.strip_prefix("drm-engine-") {
103 if !engine.starts_with("capacity-") {
105 if let Some(ns) = amount(value) {
106 client.engines.push((engine.to_string(), ns));
107 }
108 }
109 } else if let Some(region) = key.strip_prefix("drm-resident-") {
110 regions.entry(region.to_string()).or_default().resident = amount(value);
111 } else if let Some(region) = key.strip_prefix("drm-memory-") {
112 regions.entry(region.to_string()).or_default().memory = amount(value);
113 } else if let Some(region) = key.strip_prefix("drm-total-") {
114 regions.entry(region.to_string()).or_default().total = amount(value);
115 }
116 }
117 }
118 }
119 if !seen_driver {
120 return None;
121 }
122 let held = |want: Placement| {
123 regions
124 .iter()
125 .filter(|(name, _)| placement(name) == want)
126 .filter_map(|(_, r)| r.resident.or(r.memory).or(r.total))
127 .reduce(|a, b| a.saturating_add(b))
128 };
129 client.dedicated = held(Placement::Dedicated);
130 client.shared = held(Placement::Shared);
131 Some(client)
132}
133
134pub fn parse_uevent(text: &str) -> HashMap<String, String> {
136 text.lines()
137 .filter_map(|l| l.split_once('='))
138 .map(|(k, v)| (k.trim().to_string(), v.trim().to_string()))
139 .collect()
140}
141
142pub fn parse_pci_id(text: &str) -> Option<u32> {
144 let t = text.trim();
145 u32::from_str_radix(t.strip_prefix("0x").unwrap_or(t), 16).ok()
146}
147
148pub fn vendor_name(vendor: u32) -> &'static str {
150 match vendor {
151 VENDOR_AMD => "AMD",
152 VENDOR_INTEL => "Intel",
153 VENDOR_NVIDIA => "NVIDIA",
154 _ => "GPU",
155 }
156}
157
158pub fn pci_ids_device(db: &str, vendor: u32, device: u32) -> Option<String> {
160 let vendor_key = format!("{vendor:04x} ");
161 let device_key = format!("\t{device:04x} ");
162 let mut in_vendor = false;
163 for line in db.lines() {
164 if line.starts_with('#') || line.is_empty() {
165 continue;
166 }
167 if !line.starts_with('\t') {
168 if in_vendor {
170 return None;
171 }
172 in_vendor = line.to_ascii_lowercase().starts_with(&vendor_key);
173 } else if in_vendor {
174 if let Some(name) = line.to_ascii_lowercase().strip_prefix(&device_key) {
175 let cut = line.len() - name.len();
177 return Some(line[cut..].trim().to_string());
178 }
179 }
180 }
181 None
182}
183
184pub fn display_name(vendor: u32, device: u32, from_db: Option<&str>) -> String {
187 let maker = vendor_name(vendor);
188 let Some(raw) = from_db else {
189 return format!("{maker} GPU {vendor:04x}:{device:04x}");
190 };
191 let inner = match (raw.rfind('['), raw.rfind(']')) {
192 (Some(open), Some(close)) if open < close => raw[open + 1..close].trim(),
193 _ => raw.trim(),
194 };
195 if inner.to_ascii_lowercase().contains(&maker.to_ascii_lowercase()) {
196 inner.to_string()
197 } else {
198 format!("{maker} {inner}")
199 }
200}
201
202const INTEGRATED_BELOW: u64 = 1 << 30;
204
205fn named_integrated(name: &str) -> bool {
207 let n = name.to_ascii_lowercase();
208 if n.contains("intel") {
209 return !n.contains("arc");
210 }
211 (n.contains("radeon") || n.contains("amd")) && n.trim_end().ends_with("graphics") && !n.contains(" rx ")
212}
213
214pub fn kind_of(name: &str, dedicated_total: Option<u64>) -> GpuAdapterKind {
216 if named_integrated(name) || dedicated_total.is_some_and(|t| t < INTEGRATED_BELOW) {
217 GpuAdapterKind::Integrated
218 } else {
219 GpuAdapterKind::Discrete
220 }
221}
222
223#[derive(Debug, Clone, PartialEq)]
225pub struct Scanned {
226 pub pid: u32,
227 pub fd: u32,
229 pub client: DrmClient,
230}
231
232pub type ClientKey = (u32, String, u64);
234
235fn key_of(s: &Scanned) -> ClientKey {
236 (s.pid, s.client.pdev.clone().unwrap_or_default(), s.client.id.unwrap_or((1 << 63) | u64::from(s.fd)))
239}
240
241const MIN_ELAPSED: Duration = Duration::from_millis(100);
243
244pub fn process_figures(
251 scanned: &[Scanned],
252 prev: &HashMap<ClientKey, u64>,
253 elapsed: Option<Duration>,
254) -> (Vec<ProcessFigures>, HashMap<ClientKey, u64>) {
255 let elapsed_ns = elapsed.filter(|e| *e >= MIN_ELAPSED).map(|e| e.as_nanos() as f64);
256 let mut next: HashMap<ClientKey, u64> = HashMap::new();
257 let mut by_pid: HashMap<u32, ProcessFigures> = HashMap::new();
258 for s in scanned {
259 let key = key_of(s);
260 if next.contains_key(&key) {
261 continue; }
263 let busy: u64 = s.client.engines.iter().fold(0u64, |a, (_, ns)| a.saturating_add(*ns));
264 next.insert(key.clone(), busy);
265 let use_pct = match (elapsed_ns, prev.get(&key)) {
266 (Some(dt), Some(before)) if !s.client.engines.is_empty() => Some((busy.saturating_sub(*before) as f64 / dt * 100.0).clamp(0.0, 100.0)),
267 _ => None,
268 };
269 let p = by_pid.entry(s.pid).or_insert(ProcessFigures { pid: s.pid, use_pct: None, dedicated: None, shared: None });
270 p.use_pct = match (p.use_pct, use_pct) {
271 (Some(a), Some(b)) => Some((a + b).min(100.0)),
272 (a, b) => a.or(b),
273 };
274 let add = |a: Option<u64>, b: Option<u64>| match (a, b) {
275 (Some(a), Some(b)) => Some(a.saturating_add(b)),
276 (a, b) => a.or(b),
277 };
278 p.dedicated = add(p.dedicated, s.client.dedicated);
279 p.shared = add(p.shared, s.client.shared);
280 }
281 let mut out: Vec<ProcessFigures> = by_pid.into_values().collect();
282 out.sort_by_key(|p| p.pid);
283 (out, next)
284}
285
286pub fn held_on(scanned: &[Scanned], pdev: &str) -> (Option<u64>, Option<u64>) {
289 let mut seen: HashMap<ClientKey, ()> = HashMap::new();
290 let (mut dedicated, mut shared): (Option<u64>, Option<u64>) = (None, None);
291 for s in scanned.iter().filter(|s| s.client.pdev.as_deref() == Some(pdev)) {
292 if seen.insert(key_of(s), ()).is_some() {
293 continue;
294 }
295 let add = |a: Option<u64>, b: Option<u64>| match (a, b) {
296 (Some(a), Some(b)) => Some(a.saturating_add(b)),
297 (a, b) => a.or(b),
298 };
299 dedicated = add(dedicated, s.client.dedicated);
300 shared = add(shared, s.client.shared);
301 }
302 (dedicated, shared)
303}
304
305#[cfg(test)]
306mod tests {
307 use super::*;
308
309 const AMDGPU: &str = "pos:\t0\nflags:\t02100002\nmnt_id:\t26\nino:\t331\n\
310drm-driver:\tamdgpu\n\
311drm-client-name:\t\n\
312drm-pdev:\t0000:03:00.0\n\
313drm-client-id:\t4083\n\
314drm-engine-gfx:\t1234567890 ns\n\
315drm-engine-compute:\t0 ns\n\
316drm-engine-dec:\t77 ns\n\
317drm-memory-vram:\t1048576 KiB\n\
318drm-memory-gtt: \t2048 KiB\n\
319drm-memory-cpu: \t16 KiB\n";
320
321 const I915: &str = "drm-driver:\ti915\n\
322drm-pdev:\t0000:00:02.0\n\
323drm-client-id:\t12\n\
324drm-engine-render:\t5000 ns\n\
325drm-engine-capacity-render:\t1\n\
326drm-total-system0:\t30 MiB\n\
327drm-resident-system0:\t20 MiB\n";
328
329 const XE: &str = "drm-driver:\txe\n\
330drm-client-id:\t9\n\
331drm-pdev:\t0000:0A:00.0\n\
332drm-engine-rcs:\t100 ns\n\
333drm-total-vram0:\t512 MiB\n\
334drm-resident-vram0:\t256 MiB\n\
335drm-total-gtt:\t64 MiB\n";
336
337 #[test]
338 fn an_amdgpu_client_names_its_engines_and_its_memory() {
339 let c = parse_fdinfo(AMDGPU).unwrap();
340 assert_eq!((c.driver.as_str(), c.pdev.as_deref(), c.id), ("amdgpu", Some("0000:03:00.0"), Some(4083)));
341 assert_eq!(c.engines, [("gfx".to_string(), 1_234_567_890), ("compute".to_string(), 0), ("dec".to_string(), 77)]);
342 assert_eq!(c.dedicated, Some(1 << 30), "1048576 KiB of video memory");
343 assert_eq!(c.shared, Some(2 << 20), "the GTT; the CPU-visible domain is neither");
344 }
345
346 #[test]
347 fn an_i915_client_uses_what_is_resident_and_skips_the_engine_capacity_line() {
348 let c = parse_fdinfo(I915).unwrap();
349 assert_eq!(c.engines, [("render".to_string(), 5000)]);
350 assert_eq!((c.dedicated, c.shared), (None, Some(20 << 20)), "resident, not the total");
351 }
352
353 #[test]
354 fn an_xe_client_lower_cases_its_slot_and_keeps_card_and_system_memory_apart() {
355 let c = parse_fdinfo(XE).unwrap();
356 assert_eq!(c.pdev.as_deref(), Some("0000:0a:00.0"));
357 assert_eq!((c.dedicated, c.shared), (Some(256 << 20), Some(64 << 20)));
358 }
359
360 #[test]
361 fn a_descriptor_that_is_not_a_drm_one_is_not_a_client() {
362 assert_eq!(parse_fdinfo("pos:\t0\nflags:\t02\nmnt_id:\t15\n"), None);
363 assert_eq!(parse_fdinfo(""), None);
364 assert!(parse_fdinfo("drm-driver:\tamdgpu\n").is_some(), "no figures is still a client");
365 }
366
367 #[test]
368 fn a_figure_with_a_unit_it_does_not_know_is_left_out_not_guessed() {
369 let c = parse_fdinfo("drm-driver:\tx\ndrm-memory-vram:\t5 furlongs\ndrm-engine-gfx:\tlots\n").unwrap();
370 assert_eq!((c.dedicated, c.engines.len()), (None, 0));
371 }
372
373 #[test]
374 fn the_amounts_are_binary_and_bare_numbers_are_bytes() {
375 assert_eq!(amount("1 KiB"), Some(1024));
376 assert_eq!(amount("2 gib"), Some(2 << 30));
377 assert_eq!(amount("700"), Some(700));
378 assert_eq!(amount("12 ns"), Some(12));
379 assert_eq!(amount("-3 KiB"), None);
380 assert_eq!(amount(""), None);
381 }
382
383 #[test]
384 fn a_uevent_and_a_pci_id_file_are_read() {
385 let u = parse_uevent("DRIVER=amdgpu\nPCI_CLASS=30000\nPCI_ID=1002:73BF\nPCI_SLOT_NAME=0000:03:00.0\n");
386 assert_eq!(u.get("DRIVER").map(String::as_str), Some("amdgpu"));
387 assert_eq!(u.get("PCI_SLOT_NAME").map(String::as_str), Some("0000:03:00.0"));
388 assert_eq!(parse_pci_id("0x1002\n"), Some(0x1002));
389 assert_eq!(parse_pci_id("73bf"), Some(0x73bf));
390 assert_eq!(parse_pci_id("nope"), None);
391 }
392
393 const PCI_IDS: &str = "# a comment\n\
3941002 Advanced Micro Devices, Inc. [AMD/ATI]\n\
395\t73bf Navi 21 [Radeon RX 6800/6800 XT / 6900 XT]\n\
396\t\t1002 0e3a Subsystem name\n\
397\t1638 Cezanne [Radeon Vega Series / Radeon Vega Mobile Series]\n\
3988086 Intel Corporation\n\
399\t4680 AlderLake-S GT1 [UHD Graphics 770]\n\
400\t56a0 DG2 [Arc A770]\n\
40110de NVIDIA Corporation\n\
402\t2484 GA104 [GeForce RTX 3070]\n\
403\t1234 Plain Name\n";
404
405 #[test]
406 fn the_id_database_gives_a_device_its_name() {
407 assert_eq!(pci_ids_device(PCI_IDS, 0x1002, 0x73bf).as_deref(), Some("Navi 21 [Radeon RX 6800/6800 XT / 6900 XT]"));
408 assert_eq!(pci_ids_device(PCI_IDS, 0x8086, 0x56a0).as_deref(), Some("DG2 [Arc A770]"));
409 assert_eq!(pci_ids_device(PCI_IDS, 0x10de, 0x1234).as_deref(), Some("Plain Name"));
410 assert_eq!(pci_ids_device(PCI_IDS, 0x8086, 0x73bf), None);
412 assert_eq!(pci_ids_device(PCI_IDS, 0x1002, 0xffff), None);
413 assert_eq!(pci_ids_device(PCI_IDS, 0x15ad, 0x0405), None);
414 }
415
416 #[test]
417 fn a_name_is_the_marketing_one_with_its_maker() {
418 let name = |v, d| display_name(v, d, pci_ids_device(PCI_IDS, v, d).as_deref());
419 assert_eq!(name(0x1002, 0x73bf), "AMD Radeon RX 6800/6800 XT / 6900 XT");
420 assert_eq!(name(0x8086, 0x4680), "Intel UHD Graphics 770");
421 assert_eq!(name(0x8086, 0x56a0), "Intel Arc A770");
422 assert_eq!(name(0x10de, 0x2484), "NVIDIA GeForce RTX 3070");
423 assert_eq!(name(0x10de, 0x1234), "NVIDIA Plain Name");
424 assert_eq!(display_name(0x1002, 0x73bf, None), "AMD GPU 1002:73bf", "no database: the ids");
425 }
426
427 #[test]
428 fn the_cpus_own_graphics_are_integrated_a_card_is_discrete() {
429 assert_eq!(kind_of("Intel UHD Graphics 770", None), GpuAdapterKind::Integrated);
430 assert_eq!(kind_of("Intel Arc A770", Some(16 << 30)), GpuAdapterKind::Discrete);
431 assert_eq!(kind_of("Intel Arc A770", None), GpuAdapterKind::Discrete, "an Arc names itself");
432 assert_eq!(kind_of("Intel Iris Xe", None), GpuAdapterKind::Integrated);
433 assert_eq!(kind_of("AMD Radeon RX 6800/6800 XT / 6900 XT", Some(16 << 30)), GpuAdapterKind::Discrete);
434 assert_eq!(kind_of("AMD Radeon Vega Series / Radeon Vega Mobile Series", Some(512 << 20)), GpuAdapterKind::Integrated);
435 assert_eq!(kind_of("AMD Radeon Graphics", Some(2 << 30)), GpuAdapterKind::Integrated);
436 assert_eq!(kind_of("NVIDIA GeForce RTX 3070", Some(8 << 30)), GpuAdapterKind::Discrete);
437 }
438
439 fn client(pid: u32, fd: u32, id: Option<u64>, busy: u64, vram: u64, gtt: u64) -> Scanned {
440 Scanned {
441 pid,
442 fd,
443 client: DrmClient {
444 driver: "amdgpu".into(),
445 pdev: Some("0000:03:00.0".into()),
446 id,
447 engines: vec![("gfx".into(), busy)],
448 dedicated: Some(vram),
449 shared: Some(gtt),
450 },
451 }
452 }
453
454 #[test]
455 fn the_first_read_has_no_use_and_the_second_has_the_time_the_engines_were_busy() {
456 let first = [client(10, 5, Some(1), 1_000_000_000, 100 << 20, 5 << 20)];
457 let (figs, next) = process_figures(&first, &HashMap::new(), None);
458 assert_eq!(figs, [ProcessFigures { pid: 10, use_pct: None, dedicated: Some(100 << 20), shared: Some(5 << 20) }]);
459 let second = [client(10, 5, Some(1), 1_500_000_000, 100 << 20, 5 << 20)];
461 let (figs, _) = process_figures(&second, &next, Some(Duration::from_secs(2)));
462 assert_eq!(figs[0].use_pct, Some(25.0));
463 }
464
465 #[test]
466 fn two_descriptors_on_one_client_are_one_client() {
467 let scanned = [client(10, 5, Some(1), 100, 64 << 20, 0), client(10, 9, Some(1), 100, 64 << 20, 0)];
468 let (figs, next) = process_figures(&scanned, &HashMap::new(), None);
469 assert_eq!(next.len(), 1);
470 assert_eq!(figs[0].dedicated, Some(64 << 20), "not 128 MiB");
471 assert_eq!(held_on(&scanned, "0000:03:00.0").0, Some(64 << 20));
472 }
473
474 #[test]
475 fn two_clients_of_one_process_add_up_within_a_whole() {
476 let prev: HashMap<ClientKey, u64> = [((10, "0000:03:00.0".to_string(), 1), 0), ((10, "0000:03:00.0".to_string(), 2), 0)].into();
477 let scanned = [client(10, 5, Some(1), 900_000_000, 1 << 20, 0), client(10, 6, Some(2), 800_000_000, 2 << 20, 0)];
478 let (figs, _) = process_figures(&scanned, &prev, Some(Duration::from_secs(1)));
479 assert_eq!(figs[0].use_pct, Some(100.0), "90% and 80% are not 170% of one GPU");
480 assert_eq!(figs[0].dedicated, Some(3 << 20));
481 }
482
483 #[test]
484 fn a_new_client_or_a_reads_too_close_together_leaves_use_unknown() {
485 let prev: HashMap<ClientKey, u64> = [((10, "0000:03:00.0".to_string(), 1), 0)].into();
486 let scanned = [client(10, 5, Some(1), 500, 0, 0), client(11, 5, Some(7), 500, 0, 0)];
487 let (figs, _) = process_figures(&scanned, &prev, Some(Duration::from_secs(1)));
488 assert!(figs.iter().find(|p| p.pid == 10).unwrap().use_pct.is_some());
489 assert_eq!(figs.iter().find(|p| p.pid == 11).unwrap().use_pct, None, "no earlier figure for this client");
490 let (figs, _) = process_figures(&scanned, &prev, Some(Duration::from_millis(10)));
491 assert!(figs.iter().all(|p| p.use_pct.is_none()), "10 ms between reads says nothing");
492 }
493
494 #[test]
495 fn a_counter_that_went_backwards_is_not_a_negative_use() {
496 let prev: HashMap<ClientKey, u64> = [((10, "0000:03:00.0".to_string(), 1), 9_000)].into();
497 let (figs, _) = process_figures(&[client(10, 5, Some(1), 100, 0, 0)], &prev, Some(Duration::from_secs(1)));
498 assert_eq!(figs[0].use_pct, Some(0.0));
499 }
500
501 #[test]
502 fn what_the_clients_hold_on_one_gpu_is_its_memory_where_it_can_say_none() {
503 let mut other = client(11, 5, Some(3), 0, 0, 7 << 20);
504 other.client.pdev = Some("0000:00:02.0".into());
505 let scanned = [client(10, 5, Some(1), 0, 0, 30 << 20), other];
506 assert_eq!(held_on(&scanned, "0000:03:00.0"), (Some(0), Some(30 << 20)));
507 assert_eq!(held_on(&scanned, "0000:00:02.0").1, Some(7 << 20));
508 assert_eq!(held_on(&scanned, "0000:ff:00.0"), (None, None));
509 }
510}