mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
* tools/docs: complete closed-world 8-category operation inventory and ownership map (#381 Phase 1 & 4) * tools/parity: address all 9 PR #676 review findings (per-arch classes, 580/620 RPC split, full strict metadata) * tools/parity: address remaining PR #676 review findings (fail-closed RPC sources, R620 boundary, op_id) * tools/parity: exclude ENGINE_INVALID classes, verify uvm_bridge.c exports and MIG+SMC markers --------- Co-authored-by: Eric Hartford <eric@quixi.ai>
1545 lines
71 KiB
Python
1545 lines
71 KiB
Python
#!/usr/bin/env python3
|
|
"""Closed-world 580.178.04 parity ledger generator.
|
|
|
|
Audits the stock 580.178.04 driver binaries and userspace callers against
|
|
`src/` and `kernel-open/`, writing:
|
|
- reports/parity_ledger_580.json
|
|
- docs/PARITY_LEDGER.md
|
|
|
|
All external paths are configurable via CLI flags or environment variables and
|
|
fail closed (non-zero exit) when missing so no domain can silently report 0.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
|
|
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
|
|
|
# (code, name, escape_rs_ident_or_none, exclusion_reason_or_none)
|
|
NV_ESCAPES = [
|
|
(0x27, "NV_ESC_RM_ALLOC_MEMORY", "RM_ALLOC_MEMORY", None),
|
|
(0x28, "NV_ESC_RM_ALLOC_OBJECT", "RM_ALLOC_OBJECT", None),
|
|
(0x29, "NV_ESC_RM_FREE", "RM_FREE", None),
|
|
(0x2A, "NV_ESC_RM_CONTROL", "RM_CONTROL", None),
|
|
(0x2B, "NV_ESC_RM_ALLOC", "RM_ALLOC", None),
|
|
(0x34, "NV_ESC_RM_DUP_OBJECT", "RM_DUP_OBJECT", None),
|
|
(0x35, "NV_ESC_RM_SHARE", "RM_SHARE", None),
|
|
(0x39, "NV_ESC_RM_I2C_ACCESS", "RM_I2C_ACCESS", None),
|
|
(0x41, "NV_ESC_RM_IDLE_CHANNELS", "RM_IDLE_CHANNELS", None),
|
|
(0x4A, "NV_ESC_RM_VID_HEAP_CONTROL", "RM_VID_HEAP_CONTROL", None),
|
|
(0x4D, "NV_ESC_RM_ACCESS_REGISTRY", "RM_ACCESS_REGISTRY", None),
|
|
(0x4E, "NV_ESC_RM_MAP_MEMORY", "RM_MAP_MEMORY", None),
|
|
(0x4F, "NV_ESC_RM_UNMAP_MEMORY", "RM_UNMAP_MEMORY", None),
|
|
(0x52, "NV_ESC_RM_GET_EVENT_DATA", "RM_GET_EVENT_DATA", None),
|
|
(0x54, "NV_ESC_RM_ALLOC_CONTEXT_DMA2", "RM_ALLOC_CONTEXT_DMA2", None),
|
|
(
|
|
0x56,
|
|
"NV_ESC_RM_ADD_VBLANK_CALLBACK",
|
|
None,
|
|
"Legacy pre-NVKMS vblank callback (unused on NVKMS/headless Linux)",
|
|
),
|
|
(0x57, "NV_ESC_RM_MAP_MEMORY_DMA", None, None),
|
|
(0x58, "NV_ESC_RM_UNMAP_MEMORY_DMA", None, None),
|
|
(0x59, "NV_ESC_RM_BIND_CONTEXT_DMA", "RM_BIND_CONTEXT_DMA", None),
|
|
(
|
|
0x5C,
|
|
"NV_ESC_RM_EXPORT_OBJECT_TO_FD",
|
|
None,
|
|
"Superseded in 580 by NV0000_CTRL_CMD_OS_UNIX_EXPORT_OBJECT_TO_FD (0x00003d05, ported in node.rs)",
|
|
),
|
|
(
|
|
0x5D,
|
|
"NV_ESC_RM_IMPORT_OBJECT_FROM_FD",
|
|
None,
|
|
"Superseded in 580 by NV0000_CTRL_CMD_OS_UNIX_IMPORT_OBJECT_FROM_FD (0x00003d06, ported in node.rs)",
|
|
),
|
|
(0x5E, "NV_ESC_RM_UPDATE_DEVICE_MAPPING_INFO", "RM_UPDATE_DEVICE_MAPPING_INFO", None),
|
|
(0x5F, "NV_ESC_RM_LOCKLESS_DIAGNOSTIC", "LOCKLESS_DIAGNOSTIC", None),
|
|
(0xC8, "NV_ESC_CARD_INFO", "CARD_INFO", None),
|
|
(0xC9, "NV_ESC_REGISTER_FD", "REGISTER_FD", None),
|
|
(0xCE, "NV_ESC_ALLOC_OS_EVENT", "ALLOC_OS_EVENT", None),
|
|
(0xCF, "NV_ESC_FREE_OS_EVENT", "FREE_OS_EVENT", None),
|
|
(0xD1, "NV_ESC_STATUS_CODE", "STATUS_CODE", None),
|
|
(0xD2, "NV_ESC_CHECK_VERSION_STR", "CHECK_VERSION_STR", None),
|
|
(0xD3, "NV_ESC_IOCTL_XFER_CMD", "IOCTL_XFER_CMD", None),
|
|
(0xD4, "NV_ESC_ATTACH_GPUS_TO_FD", "ATTACH_GPUS_TO_FD", None),
|
|
(0xD5, "NV_ESC_QUERY_DEVICE_INTR", None, None),
|
|
(0xD6, "NV_ESC_SYS_PARAMS", "SYS_PARAMS", None),
|
|
(0xD7, "NV_ESC_NUMA_INFO", "NUMA_INFO", None),
|
|
(0xD8, "NV_ESC_SET_NUMA_STATUS", None, None),
|
|
(0xD9, "NV_ESC_EXPORT_TO_DMABUF_FD", None, None),
|
|
(0xDA, "NV_ESC_WAIT_OPEN_COMPLETE", "WAIT_OPEN_COMPLETE", None),
|
|
(
|
|
0xDB,
|
|
"NV_ESC_INIT_GPUS",
|
|
None,
|
|
"VMware-only ioctl (absent from Linux stock 580.178.04 nvidia.ko)",
|
|
),
|
|
]
|
|
|
|
|
|
def strip_rust_comments(text: str) -> str:
|
|
"""Remove // line comments and /* ... */ block comments from Rust source."""
|
|
out: list[str] = []
|
|
i = 0
|
|
n = len(text)
|
|
in_str = False
|
|
while i < n:
|
|
ch = text[i]
|
|
if in_str:
|
|
out.append(ch)
|
|
if ch == "\\" and i + 1 < n:
|
|
out.append(text[i + 1])
|
|
i += 2
|
|
continue
|
|
if ch == '"':
|
|
in_str = False
|
|
i += 1
|
|
continue
|
|
if ch == "'" and i + 2 < n:
|
|
if text[i + 1] == "\\" and i + 3 < n and text[i + 3] == "'":
|
|
out.append(text[i : i + 4])
|
|
i += 4
|
|
continue
|
|
if text[i + 2] == "'":
|
|
out.append(text[i : i + 3])
|
|
i += 3
|
|
continue
|
|
if ch == '"':
|
|
in_str = True
|
|
out.append(ch)
|
|
i += 1
|
|
continue
|
|
if ch == "/" and i + 1 < n and text[i + 1] == "/":
|
|
nl = text.find("\n", i + 2)
|
|
if nl < 0:
|
|
break
|
|
out.append("\n")
|
|
i = nl + 1
|
|
continue
|
|
if ch == "/" and i + 1 < n and text[i + 1] == "*":
|
|
depth = 1
|
|
i += 2
|
|
while i < n and depth > 0:
|
|
if text[i : i + 2] == "/*":
|
|
depth += 1
|
|
i += 2
|
|
elif text[i : i + 2] == "*/":
|
|
depth -= 1
|
|
i += 2
|
|
else:
|
|
if text[i] == "\n":
|
|
out.append("\n")
|
|
i += 1
|
|
continue
|
|
out.append(ch)
|
|
i += 1
|
|
return "".join(out)
|
|
|
|
|
|
def collect_dispatched_rm_controls() -> set[int]:
|
|
"""Collect RM control command IDs actually dispatched in src/nvidia/src/rmapi/*.rs.
|
|
|
|
Strips comments first, resolves `const NAME: u32 = 0x...;` declarations, and
|
|
only records IDs that appear in match arms, equality checks, `matches!(...)`,
|
|
or control dispatch tables — never comments or unrelated constants.
|
|
"""
|
|
rmapi_dir = ROOT / "src" / "nvidia" / "src" / "rmapi"
|
|
const_map: dict[str, int] = {}
|
|
cleaned_files: list[str] = []
|
|
|
|
for path in sorted(rmapi_dir.glob("*.rs")):
|
|
if path.name.endswith("_tests.rs") or path.name == "control_table.rs":
|
|
continue
|
|
code = strip_rust_comments(path.read_text())
|
|
cleaned_files.append(code)
|
|
for m in re.finditer(
|
|
r"\bconst\s+([A-Z][A-Z0-9_]*)\s*:\s*u32\s*=\s*0x([0-9a-fA-F_]+)\s*;",
|
|
code,
|
|
):
|
|
raw = m.group(2).replace("_", "")
|
|
if len(raw) <= 8:
|
|
const_map[m.group(1)] = int(raw, 16)
|
|
|
|
dispatched: set[int] = set()
|
|
hex_pat = re.compile(r"\b0x([0-9a-fA-F][0-9a-fA-F_]{0,15})\b")
|
|
ident_pat = re.compile(r"\b([A-Z][A-Z0-9_]{2,})\b")
|
|
|
|
def record_tokens(fragment: str) -> None:
|
|
for hm in hex_pat.finditer(fragment):
|
|
raw = hm.group(1).replace("_", "")
|
|
if len(raw) <= 8:
|
|
dispatched.add(int(raw, 16))
|
|
for im in ident_pat.finditer(fragment):
|
|
val = const_map.get(im.group(1))
|
|
if val is not None:
|
|
dispatched.add(val)
|
|
|
|
for code in cleaned_files:
|
|
# 1. Match arms: `<pattern> =>` (may span multiple lines with `|`)
|
|
for m in re.finditer(
|
|
r"([^;{}\n=]+(?:\n\s*\|[^;{}\n=]+)*)\s*(?:\bif\b[^=>{};]+)?=>", code
|
|
):
|
|
record_tokens(m.group(1))
|
|
# 2. Explicit equality/inequality checks: `== CMD` / `!= CMD`
|
|
for m in re.finditer(r"[!=]=\s*(?:[a-z0-9_]+::)*([A-Z][A-Z0-9_]+|0x[0-9a-fA-F_]+)", code):
|
|
record_tokens(m.group(1))
|
|
# 3. `matches!(expr, pat1 | pat2 | ...)`
|
|
for m in re.finditer(r"\bmatches!\s*\([^,]+,([^)]+)\)", code):
|
|
record_tokens(m.group(1))
|
|
# 4. Data-driven control dispatch arrays/tables: `(0x..., ...)` inside `&[ ... ]`
|
|
for m in re.finditer(r"&\s*\[([^\]]+)\]", code):
|
|
body = m.group(1)
|
|
if "0x" in body or "CMD_" in body:
|
|
record_tokens(body)
|
|
|
|
return dispatched
|
|
|
|
|
|
def audit_escapes() -> list[dict]:
|
|
node_rs = strip_rust_comments(
|
|
(ROOT / "src" / "nvidia" / "src" / "rmapi" / "node.rs").read_text()
|
|
)
|
|
rmapi_c = (ROOT / "kernel-open" / "nvidia" / "rmapi_node.c").read_text()
|
|
entries = []
|
|
for code, name, rs_ident, excl in NV_ESCAPES:
|
|
hx = f"0x{code:02x}"
|
|
if excl:
|
|
entries.append(
|
|
{
|
|
"id": f"{hx}:{name}",
|
|
"domain": "rmapi_escapes",
|
|
"status": "INTENTIONALLY_EXCLUDED",
|
|
"note": excl,
|
|
}
|
|
)
|
|
continue
|
|
in_c = bool(
|
|
re.search(rf"\bNV_RS_ESC_[A-Z0-9_]+\s+{hx}\b", rmapi_c, re.I)
|
|
or re.search(rf"==\s*{hx}\b", rmapi_c, re.I)
|
|
or (code == 0xD3 and "struct nv_rs_xfer xfer;" in rmapi_c)
|
|
)
|
|
in_rs = bool(re.search(rf"\b{hx}\s*=>", node_rs, re.I)) or (
|
|
rs_ident is not None
|
|
and (f"escape::{rs_ident}" in node_rs or f"ESC_{rs_ident}" in node_rs)
|
|
)
|
|
if in_rs or in_c:
|
|
status = "PORTED"
|
|
where = " + ".join(
|
|
w for w, b in [("rmapi/node.rs", in_rs), ("rmapi_node.c", in_c)] if b
|
|
)
|
|
note = f"Dispatched in {where}"
|
|
else:
|
|
status = "MISSING"
|
|
note = "Not dispatched in rmapi/node.rs or kernel-open/nvidia/rmapi_node.c"
|
|
entries.append(
|
|
{
|
|
"id": f"{hx}:{name}",
|
|
"domain": "rmapi_escapes",
|
|
"status": status,
|
|
"stock_evidence": f"target/stock-580-kmods/nvidia/nv-kernel.o_binary (NV_ESC {hx} {name})",
|
|
"rust_location": where if status == "PORTED" else None,
|
|
"verification": "cargo test rmapi::" if status == "PORTED" else None,
|
|
"note": note,
|
|
}
|
|
)
|
|
return entries
|
|
|
|
|
|
def audit_control_table(dispatched_cmds: set[int]) -> list[dict]:
|
|
ct = (ROOT / "src" / "nvidia" / "src" / "rmapi" / "control_table.rs").read_text()
|
|
entries = []
|
|
for m in re.finditer(
|
|
r"m\((0x[0-9a-f]+),\s*(0x[0-9a-f]+),\s*(0x[0-9a-f]+),\s*(\d+),\s*(\d+),\s*(\d+)\)",
|
|
ct,
|
|
):
|
|
cmd = int(m.group(2), 16)
|
|
psize = int(m.group(5))
|
|
hid = int(m.group(6))
|
|
status = "PORTED" if cmd in dispatched_cmds else "MISSING"
|
|
entries.append(
|
|
{
|
|
"id": f"0x{cmd:08x}",
|
|
"domain": "rm_control_table_580",
|
|
"status": status,
|
|
"stock_evidence": f"target/stock-580-kmods/nvidia/nv-kernel.o_binary (_nv{hid:06d}rm param_size={psize})",
|
|
"rust_location": "src/nvidia/src/rmapi/control_table.rs + src/nvidia/src/rmapi/" if status == "PORTED" else None,
|
|
"verification": "cargo test rmapi::gpu_tests::" if status == "PORTED" else None,
|
|
"note": f"handler=_nv{hid:06d}rm param_size={psize}",
|
|
}
|
|
)
|
|
return entries
|
|
|
|
|
|
def audit_rm_controls_userspace(
|
|
dispatched_cmds: set[int],
|
|
stock_dir: pathlib.Path,
|
|
open_gpu_ctrl: pathlib.Path,
|
|
libcuda_path: pathlib.Path,
|
|
libnvml_path: pathlib.Path,
|
|
) -> list[dict]:
|
|
server_rs = strip_rust_comments(
|
|
(ROOT / "src" / "nvidia" / "src" / "rmapi" / "server.rs").read_text()
|
|
)
|
|
has_null_handler = "is_null_command(request.cmd)" in server_rs
|
|
|
|
stock_cmds: dict[int, str] = {}
|
|
for h in sorted(open_gpu_ctrl.rglob("*.h")):
|
|
txt = h.read_text(errors="ignore")
|
|
for m in re.finditer(
|
|
r"#define\s+(NV(?:0000|0080|2080|90F1|A06C|A06F|C36F)_CTRL_CMD_[A-Z0-9_]+)\s+\(0x([0-9a-fA-F]+)U?\)",
|
|
txt,
|
|
):
|
|
val = int(m.group(2), 16)
|
|
name = m.group(1)
|
|
if "PFM_REQ_HNDLR" in name or "_GPS_SYS_" in name or "_GPS_DATA_" in name:
|
|
continue
|
|
if val < 0x100 and not name.endswith("_NULL"):
|
|
continue
|
|
stock_cmds[val] = name
|
|
if not stock_cmds:
|
|
raise RuntimeError(f"No RM control macros parsed from {open_gpu_ctrl}")
|
|
|
|
nv_kernel = (stock_dir / "nvidia" / "nv-kernel.o_binary").read_bytes()
|
|
lib_bytes = [
|
|
("cuda", libcuda_path.read_bytes()),
|
|
("nvml", libnvml_path.read_bytes()),
|
|
]
|
|
|
|
# Controls verified absent from stock 580 kernel RM exported tables (userspace-RMAPI-lib-only
|
|
# or unexported/removed; stock kernel RM returns NV_ERR_NOT_SUPPORTED, matching our server.rs).
|
|
non_kernel_rm_controls = {
|
|
0x00000131: "Windows ETW tracing control (absent from Linux 580 kernel RM)",
|
|
0x00000149: "Absent from stock 580 kernel RM exported tables (returns NOT_SUPPORTED)",
|
|
0x00000150: "SoC-only Tegra perf limits (absent from x86_64 580 kernel RM)",
|
|
0x0000027A: "Absent from stock 580 kernel RM exported tables (returns NOT_SUPPORTED)",
|
|
0x00000291: "Absent from stock 580 kernel RM exported tables (returns NOT_SUPPORTED)",
|
|
0x00000480: "Debug-only lock meter (absent from release 580 kernel RM)",
|
|
0x00000481: "Debug-only lock meter (absent from release 580 kernel RM)",
|
|
0x00000485: "Debug-only lock meter (absent from release 580 kernel RM)",
|
|
0x00000608: "Windows DPC/ISR timestamp diagnostic (absent from Linux 580 kernel RM)",
|
|
0x00000B06: "Absent from stock 580 kernel RM exported tables (returns NOT_SUPPORTED)",
|
|
0x00003D04: "Userspace RMAPI-lib-only control (never sent to kernel RM)",
|
|
0x00003D07: "Absent from stock 580 kernel RM exported tables (returns NOT_SUPPORTED)",
|
|
0x00003D09: "Userspace RMAPI-lib-only control (refreshes userspace RMAPI device list)",
|
|
0x20801321: "Absent from stock 580 kernel RM exported tables (returns NOT_SUPPORTED)",
|
|
}
|
|
|
|
entries = []
|
|
for val, name in sorted(stock_cmds.items()):
|
|
pat = val.to_bytes(4, "little")
|
|
in_rm = pat in nv_kernel
|
|
callers = [tag for tag, data in lib_bytes if pat in data]
|
|
if not (in_rm and callers):
|
|
continue
|
|
if val in non_kernel_rm_controls:
|
|
entries.append(
|
|
{
|
|
"id": f"0x{val:08x}:{name}",
|
|
"domain": "rm_controls_userspace",
|
|
"status": "INTENTIONALLY_EXCLUDED",
|
|
"callers": callers,
|
|
"note": non_kernel_rm_controls[val],
|
|
}
|
|
)
|
|
continue
|
|
if (val & 0xFFFF) == 0 and has_null_handler:
|
|
status = "PORTED"
|
|
note = f"Handled generically by is_null_command() in rmapi/server.rs (callers: {','.join(callers)})"
|
|
elif val in dispatched_cmds:
|
|
status = "PORTED"
|
|
note = f"Dispatched in src/nvidia/src/rmapi/ (callers: {','.join(callers)})"
|
|
else:
|
|
status = "MISSING"
|
|
note = f"In stock 580.178.04 nv-kernel.o_binary + {','.join(callers)}; not dispatched in src/nvidia/src/rmapi/"
|
|
entries.append(
|
|
{
|
|
"id": f"0x{val:08x}:{name}",
|
|
"domain": "rm_controls_userspace",
|
|
"status": status,
|
|
"stock_evidence": f"target/stock-580-kmods/nvidia/nv-kernel.o_binary + {','.join(callers)} (0x{val:08x})",
|
|
"rust_location": "src/nvidia/src/rmapi/" if status == "PORTED" else None,
|
|
"verification": "cargo test rmapi::" if status == "PORTED" else None,
|
|
"callers": callers,
|
|
"note": note,
|
|
}
|
|
)
|
|
return entries
|
|
|
|
|
|
def audit_uvm(stock_dir: pathlib.Path) -> list[dict]:
|
|
nm_uvm = subprocess.check_output(
|
|
["nm", str(stock_dir / "nvidia-uvm.ko")], text=True
|
|
)
|
|
api_syms = sorted(set(re.findall(r"\buvm_api_\w+", nm_uvm)))
|
|
uvm_rs = strip_rust_comments(
|
|
"\n".join(
|
|
p.read_text()
|
|
for p in (ROOT / "src" / "nvidia" / "src" / "uvm").glob("*.rs")
|
|
if not p.name.endswith("_tests.rs")
|
|
)
|
|
)
|
|
aliases = {
|
|
"uvm_api_register_gpu_va_space": "UVM_REGISTER_GPU_VASPACE",
|
|
"uvm_api_unregister_gpu_va_space": "UVM_UNREGISTER_GPU_VASPACE",
|
|
}
|
|
internal_helpers = {"uvm_api_range_type_check"}
|
|
entries = []
|
|
for sym in api_syms:
|
|
if sym in internal_helpers:
|
|
entries.append(
|
|
{
|
|
"id": sym,
|
|
"domain": "uvm_ioctls",
|
|
"status": "INTENTIONALLY_EXCLUDED",
|
|
"note": "Internal helper in stock nvidia-uvm.ko (not a userspace ioctl)",
|
|
}
|
|
)
|
|
continue
|
|
const_name = aliases.get(sym, "UVM_" + sym[len("uvm_api_") :].upper())
|
|
if const_name in uvm_rs:
|
|
status = "PORTED"
|
|
note = f"Handled in src/nvidia/src/uvm/ ({const_name})"
|
|
else:
|
|
status = "MISSING"
|
|
note = f"Expected {const_name} not found in src/nvidia/src/uvm/"
|
|
entries.append(
|
|
{
|
|
"id": sym,
|
|
"domain": "uvm_ioctls",
|
|
"status": status,
|
|
"stock_evidence": f"target/stock-580-kmods/nvidia-uvm.ko ({sym})",
|
|
"rust_location": f"src/nvidia/src/uvm/ ({const_name})" if status == "PORTED" else None,
|
|
"verification": "cargo test uvm::" if status == "PORTED" else None,
|
|
"note": note,
|
|
}
|
|
)
|
|
return entries
|
|
|
|
|
|
def audit_drm(stock_dir: pathlib.Path) -> list[dict]:
|
|
nm_drm = subprocess.check_output(
|
|
["nm", str(stock_dir / "nvidia-drm.ko")], text=True
|
|
)
|
|
drm_ioctls = sorted(
|
|
s
|
|
for s in set(re.findall(r"\bnv_drm_\w*_ioctl\b", nm_drm))
|
|
if s != "nv_drm_ioctl"
|
|
)
|
|
our_drm = (ROOT / "kernel-open" / "nvidia-drm" / "nvidia_rs_drm.c").read_text()
|
|
drm_aliases = {
|
|
"nv_drm_grant_permission_ioctl": "NVIDIA_GRANT_PERMISSIONS",
|
|
"nv_drm_revoke_permission_ioctl": "NVIDIA_REVOKE_PERMISSIONS",
|
|
}
|
|
drm_handler_bodies: dict[str, str] = {}
|
|
for m_fn in re.finditer(
|
|
r"static\s+int\s+(nv_rs_ioctl_\w+)\s*\([^)]*\)\s*\{(.*?)\n\}",
|
|
our_drm,
|
|
re.S,
|
|
):
|
|
drm_handler_bodies[m_fn.group(1)] = m_fn.group(2)
|
|
entries = []
|
|
for sym in drm_ioctls:
|
|
stem = sym[len("nv_drm_") : -len("_ioctl")].upper()
|
|
macro = drm_aliases.get(sym, f"NVIDIA_{stem}")
|
|
m_def = re.search(rf"DRM_IOCTL_DEF_DRV\({macro},\s*(\w+)\b", our_drm)
|
|
if m_def:
|
|
fn_name = m_def.group(1)
|
|
fn_body = drm_handler_bodies.get(fn_name, "")
|
|
if fn_name == "nv_rs_drm_eopnotsupp":
|
|
status = "PARTIAL"
|
|
note = f"UAPI struct + ioctl {macro} wired in nvidia_rs_drm.c (returns -EOPNOTSUPP until GEM/fence backend)"
|
|
elif sym in ("nv_drm_get_crtc_crc32_ioctl", "nv_drm_get_crtc_crc32_v2_ioctl"):
|
|
status = "PARTIAL"
|
|
note = f"UAPI + validation wired in nvidia_rs_drm.c ({fn_name}; hardware CRC register readout not yet implemented)"
|
|
elif fn_body and re.search(r"\bret\s*=\s*-EOPNOTSUPP\s*;\s*\}\s*out:", fn_body):
|
|
status = "PARTIAL"
|
|
note = f"UAPI + validation wired in nvidia_rs_drm.c ({fn_name} returns -EOPNOTSUPP)"
|
|
else:
|
|
status = "PORTED"
|
|
note = f"Wired in kernel-open/nvidia-drm/nvidia_rs_drm.c as {macro} ({fn_name})"
|
|
else:
|
|
status = "MISSING"
|
|
note = f"In stock nvidia-drm.ko ({sym}); not wired in nvidia_rs_drm.c"
|
|
entries.append(
|
|
{
|
|
"id": sym,
|
|
"domain": "drm_ioctls",
|
|
"status": status,
|
|
"stock_evidence": f"target/stock-580-kmods/nvidia-drm.ko ({sym})",
|
|
"rust_location": f"kernel-open/nvidia-drm/nvidia_rs_drm.c ({fn_name})" if m_def else None,
|
|
"verification": "make modules + tools/check_kernel_module.py" if status == "PORTED" else None,
|
|
"note": note,
|
|
}
|
|
)
|
|
return entries
|
|
|
|
|
|
def audit_nvkms(stock_dir: pathlib.Path, open_gpu_root: pathlib.Path) -> list[dict]:
|
|
"""Audit all 66 stock 580.178.04 NVKMS ioctl entries directly from nvidia-modeset.ko."""
|
|
nvkms_ko = stock_dir / "nvidia-modeset.ko"
|
|
if not nvkms_ko.exists():
|
|
raise RuntimeError(f"Missing stock nvidia-modeset.ko: {nvkms_ko}")
|
|
# Extract exact 66-entry paramsSize table from stock 580.178.04 nvidia-modeset.ko
|
|
secs = subprocess.check_output(["readelf", "-SW", str(nvkms_ko)], text=True)
|
|
rodata_off = None
|
|
for line in secs.splitlines():
|
|
if " .rodata " in line:
|
|
parts = line.split()
|
|
rodata_off = int(parts[parts.index(".rodata") + 3], 16)
|
|
break
|
|
if rodata_off is None:
|
|
raise RuntimeError(f"Could not locate .rodata in {nvkms_ko}")
|
|
ko_bytes = nvkms_ko.read_bytes()
|
|
# Verified from nvKmsIoctl disassembly: cmp $0x41, %r12d (66 entries), .rodata+0x25ee0, stride 72, size at +0x18
|
|
table_base = 0x25EE0
|
|
stock_sizes = [
|
|
int.from_bytes(ko_bytes[rodata_off + table_base + i * 72 + 0x18 : rodata_off + table_base + i * 72 + 0x20], "little")
|
|
for i in range(66)
|
|
]
|
|
|
|
# Exact 580.178.04 command names (retains CHECK_LUT_NOTIFIER at 13, FRAMEBUFFER_CONSOLE_DISABLED at 65)
|
|
names_580 = {
|
|
0: "NVKMS_IOCTL_ALLOC_DEVICE",
|
|
1: "NVKMS_IOCTL_FREE_DEVICE",
|
|
2: "NVKMS_IOCTL_QUERY_DISP",
|
|
3: "NVKMS_IOCTL_QUERY_CONNECTOR_STATIC_DATA",
|
|
4: "NVKMS_IOCTL_QUERY_CONNECTOR_DYNAMIC_DATA",
|
|
5: "NVKMS_IOCTL_QUERY_DPY_STATIC_DATA",
|
|
6: "NVKMS_IOCTL_QUERY_DPY_DYNAMIC_DATA",
|
|
7: "NVKMS_IOCTL_VALIDATE_MODE_INDEX",
|
|
8: "NVKMS_IOCTL_VALIDATE_MODE",
|
|
9: "NVKMS_IOCTL_SET_MODE",
|
|
10: "NVKMS_IOCTL_SET_CURSOR_IMAGE",
|
|
11: "NVKMS_IOCTL_MOVE_CURSOR",
|
|
12: "NVKMS_IOCTL_SET_LUT",
|
|
13: "NVKMS_IOCTL_CHECK_LUT_NOTIFIER",
|
|
14: "NVKMS_IOCTL_IDLE_BASE_CHANNEL",
|
|
15: "NVKMS_IOCTL_FLIP",
|
|
16: "NVKMS_IOCTL_DECLARE_DYNAMIC_DPY_INTEREST",
|
|
17: "NVKMS_IOCTL_REGISTER_SURFACE",
|
|
18: "NVKMS_IOCTL_UNREGISTER_SURFACE",
|
|
19: "NVKMS_IOCTL_GRANT_SURFACE",
|
|
20: "NVKMS_IOCTL_ACQUIRE_SURFACE",
|
|
21: "NVKMS_IOCTL_RELEASE_SURFACE",
|
|
22: "NVKMS_IOCTL_SET_DPY_ATTRIBUTE",
|
|
23: "NVKMS_IOCTL_GET_DPY_ATTRIBUTE",
|
|
24: "NVKMS_IOCTL_GET_DPY_ATTRIBUTE_VALID_VALUES",
|
|
25: "NVKMS_IOCTL_SET_DISP_ATTRIBUTE",
|
|
26: "NVKMS_IOCTL_GET_DISP_ATTRIBUTE",
|
|
27: "NVKMS_IOCTL_GET_DISP_ATTRIBUTE_VALID_VALUES",
|
|
28: "NVKMS_IOCTL_QUERY_FRAMELOCK",
|
|
29: "NVKMS_IOCTL_SET_FRAMELOCK_ATTRIBUTE",
|
|
30: "NVKMS_IOCTL_GET_FRAMELOCK_ATTRIBUTE",
|
|
31: "NVKMS_IOCTL_GET_FRAMELOCK_ATTRIBUTE_VALID_VALUES",
|
|
32: "NVKMS_IOCTL_GET_NEXT_EVENT",
|
|
33: "NVKMS_IOCTL_DECLARE_EVENT_INTEREST",
|
|
34: "NVKMS_IOCTL_CLEAR_UNICAST_EVENT",
|
|
35: "NVKMS_IOCTL_GET_3DVISION_DONGLE_PARAM_BYTES",
|
|
36: "NVKMS_IOCTL_SET_3DVISION_AEGIS_PARAMS",
|
|
37: "NVKMS_IOCTL_SET_LAYER_POSITION",
|
|
38: "NVKMS_IOCTL_GRAB_OWNERSHIP",
|
|
39: "NVKMS_IOCTL_RELEASE_OWNERSHIP",
|
|
40: "NVKMS_IOCTL_GRANT_PERMISSIONS",
|
|
41: "NVKMS_IOCTL_ACQUIRE_PERMISSIONS",
|
|
42: "NVKMS_IOCTL_REVOKE_PERMISSIONS",
|
|
43: "NVKMS_IOCTL_QUERY_DPY_CRC32",
|
|
44: "NVKMS_IOCTL_REGISTER_DEFERRED_REQUEST_FIFO",
|
|
45: "NVKMS_IOCTL_UNREGISTER_DEFERRED_REQUEST_FIFO",
|
|
46: "NVKMS_IOCTL_ALLOC_SWAP_GROUP",
|
|
47: "NVKMS_IOCTL_FREE_SWAP_GROUP",
|
|
48: "NVKMS_IOCTL_JOIN_SWAP_GROUP",
|
|
49: "NVKMS_IOCTL_LEAVE_SWAP_GROUP",
|
|
50: "NVKMS_IOCTL_SET_SWAP_GROUP_CLIP_LIST",
|
|
51: "NVKMS_IOCTL_GRANT_SWAP_GROUP",
|
|
52: "NVKMS_IOCTL_ACQUIRE_SWAP_GROUP",
|
|
53: "NVKMS_IOCTL_RELEASE_SWAP_GROUP",
|
|
54: "NVKMS_IOCTL_SWITCH_MUX",
|
|
55: "NVKMS_IOCTL_GET_MUX_STATE",
|
|
56: "NVKMS_IOCTL_ENABLE_VBLANK_SYNC_OBJECT",
|
|
57: "NVKMS_IOCTL_DISABLE_VBLANK_SYNC_OBJECT",
|
|
58: "NVKMS_IOCTL_NOTIFY_VBLANK",
|
|
59: "NVKMS_IOCTL_SET_FLIPLOCK_GROUP",
|
|
60: "NVKMS_IOCTL_ENABLE_VBLANK_SEM_CONTROL",
|
|
61: "NVKMS_IOCTL_DISABLE_VBLANK_SEM_CONTROL",
|
|
62: "NVKMS_IOCTL_ACCEL_VBLANK_SEM_CONTROLS",
|
|
63: "NVKMS_IOCTL_580_CMD_63",
|
|
64: "NVKMS_IOCTL_580_CMD_64",
|
|
65: "NVKMS_IOCTL_FRAMEBUFFER_CONSOLE_DISABLED",
|
|
}
|
|
|
|
our_ms = (
|
|
ROOT / "kernel-open" / "nvidia-modeset" / "nvidia_rs_modeset.c"
|
|
).read_text()
|
|
# Parse #define NV_RS_KMS_CMD_* <num> and switch case arms; exclude handlers returning -EOPNOTSUPP
|
|
cmd_macros: dict[str, int] = {}
|
|
for m_def in re.finditer(r"#define\s+(NV_RS_KMS_CMD_[A-Z0-9_]+)\s+(\d+)u?\b", our_ms):
|
|
cmd_macros[m_def.group(1)] = int(m_def.group(2))
|
|
our_sizes: dict[int, int] = {}
|
|
nvkms_rs = ROOT / "src" / "nvidia" / "src" / "nvkms" / "mod.rs"
|
|
nvkms_rs_text = nvkms_rs.read_text() if nvkms_rs.exists() else ""
|
|
m_arr = re.search(r"NVKMS_PARAM_SIZES_580:\s*\[u32;\s*66\]\s*=\s*\[([^\]]+)\]", nvkms_rs_text)
|
|
if m_arr:
|
|
for idx, tok in enumerate(re.findall(r"\d+", m_arr.group(1))):
|
|
our_sizes[idx] = int(tok)
|
|
else:
|
|
for m_sz in re.finditer(r"\[(\d+)\]\s*=\s*(\d+),", our_ms):
|
|
our_sizes[int(m_sz.group(1))] = int(m_sz.group(2))
|
|
# Map each static C handler name to its function body so handlers that
|
|
# still return -EOPNOTSUPP (or lack a live display/framelock backend) are
|
|
# never promoted to PORTED based on validator coverage alone.
|
|
handler_bodies: dict[str, str] = {}
|
|
for m_fn in re.finditer(
|
|
r"static\s+long\s+(nv_rs_modeset_\w+)\s*\([^)]*\)\s*\{(.*?)\n\}",
|
|
our_ms,
|
|
re.S,
|
|
):
|
|
handler_bodies[m_fn.group(1)] = m_fn.group(2)
|
|
|
|
ported_bodies: dict[int, str] = {}
|
|
for m_case in re.finditer(r"case\s+(NV_RS_KMS_CMD_[A-Z0-9_]+)\s*:\s*return\s+(\w+)\(", our_ms):
|
|
macro, fn_name = m_case.group(1), m_case.group(2)
|
|
body = handler_bodies.get(fn_name, "")
|
|
if macro in cmd_macros and body and "return -EOPNOTSUPP;" not in body:
|
|
ported_bodies[cmd_macros[macro]] = body
|
|
|
|
# Per-command live FFI + dedicated Rust unit test verification map:
|
|
# a command is marked PORTED only when its live C handler invokes the named
|
|
# Rust FFI symbol, executes its real semantics (no -EOPNOTSUPP placeholder),
|
|
# AND the corresponding dedicated unit test exists in nvkms/mod.rs.
|
|
# Commands without hardware/full-decode backends remain honestly PARTIAL:
|
|
# - 9, 10, 15: userspace NVKMS full SetMode/SetCursorImage/Flip surface commit
|
|
# - 11: hardware CursorImm move (requires display ownership; returns -EOPNOTSUPP without CursorImm)
|
|
# - 12, 13: hardware LUT programming / LUT notifier
|
|
# - 14: hardware base-channel idle wait
|
|
# - 22, 25: hardware DPY/DISP attribute writes (return -EOPNOTSUPP until wired to display HW)
|
|
# - 28..31: Quadro Sync framelock (numFrameLocks == 0)
|
|
# - 33: chardev event interest producer (nonzero mask returns -EOPNOTSUPP)
|
|
# - 35, 36: 3DVision dongle/Aegis
|
|
# - 37: hardware window layer positioning (returns -EOPNOTSUPP until wired to scanout)
|
|
# - 43: hardware CRC register readout (currently reports supported = 0)
|
|
# - 44, 45: deferred request FIFO consumer
|
|
# - 48, 49, 50: multi-member SwapGroup join/leave/clip
|
|
# - 54, 55: physical display mux switch/query
|
|
# - 56, 57: Tegra/host1x vblank sync objects
|
|
# - 59: cross-head hardware fliplock synchronization
|
|
# - 60..63: surface-backed vblank semaphore controls
|
|
verified_ffi_tests: dict[int, tuple[str, str]] = {
|
|
0: ("nv_rs_nvkms_validate_alloc_device(", "test_alloc_device"),
|
|
1: ("nv_rs_nvkms_validate_free_device(", "test_free_device"),
|
|
2: ("nv_rs_nvkms_validate_query_disp(", "test_query_disp"),
|
|
3: ("nv_rs_nvkms_validate_query_connector_static_data(", "test_query_connector_static_data"),
|
|
4: ("nv_rs_nvkms_validate_query_connector_dynamic_data(", "test_query_connector_dynamic_data"),
|
|
5: ("nv_rs_nvkms_validate_query_dpy_static_data(", "test_query_dpy_static_data"),
|
|
6: ("nv_rs_nvkms_edid_name(", "test_query_dpy_dynamic_data"),
|
|
7: ("nv_rs_nvkms_mode_from_edid(", "test_validate_mode_index"),
|
|
8: ("nv_rs_nvkms_validate_mode(", "test_validate_mode"),
|
|
16: ("nv_rs_nvkms_validate_declare_dynamic_dpy_interest(", "test_declare_dynamic_dpy_interest"),
|
|
17: ("nv_rs_nvkms_surface_register(", "test_register_surface"),
|
|
18: ("nv_rs_nvkms_surface_unregister(", "test_unregister_surface"),
|
|
19: ("nv_rs_nvkms_surface_grant(", "test_grant_surface"),
|
|
20: ("nv_rs_nvkms_surface_acquire(", "test_acquire_surface"),
|
|
21: ("nv_rs_nvkms_surface_release(", "test_release_surface"),
|
|
23: ("nv_rs_nvkms_dpy_attr_get(", "test_get_dpy_attribute"),
|
|
24: ("nv_rs_nvkms_dpy_attr_valid(", "test_get_dpy_attribute_valid_values"),
|
|
26: ("nv_rs_nvkms_disp_attr_get(", "test_get_disp_attribute"),
|
|
27: ("nv_rs_nvkms_disp_attr_valid(", "test_get_disp_attribute_valid_values"),
|
|
32: ("nv_rs_nvkms_validate_get_next_event(", "test_get_next_event"),
|
|
34: ("nv_rs_nvkms_validate_clear_unicast_event(", "test_clear_unicast_event"),
|
|
38: ("nv_rs_nvkms_ownership_grab(", "test_grab_ownership"),
|
|
39: ("nv_rs_nvkms_ownership_release(", "test_release_ownership"),
|
|
40: ("nv_rs_nvkms_perm_grant(", "test_grant_permissions"),
|
|
41: ("nv_rs_nvkms_perm_acquire(", "test_acquire_permissions"),
|
|
42: ("nv_rs_nvkms_perm_revoke(", "test_revoke_permissions"),
|
|
46: ("nv_rs_nvkms_sg_alloc(", "test_alloc_swap_group"),
|
|
47: ("nv_rs_nvkms_sg_free(", "test_free_swap_group"),
|
|
51: ("nv_rs_nvkms_sg_grant(", "test_grant_swap_group"),
|
|
52: ("nv_rs_nvkms_sg_acquire(", "test_acquire_swap_group"),
|
|
53: ("nv_rs_nvkms_sg_release(", "test_release_swap_group"),
|
|
58: ("nv_rs_nvkms_validate_notify_vblank(", "test_notify_vblank"),
|
|
64: ("nv_rs_nvkms_cmd64_mark(", "test_580_cmd_64"),
|
|
65: ("nv_rs_nvkms_validate_fbcon_disabled_userspace(", "test_fbcon_disabled_userspace"),
|
|
}
|
|
|
|
entries = []
|
|
for idx, stock_sz in enumerate(stock_sizes):
|
|
cmd = names_580[idx]
|
|
ffi_pair = verified_ffi_tests.get(idx)
|
|
is_verified = (
|
|
idx in ported_bodies
|
|
and our_sizes.get(idx) == stock_sz
|
|
and ffi_pair is not None
|
|
and ffi_pair[0] in ported_bodies[idx]
|
|
and f"fn {ffi_pair[1]}()" in nvkms_rs_text
|
|
)
|
|
if is_verified:
|
|
status = "PORTED"
|
|
verif = f"cargo test nvkms::tests::{ffi_pair[1]}"
|
|
note = f"cmd={idx} exact 580.178.04 paramSize={stock_sz}, live C handler calls {ffi_pair[0][:-1]} verified by {verif}"
|
|
elif our_sizes.get(idx) == stock_sz:
|
|
status = "PARTIAL"
|
|
verif = None
|
|
if idx == 33:
|
|
note = f"cmd=33 exact 580.178.04 paramSize={stock_sz}; rejects nonzero event mask with -EOPNOTSUPP until event producer is wired"
|
|
else:
|
|
note = f"cmd={idx} exact 580.178.04 paramSize={stock_sz} + deviceHandle validated in nvidia_rs_modeset.c (display/surface backend or per-cmd test pending)"
|
|
else:
|
|
status = "MISSING"
|
|
verif = None
|
|
note = f"cmd={idx} stock_size={stock_sz} mismatch/absent in nvidia_rs_modeset.c (got {our_sizes.get(idx)})"
|
|
entries.append(
|
|
{
|
|
"id": f"{idx}:{cmd}",
|
|
"domain": "nvkms_ioctls",
|
|
"status": status,
|
|
"stock_evidence": f"target/stock-580-kmods/nvidia-modeset.ko:.rodata+0x{table_base + idx * 72:x} (paramsSize={stock_sz})",
|
|
"rust_location": (
|
|
"src/nvidia/src/nvkms/mod.rs + kernel-open/nvidia-modeset/nvidia_rs_modeset.c"
|
|
if status == "PORTED"
|
|
else (
|
|
"kernel-open/nvidia-modeset/nvidia_rs_modeset.c"
|
|
if status == "PARTIAL"
|
|
else None
|
|
)
|
|
),
|
|
"verification": verif,
|
|
"note": note,
|
|
}
|
|
)
|
|
return entries
|
|
|
|
|
|
def audit_procfs_and_caps() -> list[dict]:
|
|
rmapi_c = (ROOT / "kernel-open" / "nvidia" / "rmapi_node.c").read_text()
|
|
required = [
|
|
("proc:/proc/driver/nvidia/params", "nv_rs_proc_params_show"),
|
|
("proc:/proc/driver/nvidia/version", "nv_rs_proc_version_show"),
|
|
("proc:/proc/driver/nvidia/gpus/<bdf>/information", "nv_rs_proc_gpu_info_show"),
|
|
("proc:/proc/driver/nvidia/gpus/<bdf>/power", "nv_rs_proc_gpu_power_show"),
|
|
("proc:/proc/driver/nvidia/gpus/<bdf>/registry", "nv_rs_proc_gpu_registry_show"),
|
|
("proc:/proc/driver/nvidia/capabilities/mig/config", "mig"),
|
|
("proc:/proc/driver/nvidia/capabilities/mig/monitor", "monitor"),
|
|
("proc:/proc/driver/nvidia/capabilities/fabric-imex-mgmt", "fabric-imex-mgmt"),
|
|
("chrdev:/dev/nvidia-caps/nvidia-capN", "nv_rs_caps_chrdev_init"),
|
|
]
|
|
entries = []
|
|
for item_id, needle in required:
|
|
if needle in rmapi_c:
|
|
status = "PORTED"
|
|
note = f"Present in kernel-open/nvidia/rmapi_node.c ({needle})"
|
|
else:
|
|
status = "MISSING"
|
|
note = f"Not found in kernel-open/nvidia/rmapi_node.c ({needle})"
|
|
entries.append(
|
|
{
|
|
"id": item_id,
|
|
"domain": "procfs_and_caps",
|
|
"status": status,
|
|
"stock_evidence": f"target/stock-580-kmods/nvidia/nv-kernel.o_binary ({item_id})",
|
|
"rust_location": f"kernel-open/nvidia/rmapi_node.c ({needle})" if status == "PORTED" else None,
|
|
"verification": "make modules + tools/vm/run_guest.py" if status == "PORTED" else None,
|
|
"note": note,
|
|
}
|
|
)
|
|
return entries
|
|
|
|
|
|
def _extract_balanced_brace_body(text: str, start_idx: int) -> str | None:
|
|
"""Return the substring inside the balanced `{ ... }` block starting at/after start_idx."""
|
|
open_pos = text.find("{", start_idx)
|
|
if open_pos == -1:
|
|
return None
|
|
depth = 0
|
|
for idx in range(open_pos, len(text)):
|
|
ch = text[idx]
|
|
if ch == "{":
|
|
depth += 1
|
|
elif ch == "}":
|
|
depth -= 1
|
|
if depth == 0:
|
|
return text[open_pos + 1 : idx]
|
|
return None
|
|
|
|
|
|
def _pascal_helper_guards_bus_loss(clean_file: str) -> bool:
|
|
"""Verify fn read_pascal_register in the same file filters out u32::MAX / 0xffff_ffff."""
|
|
m = re.search(r"\bfn\s+read_pascal_register\b[^{]*\{", clean_file)
|
|
if not m:
|
|
return False
|
|
body = _extract_balanced_brace_body(clean_file, m.end() - 1)
|
|
return bool(body and re.search(r"!=\s*(?:u32::MAX|0x[fF]{4}_?[fF]{4})\b", body))
|
|
|
|
|
|
def _has_verified_bus_loss_exit(loop_body: str, pascal_helper_ok: bool) -> bool:
|
|
"""Verify the comment-stripped loop body checks an MMIO read against u32::MAX / 0xffff_ffff and exits."""
|
|
# 1. Explicit comparison against u32::MAX / 0xffff_ffff / 0xffffffff inside an `if`
|
|
# whose consequent exits via `return` or `break` (not `unwrap_or(u32::MAX)` or comments).
|
|
cond_re = re.compile(
|
|
r"\bif\b[^{]*?(?:==\s*(?:u32::MAX|0x[fF]{4}_?[fF]{4})\b|(?:u32::MAX|0x[fF]{4}_?[fF]{4})\s*==)[^{]*?\{"
|
|
)
|
|
for m in cond_re.finditer(loop_body):
|
|
then_body = _extract_balanced_brace_body(loop_body, m.end() - 1)
|
|
if then_body and re.search(r"\b(?:return|break)\b", then_body):
|
|
return True
|
|
# 2. Checked helper read_pascal_register() that filters u32::MAX -> None, with
|
|
# immediate early exit on None (`let Some(...) = ... else { return ... }` or `.ok_or(...)?`).
|
|
if pascal_helper_ok and "read_pascal_register(" in loop_body:
|
|
if re.search(
|
|
r"read_pascal_register\([^)]*\)\s*(?:\.\s*ok_or\([^)]*\)\s*\?|\?\s*;)",
|
|
loop_body,
|
|
):
|
|
return True
|
|
if re.search(
|
|
r"\blet\s+Some\([^)]*\)\s*=\s*[^;]*read_pascal_register\([^)]*\)\s*else\s*\{[^}]*\b(?:return|break)\b",
|
|
loop_body,
|
|
):
|
|
return True
|
|
return False
|
|
|
|
|
|
def audit_mmio_bus_loss_guards() -> list[dict]:
|
|
"""Audit MMIO polling loops in src/nvidia/kernel/ for 0xffff_ffff bus-loss guards."""
|
|
entries = []
|
|
poll_hints = (
|
|
"0..10_000",
|
|
"0..100_000",
|
|
"0..1_000_000",
|
|
"nv_rs_os_busy_us",
|
|
"udelay",
|
|
)
|
|
read_hints = ("read32(", "rd32(", "bar0_read(", "read_pascal_register(")
|
|
for p in sorted((ROOT / "src" / "nvidia" / "kernel").glob("*.rs")):
|
|
raw = p.read_text()
|
|
clean = strip_rust_comments(raw)
|
|
pascal_helper_ok = _pascal_helper_guards_bus_loss(clean)
|
|
for m in re.finditer(r"\bfor\s+_\s+in\s+0\.\.[^\n{]*\{", clean):
|
|
line_no = clean.count("\n", 0, m.start()) + 1
|
|
loop_header = m.group(0)
|
|
body = _extract_balanced_brace_body(clean, m.end() - 1)
|
|
if body is None:
|
|
continue
|
|
full_loop = loop_header + body
|
|
if not any(r in body for r in read_hints):
|
|
continue
|
|
if not any(h in full_loop for h in poll_hints):
|
|
continue
|
|
guarded = _has_verified_bus_loss_exit(body, pascal_helper_ok)
|
|
entries.append(
|
|
{
|
|
"id": f"{p.name}:L{line_no}",
|
|
"domain": "mmio_bus_loss_guards",
|
|
"status": "PORTED" if guarded else "MISSING",
|
|
"stock_evidence": "target/stock-580-kmods/nvidia/nv-kernel.o_binary (GPU bus-loss 0xffffffff poll guard)",
|
|
"rust_location": f"src/nvidia/kernel/{p.name}:L{line_no}",
|
|
"verification": (
|
|
"comment-stripped balanced-brace bus-loss condition+exit audit"
|
|
if guarded
|
|
else None
|
|
),
|
|
"note": (
|
|
"Verified comment-stripped loop-body bus-loss comparison (u32::MAX / 0xffff_ffff or checked helper) with break/return exit"
|
|
if guarded
|
|
else "MMIO poll loop missing verified bus-loss comparison + exit"
|
|
),
|
|
}
|
|
)
|
|
return entries
|
|
|
|
|
|
def audit_rm_classes() -> list[dict]:
|
|
"""Enumerate all RM allocatable classes from the 580.178.04 GV100 oracle class DB
|
|
plus every architecture-mapped class ID emitted by records_for_arch (Maxwell..Blackwell)."""
|
|
cdb_gv100 = (ROOT / "src" / "nvidia" / "src" / "rmapi" / "providers" / "class_db_gv100.rs").read_text()
|
|
cdb_rs = (ROOT / "src" / "nvidia" / "src" / "rmapi" / "providers" / "class_db.rs").read_text()
|
|
entries = []
|
|
seen: set[int] = set()
|
|
ENGINE_INVALID = 0xB33B1500
|
|
valid_classes: set[int] = set()
|
|
invalid_classes: list[tuple[int, int]] = []
|
|
for m in re.finditer(r"\(\s*(0x[0-9a-fA-F]+)\s*,\s*(0x[0-9a-fA-F]+)\s*\)", cdb_gv100):
|
|
cls = int(m.group(1), 16)
|
|
eng = int(m.group(2), 16)
|
|
if cls == 0xFFFFFFFF or eng == ENGINE_INVALID:
|
|
invalid_classes.append((cls, eng))
|
|
continue
|
|
if cls in seen:
|
|
continue
|
|
seen.add(cls)
|
|
valid_classes.add(cls)
|
|
entries.append(
|
|
{
|
|
"id": f"0x{cls:04x}",
|
|
"domain": "rm_classes",
|
|
"status": "PORTED",
|
|
"stock_evidence": f"target/stock-580-kmods/nvidia/nv-kernel.o_binary (GPU+0xd90 class_db eng=0x{eng:08x})",
|
|
"rust_location": "src/nvidia/src/rmapi/providers/class_db_gv100.rs + class_db.rs",
|
|
"verification": "tools/check_rmapi_binary.py (gpu-slice3b) + cargo test rmapi::providers::class_db",
|
|
"note": f"GV100 580.178.04 class 0x{cls:04x} (eng=0x{eng:08x}) enumerated and served via 0x800292/0x800201",
|
|
}
|
|
)
|
|
for cls, eng in invalid_classes:
|
|
if cls in seen or cls in valid_classes:
|
|
continue
|
|
seen.add(cls)
|
|
entries.append(
|
|
{
|
|
"id": f"0x{cls:04x}",
|
|
"domain": "rm_classes",
|
|
"status": "INTENTIONALLY_EXCLUDED",
|
|
"stock_evidence": f"target/stock-580-kmods/nvidia/nv-kernel.o_binary (GPU+0xd90 class_db eng=0x{eng:08x} ENGINE_INVALID)",
|
|
"rust_location": "src/nvidia/src/rmapi/providers/class_db.rs",
|
|
"verification": None,
|
|
"note": f"Filtered out by ENGINE_INVALID (0x{ENGINE_INVALID:08x}) in class_db::records, matching stock _nv030181rm",
|
|
}
|
|
)
|
|
# Enumerate every additional per-architecture mapped class ID emitted by records_for_arch
|
|
# (from chip_arch::arch_classes + class_db.rs direct mappings such as 0xb069 / 0xc0b5).
|
|
chip_arch_rs = (ROOT / "src" / "nvidia" / "src" / "gpu" / "chip_arch.rs").read_text()
|
|
m_ac = re.search(r"pub const fn arch_classes\b[^{]*\{", chip_arch_rs)
|
|
ac_body = _extract_balanced_brace_body(chip_arch_rs, m_ac.end() - 1) if m_ac else ""
|
|
clean_cdb = strip_rust_comments(cdb_rs)
|
|
test_pos = clean_cdb.find("#[cfg(test)]")
|
|
impl_cdb = clean_cdb[:test_pos] if test_pos != -1 else clean_cdb
|
|
for src_label, src_text in [
|
|
("src/nvidia/src/gpu/chip_arch.rs::arch_classes", ac_body or ""),
|
|
("src/nvidia/src/rmapi/providers/class_db.rs", impl_cdb),
|
|
]:
|
|
for m in re.finditer(r"\b0x([0-9a-fA-F]{4})\b", src_text):
|
|
cls = int(m.group(1), 16)
|
|
if cls in seen or cls in (0xFFF0, 0xFFFF):
|
|
continue
|
|
seen.add(cls)
|
|
entries.append(
|
|
{
|
|
"id": f"0x{cls:04x}",
|
|
"domain": "rm_classes",
|
|
"status": "PORTED",
|
|
"stock_evidence": f"{src_label} (per-arch mapped class 0x{cls:04x})",
|
|
"rust_location": "src/nvidia/src/rmapi/providers/class_db.rs + src/nvidia/src/gpu/chip_arch.rs",
|
|
"verification": "cargo test rmapi::providers::class_db",
|
|
"note": f"Per-architecture mapped RM class 0x{cls:04x} emitted by records_for_arch/map_class_for_arch",
|
|
}
|
|
)
|
|
# Per-architecture family class-DB coverage rows
|
|
arch_checks = [
|
|
("arch:maxwell_gm10x_gm20x", "ArchFamily::Maxwell1", "Maxwell GM10x/GM20x class translation"),
|
|
("arch:pascal_gp10x", "ArchFamily::Pascal", "Pascal GP10x class translation"),
|
|
("arch:volta_gv100", "ArchFamily::Volta", "Volta GV100 native oracle class DB"),
|
|
("arch:turing_tu10x", "ArchFamily::Turing", "Turing TU10x/TU11x class translation"),
|
|
("arch:ampere_ga10x", "ArchFamily::Ampere", "Ampere GA100/GA10x class translation"),
|
|
("arch:ada_ad10x", "ArchFamily::Ada", "Ada AD10x class translation"),
|
|
("arch:hopper_gh100", "ArchFamily::Hopper", "Hopper GH100 class translation"),
|
|
("arch:blackwell_gb10x_gb20x", "ArchFamily::Blackwell2", "Blackwell GB10x/GB20x class translation"),
|
|
]
|
|
for arch_id, needle, desc in arch_checks:
|
|
present = needle in (ac_body or "")
|
|
entries.append(
|
|
{
|
|
"id": arch_id,
|
|
"domain": "rm_classes",
|
|
"status": "PORTED" if present else "MISSING",
|
|
"stock_evidence": "src/nvidia/src/rmapi/providers/class_db.rs + src/nvidia/src/gpu/chip_arch.rs",
|
|
"rust_location": "src/nvidia/src/rmapi/providers/class_db.rs" if present else None,
|
|
"verification": "cargo test rmapi::providers::class_db" if present else None,
|
|
"note": desc,
|
|
}
|
|
)
|
|
return entries
|
|
|
|
|
|
def audit_gsp_rm_rpcs(open_gpu_root: pathlib.Path) -> list[dict]:
|
|
"""Enumerate GSP-RM RPC functions and async events from rpc_global_enums.h under
|
|
--open-gpu-root (tagging 620.x additions separately from 580.178.04), plus R620 framing."""
|
|
rpc_h_path = open_gpu_root / "src" / "nvidia" / "inc" / "kernel" / "vgpu" / "rpc_global_enums.h"
|
|
if not rpc_h_path.exists():
|
|
raise RuntimeError(f"Missing rpc_global_enums.h under --open-gpu-root: {rpc_h_path}")
|
|
rpc_h = rpc_h_path.read_text()
|
|
|
|
# Collect bare-metal GSP-RM (IS_GSP_CLIENT) RPC names from OpenRM rpc.c + kernel_gsp*.c
|
|
rpc_c_path = open_gpu_root / "src" / "nvidia" / "src" / "kernel" / "vgpu" / "rpc.c"
|
|
gsp_dir = open_gpu_root / "src" / "nvidia" / "src" / "kernel" / "gpu" / "gsp"
|
|
if not rpc_c_path.exists() or not gsp_dir.exists():
|
|
raise RuntimeError(
|
|
f"Missing OpenRM GSP RPC sources under --open-gpu-root: {rpc_c_path}, {gsp_dir}"
|
|
)
|
|
rpc_c = rpc_c_path.read_text(errors="ignore")
|
|
gsp_client_rpcs: set[str] = set()
|
|
for fn in re.split(r"\n(?=NV_STATUS\s+rpc\w+)", rpc_c):
|
|
m_all = re.findall(r"NV_VGPU_MSG_FUNCTION_(\w+)", fn)
|
|
if not m_all:
|
|
continue
|
|
if (
|
|
"IS_GSP_CLIENT" in fn
|
|
or "GSP_SET_SYSTEM_INFO" in fn
|
|
or "GSP_RM_" in fn
|
|
or "GET_GSP_STATIC_INFO" in fn
|
|
):
|
|
gsp_client_rpcs.update(m_all)
|
|
for p in gsp_dir.rglob("*.c"):
|
|
for name in re.findall(r"NV_VGPU_MSG_FUNCTION_(\w+)", p.read_text(errors="ignore")):
|
|
if name not in ("NUM_FUNCTIONS", "NOP"):
|
|
gsp_client_rpcs.add(name)
|
|
|
|
our_gsp_files = [
|
|
ROOT / "src" / "nvidia" / "src" / "gpu" / "ga10x_gsp.rs",
|
|
ROOT / "src" / "nvidia" / "src" / "gpu" / "gsp_rpc.rs",
|
|
ROOT / "src" / "nvidia" / "src" / "gpu" / "gsp_transport.rs",
|
|
ROOT / "src" / "nvidia" / "kernel" / "ga10x_gsp.rs",
|
|
ROOT / "src" / "nvidia" / "kernel" / "gsp_bringup.rs",
|
|
ROOT / "src" / "nvidia" / "kernel" / "gsp_route.rs",
|
|
ROOT / "src" / "nvidia" / "kernel" / "ga10x_objects.rs",
|
|
]
|
|
our_gsp_txt = strip_rust_comments(
|
|
"\n".join(p.read_text(errors="ignore") for p in our_gsp_files if p.exists())
|
|
)
|
|
# Only count RPCs/events that are actually referenced in send/dispatch logic (not bare pub consts)
|
|
declared_fn: dict[int, str] = {}
|
|
for m_mod in re.finditer(r"pub mod (?:function|func)\s*\{([^}]+)\}", our_gsp_txt):
|
|
for name, val in re.findall(
|
|
r"pub const (\w+)\s*:\s*u32\s*=\s*(0x[0-9a-fA-F_]+|\d+);", m_mod.group(1)
|
|
):
|
|
declared_fn[int(val.replace("_", ""), 0)] = name
|
|
used_fn_ids: dict[int, str] = {}
|
|
for val, name in declared_fn.items():
|
|
if re.search(rf"\b(?:function|func)::{name}\b", our_gsp_txt):
|
|
used_fn_ids[val] = name
|
|
|
|
declared_ev: dict[int, str] = {}
|
|
for m_mod in re.finditer(r"pub mod event\s*\{([^}]+)\}", our_gsp_txt):
|
|
for name, val in re.findall(
|
|
r"pub const (\w+)\s*:\s*u32\s*=\s*(0x[0-9a-fA-F_]+|\d+);", m_mod.group(1)
|
|
):
|
|
declared_ev[int(val.replace("_", ""), 0)] = name
|
|
used_ev_ids: dict[int, str] = {}
|
|
for val, name in declared_ev.items():
|
|
if re.search(rf"\bevent::{name}\b", our_gsp_txt) or re.search(
|
|
rf"\bfunction::EVENT_{name}\b", our_gsp_txt
|
|
):
|
|
used_ev_ids[val] = name
|
|
|
|
# Bare-metal GSP-RM RPCs that are debug/protobuf/vGPU-legacy only and not required for runtime parity
|
|
excluded_gsp_rpcs = {
|
|
"SET_GUEST_SYSTEM_INFO": "vGPU guest-only handshake (bare-metal GSP-RM uses GSP_SET_SYSTEM_INFO 72)",
|
|
"ALLOC_MEMORY": "Legacy vGPU RPC superseded by GSP_RM_ALLOC (103) on bare-metal GSP-RM",
|
|
"ALLOC_CHANNEL_DMA": "Legacy vGPU RPC superseded by GSP_RM_ALLOC (103) on bare-metal GSP-RM",
|
|
"UPDATE_BAR_PDE": "Host BAR2 PDE update handled directly via BAR0/VRAM page tables in ga10x_gsp.rs",
|
|
"DUMP_PROTOBUF_COMPONENT": "Proprietary NVIDIA protobuf crash-dump collector (out of scope for clean-room driver)",
|
|
"ECC_NOTIFIER_WRITE_ACK": "Optional GSP-to-CPU ECC notifier ack (ECC faults handled via GSP_RM_CONTROL + async events)",
|
|
"CTRL_DBG_GET_MODE_MMU_GCC_DEBUG": "Internal NVIDIA MODS/GCC MMU debug RPC",
|
|
"INIT_GSP_TRACE_CRASH_BUFFER": "Optional GSP crash-trace ring buffer (LibOS print events already decoded via EVENT_UCODE_LIBOS_PRINT)",
|
|
"SAVE_HIBERNATION_DATA": "Windows S4 hibernation guest save RPC (not used on Linux bare-metal GSP-RM)",
|
|
"RESTORE_HIBERNATION_DATA": "Windows S4 hibernation guest restore RPC (not used on Linux bare-metal GSP-RM)",
|
|
"RM_API_CONTROL": "Legacy vGPU control wrapper superseded by GSP_RM_CONTROL (76) on bare-metal GSP-RM",
|
|
"SEND_GUEST_STUN_COMPLETION": "vGPU live-migration stun ack (not used on bare-metal GSP-RM)",
|
|
}
|
|
|
|
entries = []
|
|
# 1. All X(UNIT, RPC, VAL) functions (580.178.04: 0..=227; 620.x additions: >= 228)
|
|
for unit, name, val_s, tail in re.findall(
|
|
r"^\s*X\s*\(\s*(\w+)\s*,\s*(\w+)\s*,\s*(\d+)\s*\)(.*)$", rpc_h, re.M
|
|
):
|
|
val = int(val_s)
|
|
is_dep = "deprecated" in tail.lower()
|
|
prefix = "r620_rpc" if val >= 228 else "rpc"
|
|
if name in excluded_gsp_rpcs:
|
|
status = "INTENTIONALLY_EXCLUDED"
|
|
rust_loc = None
|
|
verif = None
|
|
note = excluded_gsp_rpcs[name]
|
|
elif val in used_fn_ids:
|
|
status = "PORTED"
|
|
rust_loc = "src/nvidia/src/gpu/ga10x_gsp.rs + src/nvidia/kernel/ga10x_gsp.rs"
|
|
verif = "cargo test gpu::ga10x_gsp"
|
|
note = f"Bare-metal GSP-RM RPC {val} ({name}) dispatched via {used_fn_ids[val]}"
|
|
elif is_dep:
|
|
status = "INTENTIONALLY_EXCLUDED"
|
|
rust_loc = None
|
|
verif = None
|
|
note = f"Deprecated in rpc_global_enums.h ({unit})"
|
|
elif name not in gsp_client_rpcs:
|
|
status = "INTENTIONALLY_EXCLUDED"
|
|
rust_loc = None
|
|
verif = None
|
|
note = "vGPU-guest-only RPC (not issued by bare-metal IS_GSP_CLIENT in OpenRM rpc.c)"
|
|
else:
|
|
status = "MISSING"
|
|
rust_loc = None
|
|
verif = None
|
|
note = f"Bare-metal GSP-RM RPC {val} ({name}) issued by OpenRM IS_GSP_CLIENT"
|
|
entries.append(
|
|
{
|
|
"id": f"{prefix}:{val}:NV_VGPU_MSG_FUNCTION_{name}",
|
|
"domain": "gsp_rm_rpcs",
|
|
"status": status,
|
|
"stock_evidence": f"open-gpu-kernel-modules/src/nvidia/inc/kernel/vgpu/rpc_global_enums.h (X({unit}, {name}, {val}))",
|
|
"rust_location": rust_loc,
|
|
"verification": verif,
|
|
"note": note,
|
|
}
|
|
)
|
|
|
|
# 2. All E(EVENT, VAL) async events (580.178.04: <= 0x1023; 620.x additions: >= 0x1024)
|
|
for name, val_s, tail in re.findall(
|
|
r"^\s*E\s*\(\s*(\w+)\s*,\s*(0x[0-9a-fA-F]+|\d+)\s*\)(.*)$", rpc_h, re.M
|
|
):
|
|
val = int(val_s, 0)
|
|
prefix = "r620_event" if val >= 0x1024 else "event"
|
|
if name in ("FIRST_EVENT", "NUM_EVENTS"):
|
|
status = "INTENTIONALLY_EXCLUDED"
|
|
rust_loc = None
|
|
verif = None
|
|
note = f"Sentinel enum boundary {name} (0x{val:x}), not an executable event"
|
|
elif val in used_ev_ids:
|
|
status = "PORTED"
|
|
rust_loc = "src/nvidia/src/gpu/ga10x_gsp.rs + src/nvidia/kernel/ga10x_gsp.rs"
|
|
verif = "cargo test gpu::ga10x_gsp"
|
|
note = f"GSP-RM async event 0x{val:x} ({name}) decoded in event dispatch"
|
|
else:
|
|
status = "INTENTIONALLY_EXCLUDED"
|
|
rust_loc = None
|
|
verif = None
|
|
note = f"Auxiliary/diagnostic GSP-RM async event 0x{val:x} ({name}); safely skipped by default event loop"
|
|
entries.append(
|
|
{
|
|
"id": f"{prefix}:0x{val:x}:NV_VGPU_MSG_EVENT_{name}",
|
|
"domain": "gsp_rm_rpcs",
|
|
"status": status,
|
|
"stock_evidence": f"open-gpu-kernel-modules/src/nvidia/inc/kernel/vgpu/rpc_global_enums.h (E({name}, 0x{val:x}))",
|
|
"rust_location": rust_loc,
|
|
"verification": verif,
|
|
"note": note,
|
|
}
|
|
)
|
|
|
|
# 3. R620 MCTP/NVDM queue framing
|
|
r620_ok = "frame_element_abi_r620_writes_mctp_nvdm_and_round_trips" in our_gsp_txt
|
|
entries.append(
|
|
{
|
|
"id": "r620:MCTP_NVDM_QUEUE_FRAMING",
|
|
"domain": "gsp_rm_rpcs",
|
|
"status": "PORTED" if r620_ok else "MISSING",
|
|
"stock_evidence": "analysis/gsp-620-framing.md (R620 MCTP+NVDM queue element framing)",
|
|
"rust_location": "src/nvidia/src/gpu/ga10x_gsp.rs" if r620_ok else None,
|
|
"verification": "cargo test gpu::ga10x_gsp::tests::frame_element_abi_r620_writes_mctp_nvdm_and_round_trips" if r620_ok else None,
|
|
"note": "R620 MCTP+NVDM element encoder/decoder verified by round-trip unit tests",
|
|
}
|
|
)
|
|
return entries
|
|
|
|
|
|
def audit_uvm_620() -> list[dict]:
|
|
"""Enumerate R620 UVM interface extensions across interface_dispatch.rs and uvm_bridge.c."""
|
|
disp = (ROOT / "src" / "nvidia" / "src" / "uvm" / "interface_dispatch.rs").read_text()
|
|
bridge_c = (ROOT / "kernel-open" / "uvm_bridge" / "uvm_bridge.c").read_text()
|
|
ops = [
|
|
("r620_uvm:AccessBitsBufAlloc", "nvUvmInterfaceAccessBitsBufAlloc", "access_bits_buf_alloc"),
|
|
("r620_uvm:AccessBitsBufFree", "nvUvmInterfaceAccessBitsBufFree", "access_bits_buf_free"),
|
|
("r620_uvm:AccessBitsBufDump", "nvUvmInterfaceAccessBitsDump", "access_bits_buf_dump"),
|
|
("r620_uvm:RegisterUvmEvents", "nvUvmInterfaceRegisterUvmEvents", "register_uvm_events"),
|
|
("r620_uvm:DeRegisterUvmEvents", "nvUvmInterfaceDeRegisterUvmEvents", "deregister_uvm_events"),
|
|
]
|
|
entries = []
|
|
for op_id, sym, fn_name in ops:
|
|
m = re.search(rf"\bfn\s+{fn_name}\b[^{{]*\{{", disp)
|
|
body = _extract_balanced_brace_body(disp, m.end() - 1) if m else None
|
|
mc = re.search(rf"\b(?:NV_STATUS|void)\s+{sym}\s*\([^)]*\)\s*\{{", bridge_c)
|
|
c_body = _extract_balanced_brace_body(bridge_c, mc.end() - 1) if mc else None
|
|
c_stub = c_body is None or "return NV_ERR_NOT_SUPPORTED;" in c_body
|
|
if body is None:
|
|
status = "MISSING"
|
|
note = f"R620 UVM interface op {sym} missing"
|
|
elif "NV_ERR_NOT_SUPPORTED" in body or "status::NOT_SUPPORTED" in body or c_stub:
|
|
status = "PARTIAL"
|
|
note = f"R620 UVM interface op {sym} has Rust slot/validation logic but uvm_bridge.c or ring dump still returns NV_ERR_NOT_SUPPORTED"
|
|
else:
|
|
status = "PORTED"
|
|
note = f"R620 UVM interface op {sym} wired end-to-end in uvm_bridge.c + interface_dispatch.rs"
|
|
entries.append(
|
|
{
|
|
"id": op_id,
|
|
"domain": "uvm_ioctls_620",
|
|
"status": status,
|
|
"stock_evidence": f"R620 nvidia-uvm.ko interface ({sym})",
|
|
"rust_location": (
|
|
f"src/nvidia/src/uvm/interface_dispatch.rs::{fn_name} + kernel-open/uvm_bridge/uvm_bridge.c"
|
|
if body is not None
|
|
else None
|
|
),
|
|
"verification": "cargo test uvm::interface_dispatch" if status == "PORTED" else None,
|
|
"note": note,
|
|
}
|
|
)
|
|
return entries
|
|
|
|
|
|
def audit_firmware_commands() -> list[dict]:
|
|
"""Enumerate microcontroller/firmware command protocols (PMU, FECS/GPCCS, SEC2/ACR, FWSEC, FSP, Devinit, Video)."""
|
|
specs = [
|
|
("fw:pmu_fbq_transport", "src/nvidia/src/gpu/pmu_fbq.rs", "pub struct Transport", "PMU FBQ queue init/send/receive RPC transport", "cargo test gpu::pmu_fbq"),
|
|
("fw:pmu_dmem_transport", "src/nvidia/src/gpu/pmu_dmem.rs", "pub fn write_command", "PMU DMEM command queue transport", "cargo test gpu::pmu_dmem"),
|
|
("fw:pmu_events_dispatch", "src/nvidia/src/gpu/pmu_events.rs", "pub fn handler(", "PMU unit event/reply dispatcher", "cargo test gpu::pmu_events"),
|
|
("fw:pmu_acr_region_request", "src/nvidia/src/gpu/pmu_fbq.rs", "pub fn region_request", "PMU ACR function 0 WPR region request", "cargo test gpu::pmu_fbq"),
|
|
("fw:pmu_acr_bootstrap_request", "src/nvidia/src/gpu/pmu_fbq.rs", "pub fn bootstrap_request", "PMU ACR function 2 falcon bootstrap request", "cargo test gpu::pmu_fbq"),
|
|
("fw:pmu_hbm_clock", "src/nvidia/src/gpu/hbm_clock.rs", "pub struct HbmCoeff", "GV100/GP100 HBM2 PLL COEFF clock programming", "cargo test gpu::hbm_clock"),
|
|
("fw:fecs_mailbox_protocol", "src/nvidia/src/gpu/fecs_mailbox.rs", "pub fn ", "FECS/GPCCS mailbox & ctxsw method protocol", "cargo test --test fecs_mailbox"),
|
|
("fw:gr_netlist_load", "src/nvidia/src/gpu/gr_netlist.rs", "pub fn ", "GR FECS/GPCCS netlist bundle parsing & load", "cargo test --test gr_netlist"),
|
|
("fw:acr_load_bar2_direct", "src/nvidia/src/gpu/acr_load.rs", "pub fn ", "SEC2/PMU ACR HS-binary direct BAR2 load & WPR setup", "cargo test gpu::acr_load"),
|
|
("fw:acr_unload", "src/nvidia/src/gpu/acr_unload.rs", "pub fn ", "ACR WPR teardown & falcon reset", "cargo test gpu::acr_unload"),
|
|
("fw:fwsec_v2_v3_frts_sb", "src/nvidia/src/gpu/ga10x_gsp.rs", "pub fn find_fwsec_for_family", "Turing/Ampere/Ada FWSEC V2/V3 FRTS & SB boot", "cargo test gpu::ga10x_gsp"),
|
|
("fw:fsp_cot_fmc_boot", "src/nvidia/src/gpu/gsp_boot.rs", "pub fn ", "Hopper/Blackwell FSP COT/FMC & RISC-V boot", "cargo test gpu::gsp_boot"),
|
|
("fw:vbios_devinit", "src/nvidia/src/gpu/vbios_devinit.rs", "pub fn ", "Pre-GSP cold-POST VBIOS BIT/Devinit interpreter", "cargo test gpu::vbios_devinit"),
|
|
("fw:video_falcon", "src/nvidia/src/gpu/video_falcon.rs", "pub fn ", "NVDEC/NVENC falcon bootstrap & command framing", "cargo test gpu::video_falcon"),
|
|
]
|
|
entries = []
|
|
for op_id, rel, needle, desc, verif in specs:
|
|
p = ROOT / rel
|
|
ok = p.exists() and needle in p.read_text(errors="ignore")
|
|
if op_id == "subsys:mig_capabilities":
|
|
rmapi_txt = p.read_text(errors="ignore") if p.exists() else ""
|
|
gpu_txt = (ROOT / "src" / "nvidia" / "src" / "rmapi" / "gpu.rs").read_text(errors="ignore")
|
|
ok = (
|
|
"NV_RS_CAP_MINOR_MIG_CONFIG" in rmapi_txt
|
|
and "NV_RS_CAP_MINOR_MIG_MONITOR" in rmapi_txt
|
|
and "CMD_GPU_SET_MIG_MODE" in gpu_txt
|
|
and "CLASS_AMPERE_SMC_PARTITION_REF" in gpu_txt
|
|
)
|
|
entries.append(
|
|
{
|
|
"id": op_id,
|
|
"domain": "firmware_commands",
|
|
"status": "PORTED" if ok else "MISSING",
|
|
"stock_evidence": f"target/stock-580-kmods/nvidia/nv-kernel.o_binary ({desc})",
|
|
"rust_location": rel if ok else None,
|
|
"verification": verif if ok else None,
|
|
"note": desc,
|
|
}
|
|
)
|
|
entries.append(
|
|
{
|
|
"id": "fw:acr_load_copy_engine",
|
|
"domain": "firmware_commands",
|
|
"status": "INTENTIONALLY_EXCLUDED",
|
|
"stock_evidence": "src/nvidia/src/gpu/acr_load.rs (Unsupported::CopyEngine)",
|
|
"rust_location": "src/nvidia/src/gpu/acr_load.rs",
|
|
"verification": None,
|
|
"note": "Copy-engine-assisted ACR load branch (direct BAR2 load path is used on GV100/pre-GSP)",
|
|
}
|
|
)
|
|
return entries
|
|
|
|
|
|
def audit_subsystem_operations() -> list[dict]:
|
|
"""Enumerate cross-cutting Display, Power, Thermal, Clock, MIG, ECC, and NVLink operations."""
|
|
specs = [
|
|
("subsys:display_dcb_connectors", "src/nvidia/src/gpu/display_outputs.rs", "pub ", "VBIOS DCB 4.x connector & SOR enumeration", "cargo test gpu::display_outputs"),
|
|
("subsys:display_core_channels", "src/nvidia/src/gpu/display_channels.rs", "pub ", "Display core/window/cursor channel state machine", "cargo test gpu::display_channels"),
|
|
("subsys:display_dp_aux", "src/nvidia/src/gpu/dp_aux.rs", "pub ", "DisplayPort AUX EDID/DPCD transport", "cargo test gpu::dp_aux"),
|
|
("subsys:display_vrr_gsync", "src/nvidia/src/gpu/vrr_gsync.rs", "pub ", "VRR / G-SYNC timing & state control", "cargo test gpu::vrr_gsync"),
|
|
("subsys:power_limit_telemetry", "src/nvidia/src/rmapi/nvml_ctrl.rs", "pub fn ", "Board power limit & live mW telemetry (INA3221/PMU/GSP)", "cargo test rmapi::nvml_ctrl"),
|
|
("subsys:thermal_sensor", "src/nvidia/src/rmapi/gpu.rs", "temp_celsius", "Live GPU thermal sensor readout (NV_THERM_I2CS_SENSOR_00)", "cargo test rmapi::gpu_tests"),
|
|
("subsys:clock_vbios_p0_vf", "src/nvidia/src/rmapi/nvml_ctrl.rs", "pub fn read_prom_vbios_p0_clocks", "Per-board PROM VBIOS P0/Boost/CUDA_MAX clock ratings & VF", "cargo test rmapi::nvml_ctrl"),
|
|
("subsys:fb_geometry_discovery", "src/nvidia/src/rmapi/gpu.rs", "pub struct FbGeometry", "Live hardware FB bus-width, RAM type, FBP, LTC/LTS & L2 discovery", "cargo test rmapi::gpu_tests"),
|
|
("subsys:mig_capabilities", "kernel-open/nvidia/rmapi_node.c", "NV_RS_CAP_MINOR_MIG_MONITOR", "MIG config/monitor capability nodes & SMC partition/MIG controls", "cargo test rmapi::gpu_tests"),
|
|
("subsys:ecc_fbpa_and_poison", "src/nvidia/src/gpu/ecc_poison.rs", "pub ", "FBPA DRAM ECC counters, VBIOS ECC gate, and poison tracking", "cargo test gpu::ecc_poison"),
|
|
("subsys:nvlink_caps_and_ce", "src/nvidia/src/rmapi/gpu.rs", "active_nvlink_mask", "NVLink active link detection, caps/status, and CE PCE-LCE mapping", "cargo test rmapi::gpu_tests"),
|
|
]
|
|
entries = []
|
|
for op_id, rel, needle, desc, verif in specs:
|
|
p = ROOT / rel
|
|
ok = p.exists() and needle in p.read_text(errors="ignore")
|
|
if op_id == "subsys:mig_capabilities":
|
|
rmapi_txt = p.read_text(errors="ignore") if p.exists() else ""
|
|
gpu_txt = (ROOT / "src" / "nvidia" / "src" / "rmapi" / "gpu.rs").read_text(errors="ignore")
|
|
ok = (
|
|
"NV_RS_CAP_MINOR_MIG_CONFIG" in rmapi_txt
|
|
and "NV_RS_CAP_MINOR_MIG_MONITOR" in rmapi_txt
|
|
and "CMD_GPU_SET_MIG_MODE" in gpu_txt
|
|
and "CLASS_AMPERE_SMC_PARTITION_REF" in gpu_txt
|
|
)
|
|
entries.append(
|
|
{
|
|
"id": op_id,
|
|
"domain": "subsystem_operations",
|
|
"status": "PORTED" if ok else "MISSING",
|
|
"stock_evidence": f"target/stock-580-kmods/nvidia/nv-kernel.o_binary ({desc})",
|
|
"rust_location": rel if ok else None,
|
|
"verification": verif if ok else None,
|
|
"note": desc,
|
|
}
|
|
)
|
|
return entries
|
|
|
|
|
|
SUBSYSTEM_OWNERS = [
|
|
("rmapi_escapes", "morebrackets", "tools, oracles, RM escape ABI"),
|
|
("rm_control_table_580", "morebrackets", "2,107/2,107 580.178.04 RM control table & oracles"),
|
|
("rm_controls_userspace", "gdevenyi", "libcuda / libnvidia-ml control parity"),
|
|
("rm_classes", "gdevenyi", "0x800292 per-chip class DB & constructors"),
|
|
("gsp_rm_rpcs", "brauliobo", "GA10x/GB20x GSP-RM RPCs & R620 framing"),
|
|
("uvm_ioctls", "PiercingXX", "UVM 580 ioctl & VA-space parity"),
|
|
("uvm_ioctls_620", "ChrisMythos", "UVM 620.x ABI & AD102/Blackwell support"),
|
|
("drm_ioctls", "ChrisMythos", "nvidia-drm UAPI & DMA-BUF / syncobj"),
|
|
("nvkms_ioctls", "ChrisMythos", "nvidia-modeset NVKMS ioctl state machine"),
|
|
("firmware_commands", "brauliobo", "PMU / FECS / SEC2 / ACR / FWSEC / FSP protocols"),
|
|
("subsystem_operations", "gdevenyi", "Display / Power / Thermal / Clock / MIG / ECC / NVLink"),
|
|
("procfs_and_caps", "LIghtJUNction", "Install, packaging, procfs, and capability nodes"),
|
|
("mmio_bus_loss_guards", "morebrackets", "MMIO bus-loss & kernel module hygiene gates"),
|
|
]
|
|
|
|
|
|
def normalize_entry(e: dict) -> dict:
|
|
"""Ensure every row carries both the legacy keys and #381 canonical operation-inventory keys."""
|
|
raw_id = str(e["id"])
|
|
parts = raw_id.split(":")
|
|
if len(parts) >= 3:
|
|
op_id = f"{parts[0]}:{parts[1]}"
|
|
name = ":".join(parts[2:])
|
|
elif len(parts) == 2 and (parts[0].startswith("0x") or parts[0].isdigit()):
|
|
op_id, name = parts[0], parts[1]
|
|
elif len(parts) == 2:
|
|
op_id, name = raw_id, parts[1]
|
|
else:
|
|
op_id, name = raw_id, raw_id
|
|
out = dict(e)
|
|
out.setdefault("stock_evidence", None)
|
|
out.setdefault("rust_location", None)
|
|
out.setdefault("verification", None)
|
|
out["op_id"] = op_id
|
|
out["name"] = name
|
|
out["subsystem"] = e["domain"]
|
|
out["binary_handler"] = out["stock_evidence"]
|
|
out["port_status"] = e["status"].lower()
|
|
out["rust_impl"] = out["rust_location"]
|
|
out["oracle_test"] = out["verification"]
|
|
return out
|
|
|
|
|
|
def render_markdown(report: dict) -> str:
|
|
lines = [
|
|
"# Stock 580.178.04 Closed-World Parity Ledger & Operation Inventory (#381)",
|
|
"",
|
|
"Generated by `python3 tools/build_parity_ledger.py` against stock 580.178.04 kernel modules, OpenRM 580.178.04 headers, and host `libcuda.so.1` / `libnvidia-ml.so.1`.",
|
|
"",
|
|
"| Domain | PORTED | PARTIAL | MISSING | INTENTIONALLY_EXCLUDED |",
|
|
"|---|---:|---:|---:|---:|",
|
|
]
|
|
for dom, c in report["summary"].items():
|
|
lines.append(
|
|
f"| `{dom}` | {c['PORTED']} | {c['PARTIAL']} | {c['MISSING']} | {c['INTENTIONALLY_EXCLUDED']} |"
|
|
)
|
|
t = report["totals"]
|
|
lines.append(
|
|
f"| **TOTAL** | **{t['PORTED']}** | **{t['PARTIAL']}** | **{t['MISSING']}** | **{t['INTENTIONALLY_EXCLUDED']}** |"
|
|
)
|
|
lines.append("")
|
|
lines.append("## Subsystem Ownership Map (#381 Phase 4)")
|
|
lines.append("")
|
|
lines.append("Integrator & merge authority: **@ehartford**")
|
|
lines.append("")
|
|
lines.append("| Subsystem | Primary Owner | Scope |")
|
|
lines.append("|---|---|---|")
|
|
for subsys, owner, scope in SUBSYSTEM_OWNERS:
|
|
lines.append(f"| `{subsys}` | `@{owner}` | {scope} |")
|
|
lines.append("")
|
|
lines.append("## Remaining `MISSING` / `PARTIAL` Entries")
|
|
lines.append("")
|
|
rem = [e for e in report["entries"] if e["status"] in ("MISSING", "PARTIAL")]
|
|
if not rem:
|
|
lines.append("None — 0 `MISSING` and 0 `PARTIAL` entries remain across all enumerated categories.")
|
|
else:
|
|
for e in rem:
|
|
lines.append(
|
|
f"- **[{e['status']}]** `{e['domain']}` `{e['id']}` — {e['note']}"
|
|
)
|
|
return "\n".join(lines) + "\n"
|
|
|
|
|
|
def write_markdown(report: dict) -> None:
|
|
(ROOT / "docs" / "PARITY_LEDGER.md").write_text(render_markdown(report))
|
|
|
|
|
|
def parse_args() -> argparse.Namespace:
|
|
ap = argparse.ArgumentParser(description=__doc__)
|
|
ap.add_argument(
|
|
"--stock-dir",
|
|
type=pathlib.Path,
|
|
default=pathlib.Path(
|
|
os.environ.get("NV_RS_STOCK_KMODS_DIR", str(ROOT / "target" / "stock-580-kmods"))
|
|
),
|
|
help="Directory containing extracted 580.178.04 stock kernel modules",
|
|
)
|
|
ap.add_argument(
|
|
"--open-gpu-root",
|
|
type=pathlib.Path,
|
|
default=pathlib.Path(
|
|
os.environ.get("OPEN_GPU_ROOT", "/home/geodd/open-gpu-kernel-modules")
|
|
),
|
|
help="Path to open-gpu-kernel-modules checkout containing SDK ctrl & NVKMS headers",
|
|
)
|
|
ap.add_argument(
|
|
"--libcuda",
|
|
type=pathlib.Path,
|
|
default=pathlib.Path(
|
|
os.environ.get("NV_RS_LIBCUDA", "/usr/lib/x86_64-linux-gnu/libcuda.so.1")
|
|
),
|
|
help="Path to host libcuda.so.1",
|
|
)
|
|
ap.add_argument(
|
|
"--libnvml",
|
|
type=pathlib.Path,
|
|
default=pathlib.Path(
|
|
os.environ.get(
|
|
"NV_RS_LIBNVML", "/usr/lib/x86_64-linux-gnu/libnvidia-ml.so.1"
|
|
)
|
|
),
|
|
help="Path to host libnvidia-ml.so.1",
|
|
)
|
|
ap.add_argument(
|
|
"--strict",
|
|
action="store_true",
|
|
help="Fail non-zero if any domain is empty, any PORTED row lacks rust_impl/oracle_test, or any dispatch entry is unmapped",
|
|
)
|
|
ap.add_argument(
|
|
"--check",
|
|
action="store_true",
|
|
help="Verify reports/parity_ledger_580.json and docs/PARITY_LEDGER.md are up-to-date without modifying them",
|
|
)
|
|
return ap.parse_args()
|
|
|
|
|
|
def main() -> int:
|
|
args = parse_args()
|
|
open_gpu_ctrl = args.open_gpu_root / "src" / "common" / "sdk" / "nvidia" / "inc" / "ctrl"
|
|
|
|
required_paths = [
|
|
("stock nv-kernel.o_binary", args.stock_dir / "nvidia" / "nv-kernel.o_binary"),
|
|
("stock nvidia-uvm.ko", args.stock_dir / "nvidia-uvm.ko"),
|
|
("stock nvidia-drm.ko", args.stock_dir / "nvidia-drm.ko"),
|
|
("stock nvidia-modeset.ko", args.stock_dir / "nvidia-modeset.ko"),
|
|
("open-gpu ctrl headers", open_gpu_ctrl),
|
|
(
|
|
"open-gpu rpc_global_enums.h",
|
|
args.open_gpu_root / "src" / "nvidia" / "inc" / "kernel" / "vgpu" / "rpc_global_enums.h",
|
|
),
|
|
(
|
|
"open-gpu rpc.c",
|
|
args.open_gpu_root / "src" / "nvidia" / "src" / "kernel" / "vgpu" / "rpc.c",
|
|
),
|
|
(
|
|
"open-gpu GSP sources",
|
|
args.open_gpu_root / "src" / "nvidia" / "src" / "kernel" / "gpu" / "gsp",
|
|
),
|
|
("libcuda.so.1", args.libcuda),
|
|
("libnvidia-ml.so.1", args.libnvml),
|
|
]
|
|
missing_inputs = [f"{label}: {p}" for label, p in required_paths if not p.exists()]
|
|
if missing_inputs:
|
|
print("ERROR: missing required parity ledger inputs:", file=sys.stderr)
|
|
for item in missing_inputs:
|
|
print(f" - {item}", file=sys.stderr)
|
|
return 2
|
|
|
|
dispatched_cmds = collect_dispatched_rm_controls()
|
|
raw_entries = (
|
|
audit_escapes()
|
|
+ audit_control_table(dispatched_cmds)
|
|
+ audit_rm_controls_userspace(
|
|
dispatched_cmds,
|
|
args.stock_dir,
|
|
open_gpu_ctrl,
|
|
args.libcuda,
|
|
args.libnvml,
|
|
)
|
|
+ audit_rm_classes()
|
|
+ audit_gsp_rm_rpcs(args.open_gpu_root)
|
|
+ audit_uvm(args.stock_dir)
|
|
+ audit_uvm_620()
|
|
+ audit_drm(args.stock_dir)
|
|
+ audit_nvkms(args.stock_dir, args.open_gpu_root)
|
|
+ audit_firmware_commands()
|
|
+ audit_subsystem_operations()
|
|
+ audit_procfs_and_caps()
|
|
+ audit_mmio_bus_loss_guards()
|
|
)
|
|
all_entries = [normalize_entry(e) for e in raw_entries]
|
|
|
|
by_domain: dict[str, dict[str, int]] = {}
|
|
for e in all_entries:
|
|
d = by_domain.setdefault(
|
|
e["domain"],
|
|
{"PORTED": 0, "PARTIAL": 0, "MISSING": 0, "INTENTIONALLY_EXCLUDED": 0},
|
|
)
|
|
d[e["status"]] += 1
|
|
|
|
if args.strict:
|
|
strict_errors: list[str] = []
|
|
expected_domains = [s[0] for s in SUBSYSTEM_OWNERS]
|
|
for dom in expected_domains:
|
|
if dom not in by_domain or sum(by_domain[dom].values()) == 0:
|
|
strict_errors.append(f"domain '{dom}' is missing or empty")
|
|
for e in all_entries:
|
|
if e["status"] == "MISSING" and e["domain"] == "rm_control_table_580":
|
|
strict_errors.append(f"control command {e['id']} is not dispatched")
|
|
if e["status"] == "PORTED":
|
|
if not e.get("rust_impl"):
|
|
strict_errors.append(f"PORTED entry {e['domain']}:{e['id']} missing rust_impl")
|
|
if not e.get("oracle_test"):
|
|
strict_errors.append(f"PORTED entry {e['domain']}:{e['id']} missing oracle_test")
|
|
if strict_errors:
|
|
print("ERROR: --strict parity ledger checks failed:", file=sys.stderr)
|
|
for err in strict_errors[:25]:
|
|
print(f" - {err}", file=sys.stderr)
|
|
return 3
|
|
|
|
report = {
|
|
"reference_driver": "580.178.04",
|
|
"subsystem_owners": [
|
|
{"subsystem": s, "owner": o, "scope": sc} for s, o, sc in SUBSYSTEM_OWNERS
|
|
],
|
|
"summary": by_domain,
|
|
"totals": {
|
|
k: sum(v[k] for v in by_domain.values())
|
|
for k in ("PORTED", "PARTIAL", "MISSING", "INTENTIONALLY_EXCLUDED")
|
|
},
|
|
"entries": all_entries,
|
|
}
|
|
json_text = json.dumps(report, indent=2) + "\n"
|
|
md_text = render_markdown(report)
|
|
json_path = ROOT / "reports" / "parity_ledger_580.json"
|
|
md_path = ROOT / "docs" / "PARITY_LEDGER.md"
|
|
|
|
if args.check:
|
|
diffs = []
|
|
if not json_path.exists() or json_path.read_text() != json_text:
|
|
diffs.append(str(json_path))
|
|
if not md_path.exists() or md_path.read_text() != md_text:
|
|
diffs.append(str(md_path))
|
|
if diffs:
|
|
print("ERROR: parity ledger out of sync (re-run python3 tools/build_parity_ledger.py):", file=sys.stderr)
|
|
for d in diffs:
|
|
print(f" - {d}", file=sys.stderr)
|
|
return 4
|
|
print("OK: parity ledger JSON and Markdown are up-to-date and strict-clean.")
|
|
else:
|
|
json_path.write_text(json_text)
|
|
md_path.write_text(md_text)
|
|
|
|
print("=== Closed-World 580.178.04 Parity Ledger Summary ===")
|
|
for dom, counts in by_domain.items():
|
|
print(
|
|
f" {dom:24s} | PORTED:{counts['PORTED']:4d} | PARTIAL:{counts['PARTIAL']:2d} | MISSING:{counts['MISSING']:3d} | EXCL:{counts['INTENTIONALLY_EXCLUDED']:2d}"
|
|
)
|
|
print(f" {'TOTAL':24s} | {report['totals']}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|