| 1 | mod amd_gpu_marketing; |
| 2 | |
| 3 | use std::{ |
| 4 | cell::RefCell, |
| 5 | fs::{self, read_to_string}, |
| 6 | num::NonZeroU64, |
| 7 | path::{Path, PathBuf}, |
| 8 | time::{Duration, Instant}, |
| 9 | }; |
| 10 | |
| 11 | use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet}; |
| 12 | |
| 13 | use super::linux::utils::is_device_awake; |
| 14 | use crate::{ |
| 15 | app::layout_manager::UsedWidgets, |
| 16 | collection::{memory::MemData, processes::Pid}, |
| 17 | utils::int_hash::{IntHashMap, IntHashSet}, |
| 18 | }; |
| 19 | |
| 20 | // TODO: May be able to clean up some of these, Option<Vec> for example is a bit |
| 21 | // redundant. |
| 22 | pub struct AmdGpuData { |
| 23 | pub memory: Option<Vec<(String, MemData)>>, |
| 24 | pub procs: Option<(u64, Vec<IntHashMap<Pid, (u64, u32)>>)>, |
| 25 | } |
| 26 | |
| 27 | pub struct AmdGpuMemory { |
| 28 | pub total: u64, |
| 29 | pub used: u64, |
| 30 | } |
| 31 | |
| 32 | #[derive(Debug, Clone, Default, Eq, PartialEq)] |
| 33 | pub struct AmdGpuProc { |
| 34 | pub vram_usage: u64, |
| 35 | pub gfx_usage: u64, |
| 36 | pub dma_usage: u64, |
| 37 | pub enc_usage: u64, |
| 38 | pub dec_usage: u64, |
| 39 | pub uvd_usage: u64, |
| 40 | pub vcn_usage: u64, |
| 41 | pub vpe_usage: u64, |
| 42 | pub compute_usage: u64, |
| 43 | } |
| 44 | |
| 45 | // TODO: This is kind of a hack. |
| 46 | thread_local! { |
| 47 | static PREV_PROC_DATA: RefCell<HashMap<PathBuf, IntHashMap<Pid, AmdGpuProc>>> = RefCell::new(HashMap::default()); |
| 48 | static LAST_CLEAN_COUNTER: RefCell<u32> = const { RefCell::new(0) }; |
| 49 | } |
| 50 | |
| 51 | fn get_amd_devs() -> Option<Vec<PathBuf>> { |
| 52 | let mut devices = Vec::new(); |
| 53 | |
| 54 | // read all PCI devices controlled by the AMDGPU module |
| 55 | let Ok(paths) = fs::read_dir("/sys/module/amdgpu/drivers/pci:amdgpu") else { |
| 56 | return None; |
| 57 | }; |
| 58 | |
| 59 | for path in paths { |
| 60 | let Ok(path) = path else { continue }; |
| 61 | |
| 62 | // test if it has a valid vendor path |
| 63 | let device_path = path.path(); |
| 64 | if !device_path.is_dir() { |
| 65 | continue; |
| 66 | } |
| 67 | |
| 68 | // Skip if asleep to avoid wakeups. |
| 69 | if !is_device_awake(&device_path) { |
| 70 | continue; |
| 71 | } |
| 72 | |
| 73 | // This will exist for GPUs but not others, this is how we find their kernel |
| 74 | // name. |
| 75 | let test_path = device_path.join("drm"); |
| 76 | if test_path.as_path().exists() { |
| 77 | devices.push(device_path); |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | if devices.is_empty() { |
| 82 | None |
| 83 | } else { |
| 84 | Some(devices) |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | pub fn get_amd_name(device_path: &Path) -> Option<String> { |
| 89 | // get revision and device ids from sysfs |
| 90 | let rev_path = device_path.join("revision"); |
| 91 | let dev_path = device_path.join("device"); |
| 92 | |
| 93 | if !rev_path.exists() || !dev_path.exists() { |
| 94 | return None; |
| 95 | } |
| 96 | |
| 97 | // read and remove newlines, 0x0 suffix. |
| 98 | let mut rev_data = read_to_string(rev_path).unwrap_or("0x00".to_string()); |
| 99 | let mut dev_data = read_to_string(dev_path).unwrap_or("0x0000".to_string()); |
| 100 | |
| 101 | rev_data = rev_data.trim_end().to_string(); |
| 102 | dev_data = dev_data.trim_end().to_string(); |
| 103 | |
| 104 | if let Some(stripped) = rev_data.strip_prefix("0x") { |
| 105 | rev_data = stripped.to_string(); |
| 106 | } |
| 107 | |
| 108 | if let Some(stripped) = dev_data.strip_prefix("0x") { |
| 109 | dev_data = stripped.to_string(); |
| 110 | } |
| 111 | |
| 112 | let revision_id = u32::from_str_radix(&rev_data, 16).unwrap_or(0); |
| 113 | let device_id = u32::from_str_radix(&dev_data, 16).unwrap_or(0); |
| 114 | |
| 115 | if device_id == 0 { |
| 116 | return None; |
| 117 | } |
| 118 | |
| 119 | // if it exists in our local database, use that name |
| 120 | amd_gpu_marketing::AMD_GPU_MARKETING_NAME |
| 121 | .iter() |
| 122 | .find(|(did, rid, _)| (did, rid) == (&device_id, &revision_id)) |
| 123 | .map(|tuple| tuple.2.to_string()) |
| 124 | } |
| 125 | |
| 126 | fn get_amd_vram(device_path: &Path) -> Option<AmdGpuMemory> { |
| 127 | // get vram memory info from sysfs |
| 128 | let vram_total_path = device_path.join("mem_info_vram_total"); |
| 129 | let vram_used_path = device_path.join("mem_info_vram_used"); |
| 130 | |
| 131 | let Ok(mut vram_total_data) = read_to_string(vram_total_path) else { |
| 132 | return None; |
| 133 | }; |
| 134 | let Ok(mut vram_used_data) = read_to_string(vram_used_path) else { |
| 135 | return None; |
| 136 | }; |
| 137 | |
| 138 | // read and remove newlines |
| 139 | vram_total_data = vram_total_data.trim_end().to_string(); |
| 140 | vram_used_data = vram_used_data.trim_end().to_string(); |
| 141 | |
| 142 | let Ok(vram_total) = vram_total_data.parse::<u64>() else { |
| 143 | return None; |
| 144 | }; |
| 145 | let Ok(vram_used) = vram_used_data.parse::<u64>() else { |
| 146 | return None; |
| 147 | }; |
| 148 | |
| 149 | Some(AmdGpuMemory { |
| 150 | total: vram_total, |
| 151 | used: vram_used, |
| 152 | }) |
| 153 | } |
| 154 | |
| 155 | // from amdgpu_top: https://github.com/Umio-Yasuno/amdgpu_top/blob/c961cf6625c4b6d63fda7f03348323048563c584/crates/libamdgpu_top/src/stat/fdinfo/proc_info.rs#L114 |
| 156 | fn diff_usage(pre: u64, cur: u64, interval: &Duration) -> u64 { |
| 157 | use std::ops::Mul; |
| 158 | |
| 159 | let diff_ns = if pre == 0 || cur < pre { |
| 160 | return 0; |
| 161 | } else { |
| 162 | cur.saturating_sub(pre) as u128 |
| 163 | }; |
| 164 | |
| 165 | diff_ns |
| 166 | .mul(100) |
| 167 | .checked_div(interval.as_nanos()) |
| 168 | .unwrap_or(0) as u64 |
| 169 | } |
| 170 | |
| 171 | // from amdgpu_top: https://github.com/Umio-Yasuno/amdgpu_top/blob/c961cf6625c4b6d63fda7f03348323048563c584/crates/libamdgpu_top/src/stat/fdinfo/proc_info.rs#L13-L27 |
| 172 | fn get_amdgpu_pid_fds(pid: Pid, device_path: Vec<PathBuf>) -> Option<Vec<u32>> { |
| 173 | let Ok(fd_list) = fs::read_dir(format!("/proc/{pid}/fd/")) else { |
| 174 | return None; |
| 175 | }; |
| 176 | |
| 177 | let valid_fds: Vec<u32> = fd_list |
| 178 | .filter_map(|fd_link| { |
| 179 | let dir_entry = fd_link.map(|fd_link| fd_link.path()).ok()?; |
| 180 | let link = fs::read_link(&dir_entry).ok()?; |
| 181 | |
| 182 | // e.g. "/dev/dri/renderD128" or "/dev/dri/card0" |
| 183 | if device_path.iter().any(|path| link.starts_with(path)) { |
| 184 | dir_entry.file_name()?.to_str()?.parse::<u32>().ok() |
| 185 | } else { |
| 186 | None |
| 187 | } |
| 188 | }) |
| 189 | .collect(); |
| 190 | |
| 191 | if valid_fds.is_empty() { |
| 192 | None |
| 193 | } else { |
| 194 | Some(valid_fds) |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | fn get_amdgpu_drm(device_path: &Path) -> Option<Vec<PathBuf>> { |
| 199 | let mut drm_devices = Vec::new(); |
| 200 | let drm_root = device_path.join("drm"); |
| 201 | |
| 202 | let Ok(drm_paths) = fs::read_dir(drm_root) else { |
| 203 | return None; |
| 204 | }; |
| 205 | |
| 206 | for drm_dir in drm_paths { |
| 207 | let Ok(drm_dir) = drm_dir else { |
| 208 | continue; |
| 209 | }; |
| 210 | |
| 211 | // attempt to get the device renderer name |
| 212 | let drm_name = drm_dir.file_name(); |
| 213 | let Some(drm_name) = drm_name.to_str() else { |
| 214 | continue; |
| 215 | }; |
| 216 | |
| 217 | // construct driver device path if valid |
| 218 | if !drm_name.starts_with("card") && !drm_name.starts_with("render") { |
| 219 | continue; |
| 220 | } |
| 221 | |
| 222 | drm_devices.push(PathBuf::from(format!("/dev/dri/{drm_name}"))); |
| 223 | } |
| 224 | |
| 225 | if drm_devices.is_empty() { |
| 226 | None |
| 227 | } else { |
| 228 | Some(drm_devices) |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | fn get_amd_fdinfo(device_path: &Path) -> Option<IntHashMap<Pid, AmdGpuProc>> { |
| 233 | let mut fdinfo = IntHashMap::default(); |
| 234 | |
| 235 | let drm_paths = get_amdgpu_drm(device_path)?; |
| 236 | |
| 237 | let Ok(proc_dir) = fs::read_dir("/proc") else { |
| 238 | return None; |
| 239 | }; |
| 240 | |
| 241 | let pids: Vec<Pid> = proc_dir |
| 242 | .filter_map(|dir_entry| { |
| 243 | // check if pid is valid |
| 244 | let dir_entry = dir_entry.ok()?; |
| 245 | let metadata = dir_entry.metadata().ok()?; |
| 246 | |
| 247 | if !metadata.is_dir() { |
| 248 | return None; |
| 249 | } |
| 250 | |
| 251 | let pid = dir_entry.file_name().to_str()?.parse::<Pid>().ok()?; |
| 252 | |
| 253 | // skip init process |
| 254 | if pid == 1 { |
| 255 | return None; |
| 256 | } |
| 257 | |
| 258 | Some(pid) |
| 259 | }) |
| 260 | .collect(); |
| 261 | |
| 262 | for pid in pids { |
| 263 | // collect file descriptors that point to our device renderers |
| 264 | let Some(fds) = get_amdgpu_pid_fds(pid, drm_paths.clone()) else { |
| 265 | continue; |
| 266 | }; |
| 267 | |
| 268 | let mut usage: AmdGpuProc = Default::default(); |
| 269 | |
| 270 | let mut observed_ids: HashSet<usize> = HashSet::default(); |
| 271 | |
| 272 | for fd in fds { |
| 273 | let fdinfo_path = format!("/proc/{pid}/fdinfo/{fd}"); |
| 274 | let Ok(fdinfo_data) = read_to_string(fdinfo_path) else { |
| 275 | continue; |
| 276 | }; |
| 277 | |
| 278 | let mut fdinfo_lines = fdinfo_data |
| 279 | .lines() |
| 280 | .skip_while(|l| !l.starts_with("drm-client-id")); |
| 281 | if let Some(id) = fdinfo_lines.next().and_then(|fdinfo_line| { |
| 282 | const LEN: usize = "drm-client-id:\t".len(); |
| 283 | fdinfo_line.get(LEN..)?.parse().ok() |
| 284 | }) { |
| 285 | if !observed_ids.insert(id) { |
| 286 | continue; |
| 287 | } |
| 288 | } else { |
| 289 | continue; |
| 290 | } |
| 291 | |
| 292 | for fdinfo_line in fdinfo_lines { |
| 293 | let Some(fdinfo_separator_index) = fdinfo_line.find(':') else { |
| 294 | continue; |
| 295 | }; |
| 296 | |
| 297 | let (fdinfo_keyword, mut fdinfo_value) = |
| 298 | fdinfo_line.split_at(fdinfo_separator_index); |
| 299 | fdinfo_value = &fdinfo_value[1..]; |
| 300 | |
| 301 | fdinfo_value = fdinfo_value.trim(); |
| 302 | if let Some(fdinfo_value_space_index) = fdinfo_value.find(' ') { |
| 303 | fdinfo_value = &fdinfo_value[..fdinfo_value_space_index]; |
| 304 | }; |
| 305 | |
| 306 | let Ok(fdinfo_value_num) = fdinfo_value.parse::<u64>() else { |
| 307 | continue; |
| 308 | }; |
| 309 | |
| 310 | match fdinfo_keyword { |
| 311 | "drm-engine-gfx" => usage.gfx_usage += fdinfo_value_num, |
| 312 | "drm-engine-dma" => usage.dma_usage += fdinfo_value_num, |
| 313 | "drm-engine-dec" => usage.dec_usage += fdinfo_value_num, |
| 314 | "drm-engine-enc" => usage.enc_usage += fdinfo_value_num, |
| 315 | "drm-engine-enc_1" => usage.uvd_usage += fdinfo_value_num, |
| 316 | "drm-engine-jpeg" => usage.vcn_usage += fdinfo_value_num, |
| 317 | "drm-engine-vpe" => usage.vpe_usage += fdinfo_value_num, |
| 318 | "drm-engine-compute" => usage.compute_usage += fdinfo_value_num, |
| 319 | "drm-memory-vram" => usage.vram_usage += fdinfo_value_num << 10, // KiB -> B |
| 320 | _ => {} |
| 321 | }; |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | if usage != Default::default() { |
| 326 | fdinfo.insert(pid, usage); |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | Some(fdinfo) |
| 331 | } |
| 332 | |
| 333 | pub fn get_amd_vecs(widgets_to_harvest: &UsedWidgets, prev_time: Instant) -> Option<AmdGpuData> { |
| 334 | let device_path_list = get_amd_devs()?; |
| 335 | let interval = Instant::now().duration_since(prev_time); |
| 336 | let num_gpu = device_path_list.len(); |
| 337 | let mut mem_vec = Vec::with_capacity(num_gpu); |
| 338 | let mut proc_vec = Vec::with_capacity(num_gpu); |
| 339 | let mut total_mem = 0; |
| 340 | |
| 341 | PREV_PROC_DATA.with_borrow_mut(|prev_proc_data| { |
| 342 | let device_path_set = device_path_list.iter().cloned().collect::<HashSet<_>>(); |
| 343 | prev_proc_data.retain(|k, _| device_path_set.contains(k)); |
| 344 | }); |
| 345 | |
| 346 | for device_path in device_path_list { |
| 347 | let device_name = get_amd_name(&device_path) |
| 348 | .unwrap_or(amd_gpu_marketing::AMDGPU_DEFAULT_NAME.to_string()); |
| 349 | |
| 350 | if let Some(mem) = get_amd_vram(&device_path) { |
| 351 | if widgets_to_harvest.use_mem |
| 352 | && let Some(total_bytes) = NonZeroU64::new(mem.total) |
| 353 | { |
| 354 | mem_vec.push(( |
| 355 | device_name.clone(), |
| 356 | MemData { |
| 357 | total_bytes, |
| 358 | used_bytes: mem.used, |
| 359 | }, |
| 360 | )); |
| 361 | } |
| 362 | |
| 363 | total_mem += mem.total |
| 364 | } |
| 365 | |
| 366 | if widgets_to_harvest.use_proc |
| 367 | && let Some(procs) = get_amd_fdinfo(&device_path) |
| 368 | { |
| 369 | PREV_PROC_DATA.with_borrow_mut(|prev_proc_data| { |
| 370 | let prev_fdinfo = prev_proc_data.entry(device_path).or_default(); |
| 371 | let mut seen_pids = IntHashSet::default(); |
| 372 | |
| 373 | let mut procs_map = IntHashMap::default(); |
| 374 | for (proc_pid, proc_usage) in procs { |
| 375 | seen_pids.insert(proc_pid); |
| 376 | if let Some(prev_usage) = prev_fdinfo.get_mut(&proc_pid) { |
| 377 | // calculate deltas |
| 378 | let gfx_usage = |
| 379 | diff_usage(prev_usage.gfx_usage, proc_usage.gfx_usage, &interval); |
| 380 | let dma_usage = |
| 381 | diff_usage(prev_usage.dma_usage, proc_usage.dma_usage, &interval); |
| 382 | let enc_usage = |
| 383 | diff_usage(prev_usage.enc_usage, proc_usage.enc_usage, &interval); |
| 384 | let dec_usage = |
| 385 | diff_usage(prev_usage.dec_usage, proc_usage.dec_usage, &interval); |
| 386 | let uvd_usage = |
| 387 | diff_usage(prev_usage.uvd_usage, proc_usage.uvd_usage, &interval); |
| 388 | let vcn_usage = |
| 389 | diff_usage(prev_usage.vcn_usage, proc_usage.vcn_usage, &interval); |
| 390 | let vpe_usage = |
| 391 | diff_usage(prev_usage.vpe_usage, proc_usage.vpe_usage, &interval); |
| 392 | |
| 393 | // combined usage |
| 394 | let gpu_util_wide = gfx_usage |
| 395 | + dma_usage |
| 396 | + enc_usage |
| 397 | + dec_usage |
| 398 | + uvd_usage |
| 399 | + vcn_usage |
| 400 | + vpe_usage; |
| 401 | |
| 402 | let gpu_util: u32 = gpu_util_wide.try_into().unwrap_or(0); |
| 403 | |
| 404 | if gpu_util > 0 || proc_usage.vram_usage > 0 { |
| 405 | procs_map.insert(proc_pid, (proc_usage.vram_usage, gpu_util)); |
| 406 | } |
| 407 | |
| 408 | *prev_usage = proc_usage; |
| 409 | } else { |
| 410 | prev_fdinfo.insert(proc_pid, proc_usage); |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | prev_fdinfo.retain(|k, _| seen_pids.contains(k)); |
| 415 | |
| 416 | if !procs_map.is_empty() { |
| 417 | proc_vec.push(procs_map); |
| 418 | } |
| 419 | }); |
| 420 | } |
| 421 | } |
| 422 | |
| 423 | // Bit of a hacky way to keep this trimmed. Ain't pretty but it should work. |
| 424 | LAST_CLEAN_COUNTER.with_borrow_mut(|counter| { |
| 425 | *counter += 1; |
| 426 | |
| 427 | if *counter >= 300 { |
| 428 | PREV_PROC_DATA.with_borrow_mut(|prev_proc_data| { |
| 429 | for prev_fdinfo in prev_proc_data.values_mut() { |
| 430 | prev_fdinfo.shrink_to_fit(); |
| 431 | } |
| 432 | |
| 433 | prev_proc_data.shrink_to_fit(); |
| 434 | }); |
| 435 | |
| 436 | *counter = 0; |
| 437 | } |
| 438 | }); |
| 439 | |
| 440 | Some(AmdGpuData { |
| 441 | memory: (!mem_vec.is_empty()).then_some(mem_vec), |
| 442 | procs: (!proc_vec.is_empty()).then_some((total_mem, proc_vec)), |
| 443 | }) |
| 444 | } |