Skip to content

A GPU task manager for Windows, Linux, and WSL: per-process VRAM, GPU activity, and LLM model/KV-cache insights (Windows AMD and NVIDIA).

Python

Report unknown DRM process data instead of guessing

Pinta365b6f34e15d1d1
diff --git a/README.md b/README.md
index cbc21f7..d00b50a 100644
--- a/README.md
+++ b/README.md
@@ -158,7 +158,7 @@ kernel already exposes what's needed.
|---|---|
| Device VRAM, GTT, load, temperature, power, clocks, fan, PCIe link | `/sys/class/drm/card*/device` and its `hwmon` |
| Per-process VRAM and GTT | `drm-resident-vram` / `drm-resident-gtt` (older kernels: `drm-memory-*`) and `drm-shared-*` in `/proc/<pid>/fdinfo/<fd>` |
-| Per-process engine load (gfx, compute, video) | `drm-engine-*` busy time, sampled twice; `n/a` for ROCm/HIP processes (see below) |
+| Per-process engine load (gfx, compute, video) | `drm-engine-*` busy time, sampled twice (`n/a` until a new client has two samples); `n/a` for ROCm/HIP processes (see below) |
GTT is GPU-accessible system RAM, so it fills the SPILL column (and `shared (in system RAM)` for
the device), like WDDM's non-local usage. On an APU (an integrated GPU, detected by amdgpu not
@@ -166,7 +166,9 @@ reporting a VRAM vendor, a heuristic validated on one APU) GTT is the GPU's norm
is only a RAM carve-out, so GTT is still shown but never flagged as spill, and an LLM's memory is its
VRAM plus GTT. The SDMA engine (`dma`) fills the COPY column. Paged stays blank: there is no commit
counter. A DRM client
-shared between processes (fd passing, fork) is counted once, for the lowest PID. A *buffer* shared
+held by several processes (fd passing, fork; 1Password and its crash handler on the test desktop) has one
+set of counters and nothing says which process uses it, so each is listed with VRAM and GPU% `n/a` and the
+bytes stay in *unattributed*. A *buffer* shared
between clients (a window a compositor imports, for example) is resident in each of them, and fdinfo
does not say which one owns it. VRAM therefore shows each process's private bytes (resident minus
shared), which add up without double counting; shared buffers stay in *unattributed* and are listed
@@ -175,7 +177,7 @@ of SPILL the same way. Older kernels whose amdgpu fdinfo has no `drm-shared-*` k
split, so per-process VRAM shows `n/a` there instead of double counting. amdgpu has no device-wide
video engine counter, so the device's encode/decode load stays N/A; per-process video load is
measured. On VCN 4 and later (RDNA3 and newer, including the RX 9070) decode and encode share one
-ring, so it is reported as `video` rather than split. Only processes you can inspect are listed; run with `sudo` to include other users'. `--gpu 1`
+ring, so it is reported as `video` rather than split. Only processes you can inspect are listed; the header and JSON (`process_status`) say how many could not be, and `sudo` includes other users'. `--gpu 1`
selects the next card, such as an APU's integrated GPU next to a discrete one. A ROCm/HIP process
(tagged `HIP`) has its VRAM in fdinfo like any other. Its GPU% is not: HIP submits compute through user-mode queues on `/dev/kfd`, which the kernel
does not time per process, so a process holding `/dev/kfd` shows engines as `n/a` (`null` in JSON)
@@ -545,7 +547,7 @@ Identification is designed to stay cheap. Measured on one Windows machine:
| GGUF header, model-store manifests | ms, cached | Once per file / every 60 s |
| Local API probes | ms, local only | llama-server `/v1/models` only when its model path changes |
| `psutil.open_files()` | 0.6-2.5 s per process | Never |
-| AMD on Linux: DRM fdinfo scan (`readlink` every fd, read fdinfo of `/dev/dri` ones) | ~9 ms for ~8,000 fds (Linux desktop) | Every refresh, only when an amdgpu card is shown |
+| AMD on Linux: DRM fdinfo scan (`readlink` every fd, read fdinfo of `/dev/dri` ones) | ~9 ms for ~8,000 fds (Linux desktop) | Every refresh, only when an amdgpu card is shown; listing fds is bounded to 50 ms in the TUI and resumes next refresh, known GPU fds are still read |
| macOS: `ioreg` device stats + Metal clients | ~10 ms | Every refresh |
| macOS: memory-map scan (`proc_pidinfo` region walk) | ~4 ms per process | Same policy as the memory-map scan above |
| macOS: `footprint` GPU memory | ~70 ms per process, background thread | Busy and new processes every ~2 s, idle ones every 30 s (54 runs in 40 s with 27 GPU processes, M4 Mac mini) |
diff --git a/src/gputaskman/app.py b/src/gputaskman/app.py
index 8f934ae..5e0712e 100644
--- a/src/gputaskman/app.py
+++ b/src/gputaskman/app.py
@@ -20,7 +20,7 @@ from textual.worker import get_current_worker
from .collector import BACKEND, Collector, ProcRow, Snapshot
from .llm import gb
from .nvml import NvDevice, format_metric
-from .report import (DRM_UNSPLIT_NOTE, METAL_NOTE, WSL_EMPTY, has_engine_counters, has_spill_counters, has_wddm_counters,
+from .report import (DRM_SHARED_CLIENT_NOTE, DRM_UNSPLIT_NOTE, METAL_NOTE, WSL_EMPTY, has_engine_counters, has_spill_counters, has_wddm_counters,
inferred_note, vram_label, wsl_note)
KIND_STYLE = {
@@ -81,9 +81,10 @@ candidates remain unproven; engine activity is measured per process, not per mod
**Linux / WSL:** on native Linux, per-process VRAM and SM/encoder/decoder load come from NVML
(no spill or commit counters exist there, so those columns stay blank). **AMD GPUs on Linux**
(`amdgpu`) use sysfs for the device and DRM fdinfo (`/proc/<pid>/fdinfo`) per process: VRAM,
-GTT (GPU memory in system RAM, shown as SPILL), and gfx/compute/video engine time (`n/a` for ROCm/HIP
-processes: their compute runs on `/dev/kfd` queues the kernel doesn't time per process). Only processes
-you can inspect are listed; run with `sudo` to see other users'. Under **WSL**, Windows
+GTT (GPU memory in system RAM, shown as SPILL), and gfx/compute/video engine time (`n/a` for a new client's
+first sample and for ROCm/HIP processes: their compute runs on `/dev/kfd` queues the kernel doesn't time per
+process). A client several processes share shows `n/a` for each of them. Only processes you can inspect are
+listed, and the header says how many it couldn't; run with `sudo` to see other users'. Under **WSL**, Windows
charges all Linux GPU memory to the VM (`vmwp.exe`), so VRAM and load are device-wide only; rows
are Linux processes with `/dev/dxg` open and show `n/a` rather than a made-up share. When WSL
interop is enabled, the Windows host's counters are read through `powershell.exe`: **WSL VM**
@@ -353,6 +354,8 @@ class GpuTaskManager(App):
legend.append("\n " + wsl_note(s), style="grey62")
if s.backend == "metal":
legend.append("\n " + METAL_NOTE, style="grey62")
+ if s.process_status:
+ legend.append(f"\n DRM process scan: {s.process_status}.", style="grey62")
lines = [head, vram, legend]
if nv and s.backend == "metal":
@@ -537,7 +540,7 @@ class GpuTaskManager(App):
elif s.wsl_split:
out.append(Text(f"No per-process VRAM: {s.wsl_split}.", style="grey62"))
elif s.backend == "drm":
- out.append(Text(DRM_UNSPLIT_NOTE, style="grey62"))
+ out.append(Text(DRM_SHARED_CLIENT_NOTE if r.gpu.shared_client else DRM_UNSPLIT_NOTE, style="grey62"))
elif s.backend == "metal":
out.append(Text("GPU memory n/a: footprint can't read other users' processes without root "
"(or hasn't measured this one yet). GPU% comes from Metal's per-process GPU time.",
@@ -546,7 +549,7 @@ class GpuTaskManager(App):
out.append(Text(f"+ {gb(r.gpu.shared_vram)} in VRAM buffers shared with other processes (e.g. windows a "
"compositor imports), not counted above: the driver doesn't say which process owns a shared "
"buffer, so they stay in 'unattributed'.", style="grey62"))
- if s.backend == "drm" and "engine" not in r.gpu.available:
+ if s.backend == "drm" and r.gpu.kfd:
out.append(Text("Engines n/a: this process uses ROCm/HIP (/dev/kfd), whose compute queues the kernel doesn't "
"time per process. The device's AMD gfx load includes its work.", style="grey62"))
if wddm and r.gpu.paged_out >= 64 << 20:
diff --git a/src/gputaskman/collector.py b/src/gputaskman/collector.py
index b3a83e6..51fb614 100644
--- a/src/gputaskman/collector.py
+++ b/src/gputaskman/collector.py
@@ -112,6 +112,7 @@ class Snapshot:
shared_used: int | None
procs: list[ProcRow] = field(default_factory=list)
backend: str = "wddm" # wddm (Windows) | nvml (native Linux, NVIDIA) | drm (native Linux, AMD) | wsl (device-wide only) | metal (macOS)
+ process_status: str = "" # amdgpu only: what the DRM process scan couldn't cover; empty when it saw everything
host_status: str = "" # WSL only: Windows host counters via interop -- ok | starting | off (...) | ...
wsl_split: str = "" # WSL only: why Linux rows have no (inferred) VRAM, when they don't
# False on an APU (amdgpu iGPU): its GTT is ordinary GPU memory, not spill from a full VRAM.
@@ -194,6 +195,8 @@ class Collector:
self.drm_card = next((c for c in drm.cards if c.key == self.adapter.luid), None)
if drm is not None and self.drm_card is None:
self.counters.drm = None # an NVIDIA GPU is shown: don't walk every process's fds for nothing
+ elif drm is not None and scan_budget is None:
+ drm.scan_budget = None # one-shot output sees every process
self.inspector = ProcInspector()
self.prober = ServerProber()
self.scan_budget = scan_budget # None = scan every candidate now (one-shot output)
@@ -258,6 +261,8 @@ class Collector:
)
snap.host_status = self.host_status
+ if self.drm_card is not None:
+ snap.process_status = self.counters.drm.status
live = [(pid, g) for pid, g in procs.items() if _is_live(g)]
live.sort(key=lambda x: -(x[1].shown_vram or 0))
for pid, g in live:
diff --git a/src/gputaskman/drm.py b/src/gputaskman/drm.py
index e62f1a8..517f1cb 100644
--- a/src/gputaskman/drm.py
+++ b/src/gputaskman/drm.py
@@ -11,6 +11,7 @@ from __future__ import annotations
import os
import re
import time
+from bisect import bisect_left
from dataclasses import dataclass
from functools import lru_cache
@@ -20,6 +21,7 @@ from .telemetry import DeviceTelemetry
from .pdh import AdapterGpu, ProcGpu
DRIVERS = ("amdgpu",)
+SCAN_BUDGET = 0.05 # seconds per refresh for listing process fds (one-shot output: no limit)
_SIZE_UNITS = {
"": 1,
@@ -386,15 +388,21 @@ class DrmCounters:
"""Same interface as pdh.GpuCounters: sample() -> ({adapter key: {pid: ProcGpu}}, {adapter key: AdapterGpu})."""
def __init__(self, found: list[DrmCard] | None = None, proc: str = "/proc",
- clock=time.monotonic_ns) -> None:
+ clock=time.monotonic_ns, timer=time.perf_counter) -> None:
self.cards = list(found) if found is not None else cards()
self.ok = bool(self.cards)
self._proc = proc
self._clock = clock
self._prev: dict[tuple, dict[str, int]] = {}
self._prev_ts: int | None = None
+ self._timer = timer
+ self._known: dict[int, tuple[list[str], bool]] = {}
+ self._cursor = 0
+ self.status = "" # what the last scan couldn't cover, for the UI and JSON; empty when it saw everything
+ self.scan_budget: float | None = None # the baseline below covers every process
if self.ok:
self.sample() # engine load is a rate: take the baseline now, like the WDDM counters do
+ self.scan_budget = SCAN_BUDGET
def _adapters(self) -> dict[int, AdapterGpu]:
out: dict[int, AdapterGpu] = {}
@@ -407,51 +415,83 @@ class DrmCounters:
)
return out
- def _clients(self) -> tuple[dict[tuple, tuple[int, int, dict]], set[int]]:
- """One entry per DRM client: (lowest pid, lowest fd number, fdinfo); plus the pids holding /dev/kfd."""
+ def _scan_pid(self, pid: int) -> tuple[list[str], bool] | None:
+ """(this process's /dev/dri fd names, whether it holds /dev/kfd); None when its fds can't be inspected."""
+ dri: list[str] = []
+ holds_kfd = False
+ try:
+ fds = os.scandir(os.path.join(self._proc, str(pid), "fd"))
+ except PermissionError:
+ return None
+ except OSError:
+ return dri, holds_kfd # gone since /proc was listed
+ with fds:
+ for fd in fds:
+ try:
+ target = os.readlink(fd.path)
+ except OSError:
+ continue
+ if target == "/dev/kfd":
+ holds_kfd = True
+ elif target.startswith("/dev/dri/"):
+ dri.append(fd.name)
+ return dri, holds_kfd
+
+ def _clients(self) -> tuple[dict[tuple, tuple[set[int], dict]], set[int]]:
+ """One entry per DRM client: (the pids holding it, fdinfo); plus the pids holding /dev/kfd.
+
+ Listing a process's fds is the costly part, so it is bounded by scan_budget, resuming where the last refresh
+ stopped. Past the budget a process keeps its last known fds, whose fdinfo is still read: rows and counters
+ stay current, and only a GPU client opened since the last pass can show up a refresh or two late.
+ """
by_pdev = {c.pdev: c.key for c in self.cards}
- clients: dict[tuple, tuple[int, int, dict]] = {}
+ clients: dict[tuple, tuple[set[int], dict]] = {}
kfd: set[int] = set()
+ self.status = ""
try:
- pids = os.scandir(self._proc)
+ with os.scandir(self._proc) as entries:
+ pids = sorted(int(e.name) for e in entries if e.name.isdigit())
except OSError:
+ self.status = f"{self._proc} is not readable"
return clients, kfd
- with pids:
- for pid_entry in pids:
- if not pid_entry.name.isdigit():
- continue
- pid = int(pid_entry.name)
+ start = bisect_left(pids, self._cursor)
+ deadline = None if self.scan_budget is None else self._timer() + self.scan_budget
+ known: dict[int, tuple[list[str], bool]] = {}
+ denied = skipped = 0
+ self._cursor = 0
+ for pid in pids[start:] + pids[:start]:
+ if deadline is not None and (skipped or self._timer() >= deadline):
+ if not skipped:
+ self._cursor = pid
+ skipped += 1
+ entry = self._known.get(pid)
+ else:
+ entry = self._scan_pid(pid)
+ denied += entry is None
+ if entry is None:
+ continue
+ known[pid] = entry
+ if entry[1]:
+ kfd.add(pid)
+ for name in entry[0]:
try:
- fds = os.scandir(os.path.join(pid_entry.path, "fd"))
+ with open(os.path.join(self._proc, str(pid), "fdinfo", name),
+ encoding="utf-8", errors="replace") as f:
+ info = parse_fdinfo(f.read())
except OSError:
continue
- with fds:
- for fd in fds:
- try:
- target = os.readlink(fd.path)
- except OSError:
- continue
- if target == "/dev/kfd":
- kfd.add(pid)
- if not target.startswith("/dev/dri/"):
- continue
- try:
- with open(os.path.join(pid_entry.path, "fdinfo", fd.name),
- encoding="utf-8", errors="replace") as f:
- info = parse_fdinfo(f.read())
- except OSError:
- continue
- if not info or info["driver"] not in DRIVERS or info["pdev"] not in by_pdev:
- continue
- fd_number = int(fd.name) if fd.name.isdigit() else 0
- client_id = info["client_id"]
- if client_id is None:
- key = (info["pdev"], pid, fd_number)
- else:
- key = (info["pdev"], client_id)
- best = clients.get(key)
- if best is None or (pid, fd_number) < (best[0], best[1]):
- clients[key] = (pid, fd_number, info)
+ if not info or info["driver"] not in DRIVERS or info["pdev"] not in by_pdev:
+ continue
+ client_id = info["client_id"]
+ key = (info["pdev"], client_id) if client_id is not None else (info["pdev"], pid, name)
+ clients.setdefault(key, (set(), info))[0].add(pid)
+ self._known = known
+ notes = []
+ if skipped:
+ notes.append(f"scan budget reached, {skipped} processes keep their last known GPU fds this refresh")
+ if denied:
+ notes.append(f"{denied} processes not inspectable (other users' or kernel threads; sudo includes them)")
+ self.status = "; ".join(notes)
return clients, kfd
def sample(self) -> tuple[dict[int, dict[int, ProcGpu]], dict[int, AdapterGpu]]:
@@ -463,13 +503,28 @@ class DrmCounters:
clients, kfd = self._clients()
delta = now - self._prev_ts if self._prev_ts is not None else 0
previous: dict[tuple, dict[str, int]] = {}
- for client_key, (pid, _fd, info) in clients.items():
+ for client_key, (owners, info) in clients.items():
key = by_pdev[info["pdev"]]
- # No commit counter in fdinfo, so Paged stays unavailable rather than 0. ROCm/HIP (a /dev/kfd
- # holder) submits compute through user-mode KFD queues the kernel doesn't time per process, so
- # its engine load is unknown, not 0 (AGENTS.md rule 2); its VRAM is still in fdinfo.
- available = {"dedicated", "shared"} if pid in kfd else {"dedicated", "shared", "engine"}
- proc = procs[key].setdefault(pid, ProcGpu(attributed=True, available=available))
+ previous[client_key] = dict(info["engines"])
+ rows = []
+ for pid in owners:
+ # No commit counter in fdinfo, so Paged stays unavailable rather than 0. ROCm/HIP (a /dev/kfd
+ # holder) submits compute through user-mode KFD queues the kernel doesn't time per process, so
+ # its engine load is unknown, not 0 (AGENTS.md rule 2); its VRAM is still in fdinfo.
+ available = {"dedicated", "shared"} if pid in kfd else {"dedicated", "shared", "engine"}
+ proc = procs[key].setdefault(pid, ProcGpu(attributed=True, available=available))
+ proc.kfd = pid in kfd
+ rows.append(proc)
+ if len(owners) > 1:
+ # One client held by several processes (fd passing, fork): nothing says which of them uses it,
+ # so each is listed without counters instead of charging one by guess (rules 1 and 5). Its bytes
+ # stay in the adapter's unattributed part, like a shared buffer's, so the other rows still add up.
+ for proc in rows:
+ proc.attributed = False
+ proc.shared_client = True
+ proc.available -= {"shared", "engine"}
+ continue
+ proc = rows[0]
# A buffer shared between clients is resident in each of them and fdinfo doesn't say which owns it.
# Only private bytes are charged (AGENTS.md rule 1); shared ones are reported apart, owner unknown.
if info["shared_vram"] is None:
@@ -483,19 +538,17 @@ class DrmCounters:
proc.shared_vram += shared
proc.shared += max(float(info["gtt"]) - float(info["shared_gtt"] or 0), 0.0)
old = self._prev.get(client_key)
+ if old is None or delta <= 0:
+ proc.available.discard("engine") # a rate needs two samples: unknown, not 0 (rule 2)
+ continue
engines: dict[str, float] = {}
for name, ns in info["engines"].items():
- pct = 0.0
- if old is not None and delta > 0 and name in old:
- elapsed = ns - old[name]
- if elapsed > 0:
- pct = 100.0 * elapsed / delta
- pct = min(100.0, max(0.0, pct))
+ # amdgpu omits an engine until it has run, so a missing earlier value really is 0.
+ pct = min(100.0, max(0.0, 100.0 * (ns - old.get(name, 0)) / delta))
engine = _engine_key(name, info["pdev"] in unified)
engines[engine] = engines.get(engine, 0.0) + pct
for engine, pct in engines.items():
proc.engines[engine] = min(100.0, proc.engines[engine] + pct)
- previous[client_key] = dict(info["engines"])
self._prev = previous
self._prev_ts = now
return procs, adapters
diff --git a/src/gputaskman/pdh.py b/src/gputaskman/pdh.py
index ce40615..392bf84 100644
--- a/src/gputaskman/pdh.py
+++ b/src/gputaskman/pdh.py
@@ -87,6 +87,8 @@ class ProcGpu:
# amdgpu (DRM fdinfo): resident VRAM in buffers shared with other DRM clients, kept out of `dedicated`. fdinfo
# can't say which client owns a shared buffer, so it is shown apart and left in the adapter's unattributed part.
shared_vram: float = 0.0
+ kfd: bool = False # amdgpu: holds /dev/kfd (ROCm/HIP), whose compute isn't timed per process
+ shared_client: bool = False # amdgpu: holds a DRM client other processes hold too, so its counters have no one owner
@property
def shown_vram(self) -> float | None:
diff --git a/src/gputaskman/report.py b/src/gputaskman/report.py
index 48717d4..5ea9117 100644
--- a/src/gputaskman/report.py
+++ b/src/gputaskman/report.py
@@ -63,6 +63,10 @@ DRM_UNSPLIT_NOTE = ("VRAM n/a: this kernel's amdgpu fdinfo has no drm-shared-* k
"kernels report shared buffers separately.")
+DRM_SHARED_CLIENT_NOTE = ("VRAM and GPU% n/a: this process holds a DRM client other processes hold too (fd passing, "
+ "fork). fdinfo counts the client once and doesn't say which of them uses it.")
+
+
def inferred_note(g) -> str:
return ORDER_NOTE if g.inferred_by == "order" else INFERRED_NOTE
@@ -117,6 +121,7 @@ def to_dict(s: Snapshot) -> dict:
"adapter": dataclasses.asdict(s.adapter) if s.adapter else None,
"vram_total": s.vram_total, "vram_used": s.vram_used, "shared_used": s.shared_used,
"attributed": s.attributed, "backend": s.backend, "host_status": s.host_status or None,
+ "process_status": s.process_status or None,
"wsl_split": s.wsl_split or None, "device": nv, "processes": procs,
}
@@ -180,8 +185,12 @@ def to_text(s: Snapshot, limit: int = 30) -> str:
out.append(INFERRED_NOTE)
if any(p.gpu.inferred_by == "order" for p in shown):
out.append(ORDER_NOTE)
- if s.backend == "drm" and any(not p.host and not p.gpu.attributed for p in shown):
+ if s.backend == "drm" and any(not p.host and not p.gpu.attributed and not p.gpu.shared_client for p in shown):
out.append(DRM_UNSPLIT_NOTE)
+ if s.backend == "drm" and any(not p.host and p.gpu.shared_client for p in shown):
+ out.append(DRM_SHARED_CLIENT_NOTE)
+ if s.process_status:
+ out.append(f"DRM process scan: {s.process_status}.")
if s.backend == "wsl" and s.wsl_split and any(not p.host and not p.gpu.attributed and p.gpu.inferred is None
for p in s.procs):
out.append(f"Linux VRAM split: {s.wsl_split}")
diff --git a/tests/test_drm.py b/tests/test_drm.py
index 114049b..923896c 100644
--- a/tests/test_drm.py
+++ b/tests/test_drm.py
@@ -262,7 +262,6 @@ class DrmCountersTests(unittest.TestCase):
proc = tmp / "proc"
_write_fd(proc, 100, 10, _fdinfo(26, pdev, gfx=1_000_000_000, vram=3, gtt=2, shared_vram=2))
- _write_fd(proc, 200, 11, _fdinfo(26, pdev, gfx=1_000_000_000, vram=1, gtt=2))
_write_fd(proc, 300, 12, _fdinfo(27, "0000:ff:00.0", gfx=9_999_999_999, vram=4))
# DRM-looking fdinfo behind a non-DRM fd: the /proc/<pid>/fd target rules it out.
_write_fd(proc, 400, 13, _fdinfo(28, pdev, gfx=9_999_999_999, vram=4), target="socket:[123]")
@@ -274,7 +273,6 @@ class DrmCountersTests(unittest.TestCase):
procs, adapters = counters.sample()
self.assertEqual(list(procs), [card.key])
self.assertIn(100, procs[card.key])
- self.assertNotIn(200, procs[card.key]) # same client, counted once, on the lowest pid
self.assertNotIn(300, procs[card.key]) # unknown pdev
self.assertNotIn(400, procs[card.key]) # non-DRM fd
self.assertEqual(procs[card.key][100].dedicated, 1024) # private only: 3 KiB resident - 2 KiB shared
@@ -373,6 +371,109 @@ class DrmEdgeCaseTests(unittest.TestCase):
self.assertEqual(drm._vcn_major(str(Path(tmp) / "none")), 0)
+class DrmScanTests(unittest.TestCase):
+ PDEV = "0000:03:00.0"
+
+ def _setup(self, tmp, timer=None):
+ dev = tmp / "drm" / "card1" / "device"
+ dev.mkdir(parents=True)
+ card = _card(dev, self.PDEV)
+ proc = tmp / "proc"
+ proc.mkdir()
+ return card, proc, {} if timer is None else {"timer": timer}
+
+ def test_new_client_engine_load_is_unknown_until_two_samples(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ card, proc, kw = self._setup(Path(tmp))
+ _write_fd(proc, 100, 5, _fdinfo(1, self.PDEV, gfx=0, vram=4096))
+ times = iter([0, 1_000_000_000, 2_000_000_000, 3_000_000_000])
+ counters = drm.DrmCounters(found=[card], proc=str(proc), clock=lambda: next(times), **kw)
+ _write_fd(proc, 200, 5, _fdinfo(2, self.PDEV, gfx=500_000_000, vram=4096))
+ procs = counters.sample()[0][card.key]
+ self.assertIn("engine", procs[100].available) # in the baseline: a real, measured idle
+ self.assertNotIn("engine", procs[200].available) # first seen now: unknown, not 0
+ self.assertEqual(procs[200].dedicated, 4096 * 1024) # memory doesn't need two samples
+ self.assertFalse(procs[200].kfd)
+ _write_fd(proc, 200, 5, _fdinfo(2, self.PDEV, gfx=1_000_000_000, vram=4096))
+ self.assertEqual(counters.sample()[0][card.key][200].engines["3d"], 50.0)
+
+ def test_engine_first_reported_counts_from_zero(self):
+ # amdgpu omits an engine until it has run, so its whole counter is new work.
+ text = "drm-driver:\tamdgpu\ndrm-client-id:\t1\ndrm-pdev:\t{}\ndrm-shared-vram:\t0\n{}"
+ with tempfile.TemporaryDirectory() as tmp:
+ card, proc, kw = self._setup(Path(tmp))
+ _write_fd(proc, 100, 5, text.format(self.PDEV, ""))
+ times = iter([0, 1_000_000_000])
+ counters = drm.DrmCounters(found=[card], proc=str(proc), clock=lambda: next(times), **kw)
+ _write_fd(proc, 100, 5, text.format(self.PDEV, "drm-engine-gfx:\t250000000 ns\n"))
+ self.assertEqual(counters.sample()[0][card.key][100].engines["3d"], 25.0)
+
+ def test_client_held_by_several_processes_is_charged_to_none(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ card, proc, kw = self._setup(Path(tmp))
+ _write_fd(proc, 100, 5, _fdinfo(1, self.PDEV, gfx=0, vram=4096))
+ _write_fd(proc, 200, 9, _fdinfo(1, self.PDEV, gfx=0, vram=4096))
+ _write_fd(proc, 300, 5, _fdinfo(2, self.PDEV, gfx=0, vram=8192))
+ times = iter([0, 1_000_000_000])
+ counters = drm.DrmCounters(found=[card], proc=str(proc), clock=lambda: next(times), **kw)
+ procs = counters.sample()[0][card.key]
+ for pid in (100, 200):
+ self.assertTrue(procs[pid].shared_client)
+ self.assertIsNone(procs[pid].shown_vram)
+ self.assertNotIn("engine", procs[pid].available)
+ self.assertEqual(procs[300].shown_vram, 8192 * 1024)
+ # The other rows still add up: the shared client's bytes are left out, not the whole total.
+ self.assertEqual(sum(g.dedicated for g in procs.values()), 8192 * 1024)
+ self.assertTrue(all("dedicated" in g.available for g in procs.values()))
+
+ def test_uninspectable_processes_are_reported(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ card, proc, kw = self._setup(Path(tmp))
+ _write_fd(proc, 100, 5, _fdinfo(1, self.PDEV, vram=4096))
+ (proc / "200" / "fd").mkdir(parents=True)
+ real = os.scandir
+
+ def scandir(path):
+ if str(path).endswith(os.path.join("200", "fd")):
+ raise PermissionError(path)
+ return real(path)
+
+ with patch.object(drm.os, "scandir", scandir):
+ counters = drm.DrmCounters(found=[card], proc=str(proc), **kw)
+ self.assertIn(100, counters.sample()[0][card.key])
+ self.assertIn("1 processes not inspectable", counters.status)
+ counters.sample()
+ self.assertEqual(counters.status, "") # readable now
+
+ def test_scan_budget_keeps_rows_and_resumes(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ ticks = [0.0]
+
+ def timer():
+ ticks[0] += 1.0
+ return ticks[0]
+
+ card, proc, kw = self._setup(Path(tmp), timer)
+ for pid in (100, 200, 300, 400):
+ _write_fd(proc, pid, 5, _fdinfo(pid, self.PDEV, gfx=0, vram=4096))
+ counters = drm.DrmCounters(found=[card], proc=str(proc), **kw) # the baseline is never limited
+ self.assertEqual(sorted(counters._known), [100, 200, 300, 400])
+ counters.scan_budget = 2.5 # one process per refresh with this timer
+ _write_fd(proc, 500, 5, _fdinfo(500, self.PDEV, gfx=0, vram=4096))
+ seen = set()
+ for _ in range(6):
+ rows = counters.sample()[0][card.key]
+ self.assertTrue({100, 200, 300, 400} <= set(rows)) # no row flickers while the scan is partial
+ seen |= set(rows)
+ if 500 in rows:
+ break
+ self.assertIn(500, seen) # a new client is found once the scan comes round to it
+ self.assertIn("scan budget reached", counters.status)
+ counters.scan_budget = None
+ counters.sample()
+ self.assertEqual(counters.status, "")
+
+
class EngineAndSelectionTests(unittest.TestCase):
def test_engine_names(self):
self.assertEqual(drm._engine_key("gfx"), "3d")