mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
182 lines
8.3 KiB
Python
182 lines
8.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Read stock GP100 BAR0 and correlate a bounded CUDA smoke with the CE0 packet."""
|
|
import argparse
|
|
from collections import Counter
|
|
import json
|
|
import mmap
|
|
import os
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
|
|
from stock_ce0_owned import CANDIDATES_PER_STAGE, LATE_STAGE, MAX_CANDIDATES, TIME_LIMIT, stage
|
|
|
|
REGISTERS = {
|
|
"gp_put": 0x000, "gp_get": 0x014, "get": 0x018, "get_hi": 0x01c,
|
|
"gp_base": 0x048, "gp_base_hi": 0x04c, "gp_fetch": 0x050,
|
|
"pb_fetch": 0x054, "pb_fetch_hi": 0x058, "pb_header": 0x084,
|
|
"pb_count": 0x088, "subdevice": 0x094, "target": 0x0ac,
|
|
"data0": 0x0c4, "data1": 0x0cc, "data2": 0x0d4, "status": 0x100,
|
|
"intr0": 0x108, "mask0": 0x10c, "hdr_shadow": 0x118, "channel": 0x120,
|
|
"intr1": 0x148,
|
|
}
|
|
ANCHORS = ("channel", "gp_base", "gp_base_hi", "gp_get", "gp_fetch",
|
|
"get", "get_hi", "pb_header", "hdr_shadow", "target")
|
|
|
|
|
|
def snapshot(mapping, unit):
|
|
base = 0x40000 + unit * 0x2000
|
|
|
|
def grab(key):
|
|
return struct.unpack_from("<I", mapping, base + REGISTERS[key])[0]
|
|
|
|
before = tuple(grab(key) for key in ANCHORS)
|
|
if 0xffffffff in before:
|
|
raise RuntimeError(f"PBDMA{unit}: BAR0 read returned all ones")
|
|
state = {key: grab(key) for key in REGISTERS}
|
|
if before != tuple(state[key] for key in ANCHORS):
|
|
return None
|
|
if before != tuple(grab(key) for key in ANCHORS):
|
|
return None
|
|
return state
|
|
|
|
|
|
def stock_driver(device):
|
|
if (device / "driver").resolve(strict=True).name != "nvidia":
|
|
raise RuntimeError("expected an already bound stock NVIDIA driver")
|
|
|
|
|
|
def identify(bdf):
|
|
device = Path("/sys/bus/pci/devices") / bdf
|
|
stock_driver(device)
|
|
if (device / "vendor").read_text().strip() != "0x10de" or (device / "device").read_text().strip() != "0x15f8":
|
|
raise RuntimeError(f"{bdf} is not the expected Tesla P100 PCIe")
|
|
row = subprocess.check_output(
|
|
["nvidia-smi", "-i", bdf,
|
|
"--query-gpu=uuid,pci.bus_id,driver_version", "--format=csv,noheader"],
|
|
text=True, timeout=5,
|
|
).strip()
|
|
uuid, actual_bdf, version = (value.strip() for value in row.split(","))
|
|
if actual_bdf.lower()[-len(bdf):] != bdf or version != "580.178.04":
|
|
raise RuntimeError(f"unmatched stock device or userspace driver: {row}")
|
|
info = Path("/proc/driver/nvidia/gpus") / bdf / "information"
|
|
minors = [value.strip() for line in info.read_text().splitlines()
|
|
for key, separator, value in [line.partition(":")]
|
|
if separator and key == "Device Minor"]
|
|
if len(minors) != 1 or not minors[0].isascii() or not minors[0].isdigit():
|
|
raise RuntimeError(f"cannot resolve NVIDIA device minor for {bdf}")
|
|
return device, uuid, f"/dev/nvidia{int(minors[0])}", version
|
|
|
|
|
|
def sample_run(mapping, device, folder, probe, uuid, node):
|
|
folder.mkdir()
|
|
raw = folder / "mmio.jsonl"
|
|
owned = folder / "owned.jsonl"
|
|
ready = folder / "ready"
|
|
env = dict(os.environ, CUDA_DEVICE_ORDER="PCI_BUS_ID", CUDA_VISIBLE_DEVICES=uuid)
|
|
baseline = {unit: snapshot(mapping, unit) for unit in range(4)}
|
|
seen = set()
|
|
per_stage = Counter()
|
|
later = None
|
|
unstable = 0
|
|
count = 0
|
|
start = time.monotonic()
|
|
stdout_path = folder / "probe.stdout"
|
|
stderr_path = folder / "probe.stderr"
|
|
with raw.open("x", encoding="utf-8", buffering=1) as stream:
|
|
with stdout_path.open("x", encoding="utf-8") as stdout_stream:
|
|
with stderr_path.open("x", encoding="utf-8") as stderr_stream:
|
|
with subprocess.Popen(
|
|
[sys.executable, str(Path(__file__).with_name("stock_ce0_owned.py")),
|
|
str(raw), str(owned), str(ready), node, str(probe)],
|
|
stdout=stdout_stream, stderr=stderr_stream, text=True, env=env,
|
|
) as process:
|
|
try:
|
|
while process.poll() is None and time.monotonic() - start < TIME_LIMIT:
|
|
stock_driver(device)
|
|
if not ready.exists() or count >= MAX_CANDIDATES:
|
|
time.sleep(0.001)
|
|
continue
|
|
for unit in range(4):
|
|
state = snapshot(mapping, unit)
|
|
if state is None:
|
|
unstable += 1
|
|
continue
|
|
if state == baseline[unit]:
|
|
continue
|
|
selected = stage(state)
|
|
if selected and selected[0] == LATE_STAGE and later is None:
|
|
later = {"unit": unit, "state": state}
|
|
if selected is None or per_stage[selected[0]] >= CANDIDATES_PER_STAGE:
|
|
continue
|
|
key = (unit, *(state[field] for field in ANCHORS))
|
|
if key in seen:
|
|
continue
|
|
seen.add(key)
|
|
row = {"elapsed": time.monotonic() - start, "unit": unit, "state": state}
|
|
stream.write(json.dumps(row) + "\n")
|
|
count += 1
|
|
per_stage[selected[0]] += 1
|
|
if count >= MAX_CANDIDATES:
|
|
break
|
|
time.sleep(0.001)
|
|
finally:
|
|
if process.poll() is None:
|
|
process.kill()
|
|
process.wait(timeout=3)
|
|
stdout = stdout_path.read_text(encoding="utf-8")
|
|
stderr = stderr_path.read_text(encoding="utf-8")
|
|
calls = [json.loads(line) for line in stdout.splitlines() if line.startswith("{")]
|
|
results = [json.loads(line) for line in owned.read_text().splitlines()] if owned.exists() else []
|
|
matched = {row["stage"] for row in results if row.get("packet_matches")}
|
|
return {"rc": process.returncode, "calls": calls, "stderr": stderr, "candidates": count,
|
|
"candidates_by_stage": per_stage, "unstable_samples": unstable,
|
|
"later_semaphore_reference": later,
|
|
"matched_stages": sorted(matched - {LATE_STAGE}),
|
|
"later_packet_matches": LATE_STAGE in matched,
|
|
"later_segments": [
|
|
{"size": row["push_size"],
|
|
"semaphore_groups": len(row.get("semaphore_groups", [])),
|
|
"decode_error": row.get("decode_error")}
|
|
for row in results if row.get("stage") == LATE_STAGE and "push_words" in row
|
|
],
|
|
"later_packet_shape_matches": any(
|
|
row.get("stage") == LATE_STAGE and row.get("packet_shape_matches")
|
|
for row in results
|
|
)}
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("bdf", help="already stock-bound P100 PCI BDF")
|
|
parser.add_argument("probe", type=Path, help="existing CUDA smoke Python file")
|
|
parser.add_argument("output", type=Path, help="new directory for captures")
|
|
parser.add_argument("--runs", type=int, choices=range(1, 4), default=2)
|
|
args = parser.parse_args()
|
|
bdf = args.bdf.lower()
|
|
device, uuid, node, version = identify(bdf)
|
|
probe = args.probe.resolve(strict=True)
|
|
output = args.output.resolve()
|
|
output.mkdir()
|
|
summary = {"bdf": bdf, "uuid": uuid, "gpu_node": node, "driver_version": version, "runs": []}
|
|
try:
|
|
# Keep the existing stock sampler's read-only BAR0 scope. No BAR1 mapping.
|
|
with (device / "resource0").open("rb") as resource:
|
|
with mmap.mmap(resource.fileno(), 0x60000, access=mmap.ACCESS_READ) as mapping:
|
|
for index in range(1, args.runs + 1):
|
|
stock_driver(device)
|
|
run = sample_run(mapping, device, output / f"run-{index}", probe, uuid, node)
|
|
summary["runs"].append(run)
|
|
if run["rc"] != 0:
|
|
break
|
|
finally:
|
|
(output / "summary.json").write_text(json.dumps(summary, indent=2) + "\n")
|
|
print(output / "summary.json")
|
|
return 0 if all(run["rc"] == 0 for run in summary["runs"]) else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|