Files
nvdriver/tools/extract_rmapi_memory_workload.py

146 lines
6.3 KiB
Python

#!/usr/bin/env python3
"""Extract the memory-object requests of one GPU from a captured CUDA run of the original.
Input: the ioctl payload capture of the original driver on this machine
(`cuda-compute-exact-allocation-ioctl-payloads.jsonl`, one JSON object per ioctl with the
escape block before and after and the parameter block before and after). Output:
`tools/rmapi_memory_workload.json`, the ordered requests that concern the memory objects of
the device the context was created on (the last device allocated; the other seven GPUs are
released after `cuInit`), with the original's replies:
alloc NV_ESC_RM_ALLOC of classes 0x90f1, 0x503c, 0x50a0, 0x40, 0x3e under that device
osdesc NV_ESC_RM_ALLOC_MEMORY (class 0x71)
map NV_ESC_RM_MAP_MEMORY of one of those memory objects
unmap NV_ESC_RM_UNMAP_MEMORY
update NV_ESC_RM_UPDATE_DEVICE_MAPPING_INFO
control 0xd01, 0x503c0102, 0x503c0104, 0x503c0105 that name one of those objects
free NV_ESC_RM_FREE of one of those objects
Handles are the ones libcuda chose (0x5c0000xx); the client handle is replaced by the
marker 0xc1d00001 and the device and subdevice by 0xcaf00000 and 0xcaf00001 wherever they
occur as whole 32-bit words in a request or reply. User addresses stay as captured. The
checked-in JSON is what the oracle tool and the Rust replay test read; this script only
regenerates it (`--check` compares).
"""
import argparse
import json
import os
from pathlib import Path
import struct
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_ANALYSIS_ROOT = Path("/home/geodd/nvidia-driver/analysis-580.178.04")
CAPTURE_NAME = "cuda-compute-exact-allocation-ioctl-payloads.jsonl"
TARGET = ROOT / "tools/rmapi_memory_workload.json"
CLASSES = (0x90f1, 0x503c, 0x50a0, 0x40, 0x3e)
CONTROLS = (0xd01, 0x503c0102, 0x503c0104, 0x503c0105)
def find_capture(explicit: Path | None = None) -> Path:
if explicit is not None:
if not explicit.is_file():
raise SystemExit(f"capture file not found: {explicit}")
return explicit
analysis = Path(os.environ.get("NV_RS_ANALYSIS_ROOT", str(DEFAULT_ANALYSIS_ROOT)))
candidate = analysis / "reports" / CAPTURE_NAME
if candidate.is_file():
return candidate
raise SystemExit(
f"capture file not found at {candidate}; pass --input or set NV_RS_ANALYSIS_ROOT"
)
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--check", action="store_true", help="compare output against checked-in JSON")
parser.add_argument("--input", type=Path, default=None, help="path to ioctl payload capture JSONL")
args = parser.parse_args(argv)
capture = find_capture(args.input)
rows = [json.loads(line) for line in capture.read_text(encoding="utf-8").splitlines() if line.strip()]
rows = [row for row in rows if "nvidia-uvm" not in row["device"]]
def number(row):
return int(row["request"], 16) & 0xff
def words(text):
data = bytes.fromhex(text)
return struct.unpack(f"<{len(data) // 4}I", data[:len(data) // 4 * 4])
devices, client = [], None
for row in rows:
if number(row) == 0x2b and words(row["after"])[3] == 0x80:
devices.append(words(row["after"])[2])
client = words(row["after"])[0]
if not devices or client is None:
raise SystemExit(f"no RM device allocation (class 0x80) found in {capture}")
device = devices[-1]
subdevice = next(
(
words(row["after"])[2]
for row in rows
if number(row) == 0x2b
and words(row["after"])[3] == 0x2080
and words(row["after"])[1] == device
),
None,
)
if subdevice is None:
raise SystemExit(f"no RM subdevice allocation (class 0x2080) for device 0x{device:x} in {capture}")
rename = {client: 0xc1d00001, device: 0xcaf00000, subdevice: 0xcaf00001}
def canonical(text):
data = bytearray(bytes.fromhex(text))
for offset in range(0, len(data) - 3, 4):
value = struct.unpack_from("<I", data, offset)[0]
if value in rename:
struct.pack_into("<I", data, offset, rename[value])
return data.hex()
objects, operations = {device, subdevice}, []
for index, row in enumerate(rows):
escape = number(row)
after = words(row["after"])
kind = None
if escape == 0x2b and after[3] in CLASSES and after[1] in objects:
kind = "alloc"
objects.add(after[2])
elif escape == 0x27 and after[1] in objects:
kind = "osdesc"
objects.add(after[2])
elif escape in (0x4e, 0x4f, 0x5e) and after[2] in objects - {device, subdevice}:
kind = {0x4e: "map", 0x4f: "unmap", 0x5e: "update"}[escape]
elif escape == 0x2a and after[2] in CONTROLS:
named = words(row["params_before"])[0] if row["params_before"] else 0
if after[2] == 0xd01 and named not in objects - {device, subdevice}:
continue
if after[2] != 0xd01 and after[1] not in objects:
continue
kind = "control"
elif escape == 0x29 and after[2] in objects - {device, subdevice}:
kind = "free"
objects.discard(after[2])
if kind is None:
continue
operations.append(dict(
kind=kind, index=index, node="ctl" if row["device"].endswith("ctl") else "dev",
request=canonical(row["before"]), reply=canonical(row["after"]),
params=canonical(row["params_before"]) if row["params_before"] else None,
params_reply=canonical(row["params_after"]) if row["params_after"] else None))
text = json.dumps(dict(source=capture.name, client=0xc1d00001, device=0xcaf00000,
subdevice=0xcaf00001, operations=operations), indent=1) + "\n"
if args.check:
if not TARGET.is_file() or TARGET.read_text(encoding="utf-8") != text:
raise SystemExit("workload extract differs from the checked copy")
else:
TARGET.parent.mkdir(parents=True, exist_ok=True)
TARGET.write_text(text, encoding="utf-8")
counts = {}
for operation in operations:
counts[operation["kind"]] = counts.get(operation["kind"], 0) + 1
print(json.dumps(counts))
if __name__ == "__main__":
main()