Files
nvdriver/tools/first_pbentry_owned.py
2026-12-03 07:32:34 +00:00

171 lines
6.6 KiB
Python

#!/usr/bin/env python3
"""Pair the first fresh PBENTRY sample with bytes in the probe's own NVIDIA VMAs.
Run as the Python entry point inside the CUDA probe, with the existing MMIO
sampler writing MMIO_JSONL. This program opens no GPU device and changes no
GPU mapping. GPU VAs without a matching CPU mapping are reported as unavailable.
"""
import ctypes
import json
import os
from pathlib import Path
import runpy
import stat
import struct
import sys
import threading
import time
PBENTRY = 0x00040000
MAX_PUSH_BYTES = 32
TIME_LIMIT = 12.0
NODE_PATHS = ("/dev/nvidiactl", "/dev/nvidia-rs-rmapi")
class Iovec(ctypes.Structure):
_fields_ = [("base", ctypes.c_void_p), ("length", ctypes.c_size_t)]
def address(low, high):
return low | ((high & 0xff) << 32)
def owned_vma(maps, nodes, start, size):
end = start + size
for line in maps.splitlines():
fields = line.split(maxsplit=5)
if len(fields) != 6:
continue
limits, perm, offset, device, inode, path = fields
if path not in nodes or perm[0] != "r" or perm[3] != "s":
continue
major, minor = (int(part, 16) for part in device.split(":"))
if (major, minor, int(inode)) != nodes[path]:
continue
low, high = (int(part, 16) for part in limits.split("-"))
if low <= start < end <= high and int(offset, 16) == 0:
return line
return None
def vma_covers(line, start, size):
low, high = (int(value, 16) for value in line.split()[0].split("-"))
return low <= start < start + size <= high
def read_owned(address, size, node_paths=NODE_PATHS):
nodes = {}
for path in node_paths:
try:
info = os.stat(path)
except FileNotFoundError:
continue
if stat.S_ISCHR(info.st_mode):
nodes[path] = (os.major(info.st_dev), os.minor(info.st_dev), info.st_ino)
maps = Path("/proc/self/maps")
before = owned_vma(maps.read_text(), nodes, address, size)
if before is None:
covering = next((line for line in maps.read_text().splitlines()
if vma_covers(line, address, size)), None)
reason = "no same-VA CPU mapping" if covering is None else covering
raise ValueError(f"range is outside an eligible NVIDIA VMA: {reason}")
fn = ctypes.CDLL(None, use_errno=True).process_vm_readv
fn.argtypes = [ctypes.c_int, ctypes.POINTER(Iovec), ctypes.c_ulong,
ctypes.POINTER(Iovec), ctypes.c_ulong, ctypes.c_ulong]
fn.restype = ctypes.c_ssize_t
data = ctypes.create_string_buffer(size)
local = Iovec(ctypes.addressof(data), size)
remote = Iovec(address, size)
count = fn(os.getpid(), ctypes.byref(local), 1, ctypes.byref(remote), 1, 0)
if count != size:
raise ValueError(f"self read length {count}/{size}, errno {ctypes.get_errno() if count < 0 else 0}")
if owned_vma(maps.read_text(), nodes, address, size) != before:
raise ValueError("NVIDIA control VMA changed during read")
return data.raw
def snapshot_unit(unit, pending, read=read_owned):
result = {"unit": unit, "registers": pending}
try:
decoder = pending["pbentry"]
if pending["0x108"] & PBENTRY == 0 or decoder["intr0_after"] & PBENTRY == 0:
raise ValueError("PBENTRY changed during register sampling")
if (decoder["gp_put"], decoder["gp_get"], decoder["gp_fetch"]) != (1, 1, 1):
raise ValueError("counters do not match the first GPFIFO slot")
base_lo, base_hi = pending["0x48"], pending["0x4c"]
if base_lo == 0xffffffff or base_hi == 0xffffffff:
raise ValueError("GP_BASE read unavailable")
gp = address(base_lo & ~7, base_hi)
result["gp_first_slot_va"] = hex(gp)
gp0, gp1 = struct.unpack("<II", read(gp, 8))
result["gp_words"] = [hex(gp0), hex(gp1)]
pb = address(gp0 & ~3, gp1)
size = ((gp1 >> 10) & 0x1fffff) * 4
result.update(push_va=hex(pb), push_bytes=size)
get = address(decoder["get"], decoder["get_hi"])
fetch = address(decoder["pb_fetch"], decoder["pb_fetch_hi"])
if size == 0 or not (pb <= get < pb + size and pb <= fetch <= pb + size):
raise ValueError("decoded entry does not contain sampled GET and PB_FETCH")
raw = read(pb, min(size, MAX_PUSH_BYTES))
result["push_words"] = [hex(word) for word, in struct.iter_unpack("<I", raw)]
except (KeyError, OSError, ValueError) as error:
result["unavailable"] = str(error)
return result
def watch(source, output, stop):
deadline = time.monotonic() + TIME_LIMIT
result = {"status": "no fresh PBENTRY"}
while time.monotonic() < deadline:
offset = source.tell()
line = source.readline(65537)
if len(line) > 65536:
result = {"status": "MMIO record exceeds limit"}
break
if not line.endswith("\n"):
source.seek(offset)
if stop.is_set():
break
stop.wait(0.02)
continue
try:
sample = json.loads(line)
units = sample.get("pbdma", {})
first = sorted(int(unit) for unit, pending in units.items()
if pending.get("pbentry") and pending["0x108"] & PBENTRY)
except (ValueError, KeyError, TypeError):
result = {"status": "malformed MMIO record"}
break
if first:
# At most the first two asserted units in this one sample.
result = {"status": "first observed PBENTRY", "pid": os.getpid(),
"elapsed": sample.get("elapsed"), "pfifo_intr": sample.get("0x2100"),
"pbdma_pending": sample.get("0x25a0"),
"units": [snapshot_unit(unit, units[str(unit)]) for unit in first[:2]]}
break
output.write(json.dumps(result) + "\n")
output.flush()
def main():
if len(sys.argv) < 4:
raise SystemExit("usage: first_pbentry_owned.py MMIO_JSONL OUTPUT_JSON PROBE.py [args ...]")
mmio, output, probe, *args = sys.argv[1:]
# The sampler must have started. Reject existing output and ignore stale samples.
with open(mmio, encoding="utf-8") as source, open(output, "x", encoding="utf-8") as target:
source.seek(0, os.SEEK_END)
stop = threading.Event()
worker = threading.Thread(target=watch, args=(source, target, stop), daemon=True)
worker.start()
try:
sys.argv = [probe, *args]
sys.path.insert(0, str(Path(probe).resolve().parent))
runpy.run_path(probe, run_name="__main__")
finally:
stop.set()
worker.join()
if __name__ == "__main__":
main()