Files
nvdriver/tools/check_modeset_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

565 lines
23 KiB
Python
Executable File

#!/usr/bin/env python3
"""Verify 100% symbol & CONFIG_MODVERSIONS CRC conformance for stock nvidia-modeset.ko and nvidia-drm.ko.
Checks:
1. Every undefined symbol in stock nvidia-modeset.ko and nvidia-drm.ko that is provided
by stock nvidia.ko (`nvidia_get_rm_ops`) is exported by
`kernel-open/modeset_bridge/nvidia_rs_modeset_bridge.ko`.
2. Every CONFIG_MODVERSIONS CRC in stock nvidia-modeset.ko / nvidia-drm.ko matches
`nvidia_rs_modeset_bridge.ko`'s Module.symvers 100% (so stock modules load cleanly
without --force).
3. Every undefined symbol in stock nvidia-drm.ko provided by stock nvidia-modeset.ko
(`nvKmsKapi*`) has matching CRCs between stock nvidia-drm.ko and stock nvidia-modeset.ko.
4. Every `nv_rs_modeset_*` symbol imported by `nvidia_rs_modeset_bridge.ko` is defined in
`kernel-open/nvidia/nv-rust.o_binary` and exported by `kernel-open/nvidia_rs.ko` with
matching CRC.
5. `nvidia_rs.ko` itself does NOT export `nvidia_get_rm_ops` 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-modeset` / `nvidia-drm` / `nvidia`). `--stock-modeset-ko`,
`--stock-drm-ko` and `--stock-nvidia-ko` (or the `NV_RS_STOCK_MODESET_KO`,
`NV_RS_STOCK_DRM_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/modeset_bridge/nvidia_rs_modeset_bridge.ko"
BRIDGE_SYMVERS = ROOT / "kernel-open/modeset_bridge/Module.symvers"
UVM_BRIDGE_KO = ROOT / "kernel-open/uvm_bridge/nvidia_rs_uvm_bridge.ko"
UVM_BRIDGE_SYMVERS = ROOT / "kernel-open/uvm_bridge/Module.symvers"
REPORT_OUT = ROOT / "reports/modeset-symbol-conformance.json"
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_modeset_ko: str,
stock_drm_ko: str,
stock_nv_ko: str,
stock_nv_def: set[str],
stock_ms_def: set[str],
stock_ms_und: set[str],
stock_drm_und: set[str],
stock_ms_crcs: dict[str, str] | None,
stock_drm_crcs: dict[str, str] | None,
combined_symvers: dict[str, str],
combined_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,
allowed_crc_differences: frozenset[str] = frozenset(),
stock_modeset_symvers: dict[str, str] | None = None,
require_stock_pair_check: bool = False,
) -> dict:
required_from_nvidia = sorted((stock_ms_und | stock_drm_und) & stock_nv_def)
drm_from_modeset = sorted(stock_drm_und & stock_ms_def)
modversions_inputs = (
("stock_modeset", stock_ms_crcs),
("stock_drm", stock_drm_crcs),
("bridge", bridge_modvers),
)
modversions_flags = tuple(crcs is not None for _, crcs in modversions_inputs)
modversions_enabled = all(modversions_flags)
modversions_mismatch = any(modversions_flags) and not modversions_enabled
missing_modversions_inputs = (
[name for name, crcs in modversions_inputs if crcs is None]
if modversions_mismatch
else []
)
if modversions_enabled:
assert stock_ms_crcs is not None and stock_drm_crcs is not None and bridge_modvers is not None
stock_required_crcs = {**stock_drm_crcs, **stock_ms_crcs}
crc_mismatches = [
{"symbol": s, "stock_crc": stock_required_crcs.get(s), "bridge_crc": combined_symvers.get(s)}
for s in required_from_nvidia
if stock_required_crcs.get(s) != combined_symvers.get(s)
]
elif modversions_mismatch:
stock_required_crcs = {**(stock_drm_crcs or {}), **(stock_ms_crcs or {})}
if bridge_modvers is not None:
crc_mismatches = [
{
"symbol": s,
"stock_crc": stock_required_crcs.get(s),
"bridge_crc": combined_symvers.get(s),
}
for s in required_from_nvidia
if s in stock_required_crcs
and s in combined_symvers
and stock_required_crcs.get(s) != combined_symvers.get(s)
]
else:
crc_mismatches = []
else:
stock_required_crcs = {}
crc_mismatches = []
missing_bridge_exports = [
s for s in required_from_nvidia if s not in combined_symvers or s not in combined_def
]
bridge_nv_rs_imports = sorted(s for s in bridge_und if s.startswith("nv_rs_modeset_"))
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_collisions = sorted(s for s in nv_rs_symvers if s in required_from_nvidia)
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)
stock_pair_checked = stock_modeset_symvers is not None and stock_drm_crcs is not None
stock_pair_crc_mismatches = []
if stock_modeset_symvers is not None and stock_drm_crcs is not None:
stock_pair_crc_mismatches = [
{
"symbol": symbol,
"drm_import_crc": stock_drm_crcs.get(symbol),
"modeset_export_crc": stock_modeset_symvers.get(symbol),
}
for symbol in drm_from_modeset
if symbol.startswith("nvKmsKapi")
and (
symbol not in stock_drm_crcs
or symbol not in stock_modeset_symvers
or stock_drm_crcs[symbol] != stock_modeset_symvers[symbol]
)
]
exact_checks = {
"stock_required_nvidia_symbol_count_nonzero": len(required_from_nvidia) > 0,
"all_stock_modeset_drm_nvidia_symbols_exported_by_bridge": len(missing_bridge_exports) == 0,
"all_stock_modeset_drm_modversions_crcs_match": (not modversions_mismatch) and not unexpected_crc_mismatches,
}
internal_checks = {
"stock_drm_modeset_nvkmskapi_crcs_match": (
(not stock_pair_crc_mismatches)
and (stock_pair_checked or not require_stock_pair_check)
),
"all_bridge_rust_ffi_handlers_linked_and_exported": (
len(bridge_nv_rs_imports) == 8
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_nvidia_get_rm_ops_collision_in_nvidia_rs": len(nv_rs_direct_collisions) == 0,
}
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_modeset_ko": stock_modeset_ko,
"stock_drm_ko": stock_drm_ko,
"stock_nvidia_ko": stock_nv_ko,
"required_from_nvidia": required_from_nvidia,
"drm_from_modeset": drm_from_modeset,
"allowed_crc_differences": sorted(allowed_crc_differences),
"allowed_crc_mismatches": allowed_crc_mismatches,
"unexpected_crc_mismatches": unexpected_crc_mismatches,
"stock_drm_modeset_nvkmskapi_checked": stock_pair_checked,
"stock_drm_modeset_nvkmskapi_crc_mismatches": stock_pair_crc_mismatches,
"required_symbol_count": len(required_from_nvidia),
"bridge_exported_count": len(required_from_nvidia) - len(missing_bridge_exports),
"exact_crc_match_count": (len(required_from_nvidia) - len(crc_mismatches)) if modversions_enabled else 0,
"rust_ffi_backing_count": len(bridge_nv_rs_imports),
"symbol_crcs": {
s: {
"stock": stock_required_crcs.get(s) if modversions_enabled else None,
"bridge": combined_symvers.get(s) if modversions_enabled else None,
}
for s in required_from_nvidia
},
"checks": checks,
"missing_bridge_exports": missing_bridge_exports,
"missing_modversions_inputs": missing_modversions_inputs,
"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_collisions": nv_rs_direct_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-modeset-ko",
help="stock nvidia-modeset.ko to compare against (default: modinfo -n nvidia-modeset)",
)
parser.add_argument(
"--stock-drm-ko",
help="stock nvidia-drm.ko to compare against (default: modinfo -n nvidia-drm)",
)
parser.add_argument(
"--stock-nvidia-ko",
help="stock nvidia.ko that provides the RM ops (default: modinfo -n nvidia)",
)
parser.add_argument(
"--report",
help="report path (default: reports/modeset-symbol-conformance.json)",
)
parser.add_argument(
"--stock-symvers",
help=(
"stock Module.symvers used to cross-check the stock nvidia-drm.ko <- "
"nvidia-modeset.ko nvKmsKapi* CRCs (default: Module.symvers next to the "
"stock modules, when present)"
),
)
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_modeset_ko = stock_module(
args.stock_modeset_ko, "NV_RS_STOCK_MODESET_KO", "nvidia-modeset"
)
stock_drm_ko = stock_module(args.stock_drm_ko, "NV_RS_STOCK_DRM_KO", "nvidia-drm")
stock_nv_ko = stock_module(args.stock_nvidia_ko, "NV_RS_STOCK_NVIDIA_KO", "nvidia")
for p in (stock_modeset_ko, stock_drm_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_modeset_ko or args.stock_drm_ko or args.stock_nvidia_ko or args.stock_symvers)
or any(os.environ.get(key) for key in (
"NV_RS_STOCK_MODESET_KO", "NV_RS_STOCK_DRM_KO", "NV_RS_STOCK_NVIDIA_KO",
))
or bool(args.allow_crc_difference)
)
skipped_exact_gate = bool(
not strict_conformance
and reference_version
and stock_nvidia_version
and stock_nvidia_version != reference_version
)
stock_nv_def, _ = parse_elf_symbols(stock_nv_ko)
stock_ms_def, stock_ms_und = parse_elf_symbols(stock_modeset_ko)
_, stock_drm_und = parse_elf_symbols(stock_drm_ko)
stock_ms_crcs = parse_modversions(stock_modeset_ko)
stock_drm_crcs = parse_modversions(stock_drm_ko)
bridge_symvers = parse_symvers(BRIDGE_SYMVERS)
bridge_def, bridge_und = parse_elf_symbols(BRIDGE_KO)
bridge_modvers = parse_modversions(BRIDGE_KO)
# Shared kernel-compat helpers (e.g. nv_vma_start_write on Linux 7.0) are
# exported once by nvidia_rs_uvm_bridge.ko so both bridge modules can be
# loaded simultaneously without duplicate symbol collisions.
combined_symvers = dict(bridge_symvers)
combined_def = set(bridge_def)
if UVM_BRIDGE_SYMVERS.exists() and UVM_BRIDGE_KO.exists():
uvm_symvers = parse_symvers(UVM_BRIDGE_SYMVERS)
uvm_def, _ = parse_elf_symbols(UVM_BRIDGE_KO)
for sym, crc in uvm_symvers.items():
if sym not in combined_symvers and not sym.startswith("nvUvmInterface"):
combined_symvers[sym] = crc
for sym in uvm_def:
if not sym.startswith("nvUvmInterface"):
combined_def.add(sym)
nv_rs_symvers = parse_symvers(NVIDIA_RS_SYMVERS)
rust_def, _ = parse_elf_symbols(RUST_OBJ)
stock_symvers_path = (
Path(args.stock_symvers) if args.stock_symvers
else stock_modeset_ko.parent / "Module.symvers"
)
if args.stock_symvers and not stock_symvers_path.is_file():
print(f"ERROR: missing stock symbol versions: {stock_symvers_path}", file=sys.stderr)
return 2
stock_modeset_symvers = parse_symvers(stock_symvers_path) if stock_symvers_path.is_file() else None
report = evaluate_conformance(
stock_modeset_ko=str(stock_modeset_ko),
stock_drm_ko=str(stock_drm_ko),
stock_nv_ko=str(stock_nv_ko),
stock_nv_def=stock_nv_def,
stock_ms_def=stock_ms_def,
stock_ms_und=stock_ms_und,
stock_drm_und=stock_drm_und,
stock_ms_crcs=stock_ms_crcs,
stock_drm_crcs=stock_drm_crcs,
combined_symvers=combined_symvers,
combined_def=combined_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,
allowed_crc_differences=frozenset(args.allow_crc_difference),
stock_modeset_symvers=stock_modeset_symvers,
require_stock_pair_check=bool(args.stock_symvers),
)
report["stock_symvers"] = str(stock_symvers_path) if stock_modeset_symvers is not None else None
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"],
"symbol_crcs": report["symbol_crcs"],
"checks": report["checks"],
}))
return 0 if passed else 1
if __name__ == "__main__":
raise SystemExit(main())