Files
nvdriver/tools/check_uvm_symbol_conformance.py
harmless_teddy e8ba298d38 Verify stock requirements in UVM and modeset bridge checks (#462)
* Verify stock requirements in UVM and modeset bridge checks

* fix(tools): require stock pair check for explicit --stock-symvers and check access-bits from stock_uvm_und

---------

Co-authored-by: Codex <codex@openai.com>
Co-authored-by: Eric Hartford <eric@quixi.ai>
2026-12-04 21:08:46 -08:00

484 lines
19 KiB
Python
Executable File

#!/usr/bin/env python3
"""Verify 100% symbol & CONFIG_MODVERSIONS CRC conformance for stock nvidia-uvm.ko.
Checks:
1. Every undefined symbol in stock nvidia-uvm.ko that is provided by stock nvidia.ko
(all 76 nvUvmInterface* symbols) is exported by kernel-open/uvm_bridge/nvidia_rs_uvm_bridge.ko.
2. Every CONFIG_MODVERSIONS CRC in stock nvidia-uvm.ko matches nvidia_rs_uvm_bridge.ko's
Module.symvers 76/76 (so stock nvidia-uvm.ko loads cleanly without --force).
3. Every nv_rs_uvm_iface_* symbol imported by nvidia_rs_uvm_bridge.ko is defined in
kernel-open/nvidia/nv-rust.o_binary and exported by kernel-open/nvidia_rs.ko with
matching CRC (76/76).
4. nvidia_rs.ko itself does NOT export nvUvmInterface* directly (preserving side-by-side
Dual-GPU Parity compatibility with stock nvidia.ko on the host).
By default the stock modules are the ones installed on the host
(`modinfo -n nvidia-uvm` / `modinfo -n nvidia`). `--stock-uvm-ko` and
`--stock-nvidia-ko` (or the `NV_RS_STOCK_UVM_KO` / `NV_RS_STOCK_NVIDIA_KO`
environment variables) point the comparison at a stock build tree instead, so the
same check can run against a locally built stock module set.
"""
from __future__ import annotations
from contextlib import contextmanager
import argparse
import json
import os
import re
import shutil
import struct
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import Iterator
ROOT = Path(__file__).resolve().parents[1]
VERSION_MK = ROOT / "version.mk"
RUST_OBJ = ROOT / "kernel-open/nvidia/nv-rust.o_binary"
NVIDIA_RS_KO = ROOT / "kernel-open/nvidia_rs.ko"
NVIDIA_RS_SYMVERS = ROOT / "kernel-open/Module.symvers"
BRIDGE_KO = ROOT / "kernel-open/uvm_bridge/nvidia_rs_uvm_bridge.ko"
BRIDGE_SYMVERS = ROOT / "kernel-open/uvm_bridge/Module.symvers"
REPORT_OUT = ROOT / "reports/uvm-symbol-conformance.json"
# Rust handlers behind the 620.73.04 access-bits entry points. They are not
# part of the stock 580 symbol set, but the bridge has to reach them: stock
# UVM allocates one access-bits buffer per parent GPU and aborts the whole GPU
# registration when the allocation fails (uvm_gpu.c:3034-3038).
R620_ACCESS_BITS_SYMBOLS = frozenset({
"nvUvmInterfaceAccessBitsBufAlloc",
"nvUvmInterfaceAccessBitsBufFree",
"nvUvmInterfaceAccessBitsDump",
})
R620_ACCESS_BITS_HANDLERS = (
"nv_rs_uvm_iface_access_bits_buf_alloc",
"nv_rs_uvm_iface_access_bits_buf_free",
"nv_rs_uvm_iface_access_bits_buf_dump",
)
def find_tool(name: str) -> str:
return shutil.which(name) or f"/sbin/{name}"
def run(*args: str) -> str:
return subprocess.check_output(args, text=True)
@contextmanager
def uncompressed_ko(path: Path) -> Iterator[Path]:
suffix = path.suffix
if suffix not in (".zst", ".xz", ".gz"):
yield path
return
cmd = {".zst": ["zstd", "-dc"], ".xz": ["xz", "-dc"], ".gz": ["gzip", "-dc"]}[suffix]
with tempfile.TemporaryDirectory(prefix="nvrs-ko-") as tmpdir:
out = Path(tmpdir) / path.stem
out.write_bytes(subprocess.check_output(cmd + [str(path)]))
yield out
def parse_elf_symbols(path: Path) -> tuple[set[str], set[str]]:
defined: set[str] = set()
undefined: set[str] = set()
with uncompressed_ko(path) as ko:
for line in run("readelf", "-sW", str(ko)).splitlines():
parts = line.split()
if len(parts) < 8 or not parts[0].endswith(":"):
continue
bind, ndx, name = parts[4], parts[6], parts[7]
if ndx == "UND":
undefined.add(name)
elif bind == "GLOBAL":
defined.add(name)
return defined, undefined
MODVERSION_SECTION_NAMES = frozenset({
"__versions",
"__version_ext_crcs",
"__version_ext_names",
})
_SECTION_HEADER_RE = re.compile(r"^\s*\[\s*\d+\]\s+(\S+)")
def has_modversions_section(ko_path: Path) -> bool:
for line in run("readelf", "-SW", str(ko_path)).splitlines():
m = _SECTION_HEADER_RE.match(line)
if m and m.group(1) in MODVERSION_SECTION_NAMES:
return True
return False
def read_reference_driver_version(path: Path = VERSION_MK) -> str:
if not path.exists():
return ""
for line in path.read_text().splitlines():
if line.startswith("REFERENCE_DRIVER_VERSION"):
_, _, value = line.partition(":=")
if not value:
_, _, value = line.partition("=")
return value.strip()
return ""
_SYMBOL_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_.]*$")
# struct modversion_info { unsigned long crc; char name[MODULE_NAME_LEN - sizeof(unsigned long)]; }
_MODULE_NAME_LEN = 64
_ULONG_SIZE = struct.calcsize("N")
# GNU readelf pads the bracketed index ("[ 5]"), so match the row instead of splitting it.
_SECTION_ROW_RE = re.compile(r"^\s*\[\s*\d+\]\s+(\S+)\s+\S+\s+\S+\s+(\S+)\s+(\S+)")
def read_section_bytes(ko: Path, section: str) -> bytes | None:
"""Raw bytes of an ELF section, or None when the section is absent."""
for line in run("readelf", "-SW", str(ko)).splitlines():
match = _SECTION_ROW_RE.match(line)
if match and match.group(1) == section:
offset, size = int(match.group(2), 16), int(match.group(3), 16)
return ko.read_bytes()[offset : offset + size]
return None
def _parse_compact_versions(data: bytes) -> dict[str, str] | None:
"""Variable-length {u32 len; u32 crc; char name[]} records, or None if absent."""
out: dict[str, str] = {}
offset = 0
while offset < len(data):
if data[offset:] == b"\0" * (len(data) - offset):
break
if offset + 8 > len(data):
return None
length, crc = struct.unpack_from("<II", data, offset)
if length < 9 or offset + length > len(data):
return None
name = data[offset + 8 : offset + length].split(b"\0")[0].decode("ascii", "replace")
if not _SYMBOL_NAME_RE.match(name):
return None
out[name] = f"0x{crc:08x}"
offset += length
return out or None
def parse_versions_section(data: bytes) -> dict[str, str]:
"""symbol -> CRC from a __versions section.
`modprobe --dump-modversions` only understands the fixed-layout records older kernels
emit: struct modversion_info is MODULE_NAME_LEN bytes, an unsigned long CRC followed by
the name padded to the rest. Kernels that moved to compact records store variable-length
{u32 len; u32 crc; char name[]} entries and kmod rejects the whole section with EINVAL,
so read both layouts here.
"""
compact = _parse_compact_versions(data)
if compact is not None:
return compact
out: dict[str, str] = {}
for index in range(0, len(data) - len(data) % _MODULE_NAME_LEN, _MODULE_NAME_LEN):
crc = int.from_bytes(data[index : index + _ULONG_SIZE], "little") & 0xFFFFFFFF
name = data[index + _ULONG_SIZE : index + _MODULE_NAME_LEN]
name = name.split(b"\0")[0].decode("ascii", "replace")
if name:
out[name] = f"0x{crc:08x}"
return out
def parse_modversions(path: Path) -> dict[str, str] | None:
"""Return symbol -> CRC mapping from __versions, or None if CONFIG_MODVERSIONS is off."""
out: dict[str, str] = {}
modprobe_bin = find_tool("modprobe")
with uncompressed_ko(path) as ko:
proc = subprocess.run(
[modprobe_bin, "--dump-modversions", str(ko)],
capture_output=True,
text=True,
)
if proc.returncode != 0:
if not has_modversions_section(ko):
return None
section = read_section_bytes(ko, "__versions")
parsed = parse_versions_section(section) if section else {}
if parsed:
return parsed
if proc.stderr:
print(proc.stderr, file=sys.stderr, end="")
raise subprocess.CalledProcessError(
proc.returncode, proc.args, output=proc.stdout, stderr=proc.stderr
)
for line in proc.stdout.splitlines():
parts = line.split()
if len(parts) == 2:
out[parts[1]] = parts[0]
return out
def parse_symvers(path: Path) -> dict[str, str]:
out: dict[str, str] = {}
for line in path.read_text().splitlines():
parts = line.split()
if len(parts) >= 2:
out[parts[1]] = parts[0]
return out
def evaluate_conformance(
*,
stock_uvm_ko: str,
stock_nv_ko: str,
stock_uvm_und: set[str],
stock_nv_def: set[str],
stock_uvm_crcs: dict[str, str] | None,
bridge_symvers: dict[str, str],
bridge_def: set[str],
bridge_und: set[str],
bridge_modvers: dict[str, str] | None,
nv_rs_symvers: dict[str, str],
rust_def: set[str],
reference_driver_version: str = "",
stock_nvidia_version: str = "",
skipped_exact_gate: bool = False,
expected_symbol_count: int = 76,
allowed_crc_differences: frozenset[str] = frozenset(),
) -> dict:
required_uvm_syms = sorted(stock_uvm_und & stock_nv_def)
missing_bridge_exports = [s for s in required_uvm_syms if s not in bridge_symvers or s not in bridge_def]
modversions_enabled = stock_uvm_crcs is not None and bridge_modvers is not None
modversions_mismatch = (stock_uvm_crcs is None) != (bridge_modvers is None)
if modversions_enabled:
assert stock_uvm_crcs is not None and bridge_modvers is not None
crc_mismatches = [
{"symbol": s, "stock_crc": stock_uvm_crcs.get(s), "bridge_crc": bridge_symvers.get(s)}
for s in required_uvm_syms
if stock_uvm_crcs.get(s) != bridge_symvers.get(s)
]
elif modversions_mismatch:
crc_mismatches = [
{
"symbol": s,
"stock_crc": None if stock_uvm_crcs is None else stock_uvm_crcs.get(s),
"bridge_crc": None if bridge_modvers is None else bridge_symvers.get(s),
}
for s in required_uvm_syms
]
else:
crc_mismatches = []
bridge_nv_rs_imports = sorted(s for s in bridge_und if s.startswith("nv_rs_uvm_iface_"))
missing_rust_defs = [s for s in bridge_nv_rs_imports if s not in rust_def]
missing_nv_rs_exports = [s for s in bridge_nv_rs_imports if s not in nv_rs_symvers]
if bridge_modvers is not None:
bridge_to_nv_rs_crc_mismatches = [
{"symbol": s, "bridge_crc": bridge_modvers.get(s), "nv_rs_crc": nv_rs_symvers.get(s)}
for s in bridge_nv_rs_imports
if bridge_modvers.get(s) != nv_rs_symvers.get(s)
]
elif modversions_mismatch:
bridge_to_nv_rs_crc_mismatches = [
{"symbol": s, "bridge_crc": None, "nv_rs_crc": nv_rs_symvers.get(s)}
for s in bridge_nv_rs_imports
]
else:
bridge_to_nv_rs_crc_mismatches = []
nv_rs_direct_uvm_collisions = sorted(s for s in nv_rs_symvers if s.startswith("nvUvmInterface"))
required_uvm_iface_syms = [s for s in required_uvm_syms if s.startswith("nvUvmInterface")]
missing_access_bits_handlers = [
s for s in R620_ACCESS_BITS_HANDLERS if s not in bridge_nv_rs_imports
]
# The host's stock UVM may need these even when exact stock CRC checks are skipped.
check_access_bits = (
bool(R620_ACCESS_BITS_SYMBOLS.intersection(stock_uvm_und))
or expected_symbol_count >= 79
or len(missing_access_bits_handlers) < len(R620_ACCESS_BITS_HANDLERS)
)
expected_backing_count = 76 + (len(R620_ACCESS_BITS_HANDLERS) if check_access_bits else 0)
allowed_crc_mismatches = []
unexpected_crc_mismatches = []
for mismatch in crc_mismatches:
if (mismatch["symbol"] in allowed_crc_differences
and mismatch["stock_crc"] is not None and mismatch["bridge_crc"] is not None):
allowed_crc_mismatches.append(mismatch)
else:
unexpected_crc_mismatches.append(mismatch)
exact_checks = {
"stock_uvm_required_symbol_count_matches_expectation": len(required_uvm_iface_syms) == expected_symbol_count,
"all_stock_uvm_symbols_exported_by_bridge": len(missing_bridge_exports) == 0,
"all_stock_uvm_modversions_crcs_match": (not modversions_mismatch) and not unexpected_crc_mismatches,
}
internal_checks = {
"all_expected_rust_ffi_handlers_linked_and_exported": (
len(bridge_nv_rs_imports) == expected_backing_count
and len(missing_rust_defs) == 0
and len(missing_nv_rs_exports) == 0
),
"bridge_to_nvidia_rs_modversions_crcs_match": (not modversions_mismatch) and len(bridge_to_nv_rs_crc_mismatches) == 0,
"no_direct_nvUvmInterface_collision_in_nvidia_rs": len(nv_rs_direct_uvm_collisions) == 0,
}
if check_access_bits:
internal_checks["r620_access_bits_handlers_wired"] = not missing_access_bits_handlers
checks = {**exact_checks, **internal_checks}
passed = all(internal_checks.values()) if skipped_exact_gate else all(checks.values())
return {
"passed": passed,
"modversions_enabled": modversions_enabled,
"reference_driver_version": reference_driver_version,
"stock_nvidia_version": stock_nvidia_version,
"skipped_exact_gate": skipped_exact_gate,
"stock_uvm_ko": str(stock_uvm_ko),
"stock_nvidia_ko": str(stock_nv_ko),
"expected_symbol_count": expected_symbol_count,
"allowed_crc_differences": sorted(allowed_crc_differences),
"allowed_crc_mismatches": allowed_crc_mismatches,
"missing_access_bits_handlers": missing_access_bits_handlers,
"unexpected_crc_mismatches": unexpected_crc_mismatches,
"required_symbol_count": len(required_uvm_syms),
"bridge_exported_count": len(required_uvm_syms) - len(missing_bridge_exports),
"exact_crc_match_count": (len(required_uvm_syms) - len(crc_mismatches)) if modversions_enabled else 0,
"rust_ffi_backing_count": len(bridge_nv_rs_imports),
"checks": checks,
"missing_bridge_exports": missing_bridge_exports,
"crc_mismatches": crc_mismatches,
"missing_rust_defs": missing_rust_defs,
"missing_nv_rs_exports": missing_nv_rs_exports,
"bridge_to_nv_rs_crc_mismatches": bridge_to_nv_rs_crc_mismatches,
"nv_rs_direct_uvm_collisions": nv_rs_direct_uvm_collisions,
}
def stock_module(explicit: str | None, env: str, module: str) -> Path:
"""Locate a stock module: explicit path, environment override, or modinfo."""
if explicit:
return Path(explicit)
from_env = os.environ.get(env)
if from_env:
return Path(from_env)
return Path(run(find_tool("modinfo"), "-n", module).strip())
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument(
"--stock-uvm-ko",
help="stock nvidia-uvm.ko to compare against (default: modinfo -n nvidia-uvm)",
)
parser.add_argument(
"--stock-nvidia-ko",
help="stock nvidia.ko that provides the interface (default: modinfo -n nvidia)",
)
parser.add_argument(
"--report",
help="report path (default: reports/uvm-symbol-conformance.json)",
)
parser.add_argument(
"--expected-symbol-count",
type=int,
default=76,
help="number of required nvUvmInterface* symbols the stock tree must import",
)
parser.add_argument(
"--allow-crc-difference",
action="append",
default=[],
metavar="SYMBOL",
help=(
"stock symbol whose CONFIG_MODVERSIONS CRC is known to differ because the "
"stock tree is a different driver version (repeatable)"
),
)
args = parser.parse_args()
report_out = Path(args.report) if args.report else REPORT_OUT
for p in (RUST_OBJ, NVIDIA_RS_KO, NVIDIA_RS_SYMVERS, BRIDGE_KO, BRIDGE_SYMVERS):
if not p.exists():
print(f"ERROR: missing build artifact: {p}", file=sys.stderr)
return 2
modinfo_bin = find_tool("modinfo")
stock_uvm_ko = stock_module(args.stock_uvm_ko, "NV_RS_STOCK_UVM_KO", "nvidia-uvm")
stock_nv_ko = stock_module(
args.stock_nvidia_ko, "NV_RS_STOCK_NVIDIA_KO", "nvidia"
)
for p in (stock_uvm_ko, stock_nv_ko):
if not p.exists():
print(f"ERROR: missing stock module: {p}", file=sys.stderr)
return 2
reference_version = read_reference_driver_version()
stock_nvidia_version = run(modinfo_bin, "-F", "version", str(stock_nv_ko)).strip()
strict_conformance = (
os.environ.get("NV_RS_STRICT_CONFORMANCE") == "1"
or bool(args.stock_uvm_ko or args.stock_nvidia_ko)
or bool(os.environ.get("NV_RS_STOCK_UVM_KO") or os.environ.get("NV_RS_STOCK_NVIDIA_KO"))
or bool(args.allow_crc_difference)
or args.expected_symbol_count != 76
)
skipped_exact_gate = bool(
not strict_conformance
and reference_version
and stock_nvidia_version
and stock_nvidia_version != reference_version
)
_, stock_uvm_und = parse_elf_symbols(stock_uvm_ko)
stock_nv_def, _ = parse_elf_symbols(stock_nv_ko)
stock_uvm_crcs = parse_modversions(stock_uvm_ko)
bridge_symvers = parse_symvers(BRIDGE_SYMVERS)
bridge_def, bridge_und = parse_elf_symbols(BRIDGE_KO)
bridge_modvers = parse_modversions(BRIDGE_KO)
nv_rs_symvers = parse_symvers(NVIDIA_RS_SYMVERS)
rust_def, _ = parse_elf_symbols(RUST_OBJ)
report = evaluate_conformance(
stock_uvm_ko=str(stock_uvm_ko),
stock_nv_ko=str(stock_nv_ko),
stock_uvm_und=stock_uvm_und,
stock_nv_def=stock_nv_def,
stock_uvm_crcs=stock_uvm_crcs,
bridge_symvers=bridge_symvers,
bridge_def=bridge_def,
bridge_und=bridge_und,
bridge_modvers=bridge_modvers,
nv_rs_symvers=nv_rs_symvers,
rust_def=rust_def,
reference_driver_version=reference_version,
stock_nvidia_version=stock_nvidia_version,
skipped_exact_gate=skipped_exact_gate,
expected_symbol_count=args.expected_symbol_count,
allowed_crc_differences=frozenset(args.allow_crc_difference),
)
passed = report["passed"]
if skipped_exact_gate:
print(
f"NOTE: stock nvidia.ko is {stock_nvidia_version} (reference is {reference_version}); "
f"skipping exact stock symbol/CRC gate (measured {report['exact_crc_match_count']}/{report['required_symbol_count']} CRC matches); "
"internal bridge <-> nvidia_rs.ko wiring checks still enforced.",
file=sys.stderr,
)
report_out.parent.mkdir(parents=True, exist_ok=True)
report_out.write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps({
"passed": passed,
"modversions_enabled": report["modversions_enabled"],
"reference_driver_version": reference_version,
"stock_nvidia_version": stock_nvidia_version,
"skipped_exact_gate": skipped_exact_gate,
"required_symbols": report["required_symbol_count"],
"exact_crc_matches": report["exact_crc_match_count"],
"rust_ffi_backing": report["rust_ffi_backing_count"],
"checks": report["checks"],
}))
return 0 if passed else 1
if __name__ == "__main__":
raise SystemExit(main())