#!/usr/bin/env python3 """Offline check of the pointer deny-lists (`nv_rs_core::gpu::gsp_pointer_controls`) against an NVIDIA open-gpu-kernel-modules tree of 620 or 580. Needs no GPU and no module. The release comes from the tree's version.mk (`NVIDIA_VERSION`) and picks the list: 620.x checks `NVP64_CONTROLS_620` (the R620 ABI), 580.x checks `NVP64_CONTROLS_580` (the R580 ABI). That list must be exactly the controls the tree's RM exports (the NVOC method tables of src/nvidia/generated/g_*_nvoc.c: methodId and `sizeof()`) whose parameter struct holds an `NvP64`, directly or through a nested struct, union or typedef (the SDK headers under src/common, src/nvidia/inc and src/nvidia/interface), less the ones stock CPU-RM forwards to GSP-RM flat. Those are the exported controls whose every method entry carries `RMCTRL_FLAGS_ROUTE_TO_PHYSICAL` (its value read from src/nvidia/inc/kernel/rmapi/control.h) and that FINN does not serialize: `serverSerializeCtrlDown` (src/nvidia/src/kernel/rmapi/ rmapi_finn.c) returns with the block unchanged and `rmresControl_Prologue_IMPL` (src/nvidia/src/kernel/rmapi/resource.c) sends it to GSP-RM with `NV_RM_RPC_CONTROL`, so gsp_bringup's forwarder lets them through as well and they must be on no list. Every control the tree's FINN serializer handles (`finnUnserializedInterfaceSize_*`, src/nvidia/interface/rmapi/src/g_finn_rm_api.c) and every command of the deprecated converter table (`rmDeprecatedControlTable`, src/nvidia/interface/deprecated/rmapi_deprecated_control.c) must be on the release's list or on `POINTER_CONTROLS`. Stock CPU-RM never sends any of them to GSP-RM as a flat block, so gsp_bringup's forwarder must not either. A third, independent list cross-checks the result: every command `embeddedParamCopyIn` (src/nvidia/src/kernel/rmapi/embedded_param_copy.c) copies an embedded buffer in for must be on one of the two lists, unless stock forwards it flat (above), the tree's RM does not export it or its headers do not define it. Only `NvP64` members count as user pointers; plain `T *` members are not looked at. usage: check_pointer_controls.py [tree ...] Each tree is checked in turn; the exit status is 1 when any fails. Without an argument the 620 tree is `$NV_RS_OGKM_620`, then `$OPEN_GPU_ROOT`, then target/ref/ogkm in the repository (the last two are the defaults of tools/oracle_gsp_620.py). A 580 tree is checked only when given as an argument. """ import os import re import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] def default_tree(): for env in ("NV_RS_OGKM_620", "OPEN_GPU_ROOT"): if os.environ.get(env): return Path(os.environ[env]) return ROOT / "target/ref/ogkm" RUST = ROOT / "src/nvidia/src/gpu/gsp_pointer_controls.rs" HEADER_DIRS = ["src/common/sdk/nvidia/inc", "src/common/inc", "src/nvidia/inc", "src/nvidia/interface"] # NVIDIA_VERSION major -> the list of exported NvP64 controls for that release NVP64_LISTS = {"620": "NVP64_CONTROLS_620", "580": "NVP64_CONTROLS_580"} def release(tree): """The `NVIDIA_VERSION` of the tree's version.mk, e.g. 580.178.04; None without one.""" try: text = (tree / "version.mk").read_text(errors="replace") except OSError: return None m = re.search(r"^NVIDIA_VERSION\s*=\s*(\S+)", text, flags=re.M) return m.group(1) if m else None def strip_comments(text): text = re.sub(r"/\*.*?\*/", " ", text, flags=re.S) return re.sub(r"//[^\n]*", " ", text) def scan_headers(tree): """struct / union bodies by every name they go by, and plain typedef / #define aliases.""" bodies, aliases = {}, {} for base in HEADER_DIRS: for dirpath, _, files in os.walk(tree / base): for name in files: if not name.endswith(".h"): continue text = strip_comments(Path(dirpath, name).read_text(errors="replace")) for m in re.finditer(r"\b(typedef\s+)?(struct|union)\s+(\w+)?\s*\{", text): depth, i = 0, m.end() - 1 while i < len(text): depth += {"{": 1, "}": -1}.get(text[i], 0) if depth == 0: break i += 1 body = text[m.end():i] names = [m.group(3)] if m.group(3) else [] if m.group(1): tail = re.match(r"\s*([\w\s,*]+?)\s*;", text[i + 1:i + 200]) if tail: names += [n.strip().lstrip("*").strip() for n in tail.group(1).split(",")] for n in names: if re.fullmatch(r"\w+", n): bodies.setdefault(n, body) for m in re.finditer(r"^\s*#\s*define\s+(\w+)\s+(\w+)\s*$", text, flags=re.M): aliases.setdefault(m.group(1), m.group(2)) for m in re.finditer(r"\btypedef\s+(?:struct\s+|union\s+)?(\w+)\s+(\w+)\s*;", text): aliases.setdefault(m.group(2), m.group(1)) return bodies, aliases def route_to_physical_flag(tree): """`RMCTRL_FLAGS_ROUTE_TO_PHYSICAL` of the tree's control.h.""" text = (tree / "src/nvidia/inc/kernel/rmapi/control.h").read_text(errors="replace") m = re.search(r"^\s*#\s*define\s+RMCTRL_FLAGS_ROUTE_TO_PHYSICAL\s+\(?(0x[0-9a-fA-F]+)", text, flags=re.M) if not m: sys.exit("no RMCTRL_FLAGS_ROUTE_TO_PHYSICAL in src/nvidia/inc/kernel/rmapi/control.h") return int(m.group(1), 16) def forwarded_flat(exported, flags, finn_commands, route): """The exported NvP64 controls stock CPU-RM sends to GSP-RM as a flat block. Every method entry of the command carries `route` (RMCTRL_FLAGS_ROUTE_TO_PHYSICAL), so `rmresControlSerialization_Prologue_IMPL` calls `serverSerializeCtrlDown` and `rmresControl_Prologue_IMPL` sends `NV_RM_RPC_CONTROL`; FINN does not serialize it, so `serverSerializeCtrlDown` leaves the block as it is. A command with an entry CPU-RM handles itself (no ROUTE_TO_PHYSICAL) stays on the list.""" return {method for method in exported if method not in finn_commands and all(f & route for f in flags[method])} def nvp64_exports(tree): bodies, aliases = scan_headers(tree) memo = {} def resolve(name): for _ in range(10): if name in bodies or name not in aliases: break name = aliases[name] return name def holds_p64(name, stack=()): name = resolve(name) if name in memo: return memo[name] body = bodies.get(name) if body is None or name in stack: return False found = bool(re.search(r"\bNvP64\b", body)) or any( holds_p64(ident, stack + (name,)) for ident in set(re.findall(r"\b[A-Za-z_]\w*\b", body)) if ident != name and resolve(ident) in bodies) # a "no" found below a type still on the stack may only be the cycle cut short if found or not stack: memo[name] = found return found exported, every, flags, unresolved = {}, set(), {}, set() for path in sorted((tree / "src/nvidia/generated").glob("g_*_nvoc.c")): text = path.read_text(errors="replace") methods = re.findall(r"/\*methodId=\*/\s*(0x[0-9a-fA-F]+)u,", text) every.update(int(method, 16) for method in methods) # each method entry: /*flags=*/ 0x..u, /*accessRight=*/ 0x..u, /*methodId=*/ 0x..u, entries = re.findall(r"/\*flags=\*/\s*(0x[0-9a-fA-F]+)u," r"\s*/\*accessRight=\*/\s*0x[0-9a-fA-F]+u," r"\s*/\*methodId=\*/\s*(0x[0-9a-fA-F]+)u,", text) if len(entries) != len(methods): sys.exit(f"{path}: {len(methods)} methodIds, {len(entries)} of them with their flags") for flag, method in entries: flags.setdefault(int(method, 16), []).append(int(flag, 16)) for m in re.finditer(r"/\*methodId=\*/\s*(0x[0-9a-fA-F]+)u,\s*/\*paramSize=\*/\s*sizeof\((\w+)\)", text): method, params = int(m.group(1), 16), m.group(2) if resolve(params) not in bodies: unresolved.add(params) elif holds_p64(params): exported[method] = params return exported, every, flags, unresolved def finn_serialized(tree): text = (tree / "src/nvidia/interface/rmapi/src/g_finn_rm_api.c").read_text(errors="replace") messages = set() for m in re.finditer(r"static NvU64 finnUnserializedInterfaceSize_\w+\(NvU64 message\)\s*\{(.*?)\n\}", text, re.S): messages.update(re.findall(r"case FINN_MESSAGE_ID\((\w+)\)", m.group(1))) # _MESSAGE_ID (0xNNU) and the interface of the header's commands give the command id commands = {} for dirpath, _, files in os.walk(tree / "src/common/sdk/nvidia/inc/ctrl"): for name in files: if not name.endswith(".h"): continue text = Path(dirpath, name).read_text(errors="replace") iface = re.search(r"\(\s*(FINN_\w+_INTERFACE_ID)\s*<<\s*8\s*\)", text) ids = {m.group(1): int(m.group(2), 16) for m in re.finditer(r"#define\s+(\w+)_MESSAGE_ID\s+\((0x[0-9a-fA-F]+)U?\)", text)} cmds = {m.group(3): int(m.group(2), 16) for m in re.finditer(r"#define\s+(\w+)\s+\((0x[0-9a-fA-F]+)U?\)\s*/\*\s*finn: Evaluated from " r"\"\(\w+ << 8\) \| (\w+)_MESSAGE_ID\"", text)} for params, message in ids.items(): if params in cmds: commands[params] = cmds[params] elif iface: # a message whose command define is gone: interface id from a sibling command sibling = next(iter(cmds.values()), None) if sibling is not None: commands.setdefault(params, (sibling & ~0xff) | message) return {params: commands.get(params) for params in messages} def control_command_ids(tree): """Resolves a control command name (`NV0080_CTRL_CMD_..`, also `NV2080_CTRL_GPU_GET_..`) to its id through the SDK control headers, following plain aliases; None when no header defines it.""" values, aliases = {}, {} for dirpath, _, files in os.walk(tree / "src/common/sdk/nvidia/inc/ctrl"): for name in files: if name.endswith(".h"): header = Path(dirpath, name).read_text(errors="replace") for m in re.finditer(r"#define\s+(NV\w+_CTRL_\w+)\s+\((0x[0-9a-fA-F]+)U?\)", header): values.setdefault(m.group(1), int(m.group(2), 16)) # e.g. NV0080_CTRL_CMD_MSENC_GET_CAPS NV0080_CTRL_CMD_NVENC_GET_CAPS for m in re.finditer(r"^\s*#\s*define\s+(NV\w+_CTRL_CMD_\w+)\s+(NV\w+_CTRL_CMD_\w+)\s*$", header, flags=re.M): aliases.setdefault(m.group(1), m.group(2)) def resolve(name): for _ in range(10): if name in values or name not in aliases: break name = aliases[name] return values.get(name) return resolve def deprecated_commands(tree, resolve): """The commands of rmDeprecatedControlTable, resolved through the SDK control headers.""" text = strip_comments((tree / "src/nvidia/interface/deprecated/rmapi_deprecated_control.c") .read_text(errors="replace")) table = re.search(r"rmDeprecatedControlTable\[\]\s*=\s*\{(.*?)\};", text, re.S) if not table: sys.exit("no rmDeprecatedControlTable in rmapi_deprecated_control.c") names = re.findall(r"\{\s*(NV\w+_CTRL_CMD_\w+)\s*,", table.group(1)) return {name: resolve(name) for name in names} def embedded_copy_commands(tree, resolve): """The `case` labels of embeddedParamCopyIn: the controls stock copies an embedded buffer in for.""" text = strip_comments((tree / "src/nvidia/src/kernel/rmapi/embedded_param_copy.c") .read_text(errors="replace")) body = re.search(r"NV_STATUS\s+embeddedParamCopyIn\s*\((.*?)\nNV_STATUS\s+embeddedParamCopyOut", text, re.S) if not body: sys.exit("no embeddedParamCopyIn in embedded_param_copy.c") names = re.findall(r"\bcase\s+(NV\w+_CTRL_\w+)\s*:", body.group(1)) return {name: resolve(name) for name in names} def rust_list(name): text = RUST.read_text() m = re.search(rf"pub const {name}: \[u32; (\d+)\] = \[(.*?)\];", text, re.S) if not m: sys.exit(f"{RUST}: no {name}") values = [int(v.replace("_", ""), 16) for v in re.findall(r"^\s*(0x[0-9a-fA-F_]+),", m.group(2), re.M)] if len(values) != int(m.group(1)): sys.exit(f"{name}: {len(values)} entries parsed, the array holds {m.group(1)}") return values def check(tree): """Checks the lists against one tree; True when they match it.""" if not (tree / "src/nvidia/generated").is_dir(): print(f"no open-gpu-kernel-modules tree at {tree} (set NV_RS_OGKM_620 or pass the tree)") return False version = release(tree) list_name = NVP64_LISTS.get((version or "").split(".")[0]) if list_name is None: print(f"{tree}: NVIDIA_VERSION {version or 'not found'} in version.mk; " f"this check knows {', '.join(sorted(NVP64_LISTS))}") return False exported, every, flags, unresolved = nvp64_exports(tree) finn = finn_serialized(tree) flat = forwarded_flat(exported, flags, set(finn.values()), route_to_physical_flag(tree)) expected = {method: params for method, params in exported.items() if method not in flat} listed = rust_list(list_name) others = rust_list("POINTER_CONTROLS") failed = False if unresolved: failed = True print("parameter types the header scan cannot resolve:", ", ".join(sorted(unresolved))) if listed != sorted(set(listed)): failed = True print(f"{list_name} is not sorted and unique (holds_user_pointer binary-searches it)") for method in sorted(set(expected) - set(listed)): failed = True print(f"MISSING from {list_name}: {method:#010x} {expected[method]}") for method in sorted(set(listed) & flat): failed = True print(f"stock forwards {method:#010x} {exported[method]} flat (ROUTE_TO_PHYSICAL, not " f"FINN-serialized); it must not be on {list_name}") for method in sorted(set(listed) - set(exported)): failed = True print(f"NOT an exported NvP64 control: {method:#010x}") resolve = control_command_ids(tree) deprecated = deprecated_commands(tree, resolve) embedded = embedded_copy_commands(tree, resolve) for method in sorted(set(others) - set(finn.values()) - set(deprecated.values())): failed = True print(f"POINTER_CONTROLS {method:#010x} is neither FINN-serialized nor deprecated") for method in sorted(set(others) & set(listed)): failed = True print(f"{method:#010x} is on both lists") for method in sorted(set(others) & flat): failed = True print(f"stock forwards POINTER_CONTROLS {method:#010x} flat; it must not be on a list") for params, method in sorted(finn.items()): if method is None: failed = True print(f"FINN message without a command id: {params}") elif method not in expected and method not in others: failed = True print(f"FINN-serialized {method:#010x} {params} is on neither list") if not deprecated: failed = True print("rmDeprecatedControlTable: no commands parsed") for name, method in sorted(deprecated.items()): if method is None: failed = True print(f"deprecated {name}: no command id in the control headers") elif method not in expected and method not in others: failed = True print(f"deprecated {method:#010x} {name} is on neither list") # embeddedParamCopyIn: on a list, or a command stock forwards flat, or one the tree's RM does # not export or define flat_copied, not_exported, undefined = [], [], [] if not embedded: failed = True print("embeddedParamCopyIn: no case labels parsed") for name, method in sorted(embedded.items()): if method is None: undefined.append(name) elif method in listed or method in others: continue elif method in flat: flat_copied.append(f"{method:#010x}") elif method not in every: not_exported.append(f"{method:#010x}") else: failed = True print(f"embeddedParamCopyIn {method:#010x} {name} is exported and on neither list") print(f"{tree} ({version}): {len(exported)} exported NvP64 controls, " f"{len(flat)} of them forwarded flat by stock " f"({' '.join(f'{method:#010x}' for method in sorted(flat)) or '-'}), " f"{len(deprecated)} deprecated; embeddedParamCopyIn {len(embedded)} cases, " f"{len(flat_copied)} forwarded flat ({' '.join(flat_copied) or '-'}), " f"{len(not_exported)} not exported ({' '.join(not_exported) or '-'}), " f"{len(undefined)} not defined ({' '.join(undefined) or '-'}); " f"{list_name} {len(listed)}, POINTER_CONTROLS {len(others)}: " f"{'FAIL' if failed else 'ok'}") return not failed def main(): trees = [Path(arg) for arg in sys.argv[1:]] or [default_tree()] results = [check(tree) for tree in trees] return 0 if all(results) else 1 if __name__ == "__main__": sys.exit(main())