Files
nvdriver/tools/generate_rmapi_tables.py

116 lines
4.5 KiB
Python

#!/usr/bin/env python3
"""Generate src/nvidia/src/rmapi/control_table.rs from the RM API dossier.
The dossier's `methods` and `class_defs` arrays are decodes of the original's
NVOC_EXPORTED_METHOD_DEF arrays and class definitions (relocation records of
nv-kernel.o_binary 580.178.04; see analysis/closed-driver-580/rmapi-userspace.md 2.3).
"""
import argparse
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
DOSSIER = ROOT / "analysis/closed-driver-580/rmapi-userspace.json"
TARGET = ROOT / "src/nvidia/src/rmapi/control_table.rs"
# Existing Memory-class exports present in the checked-in control table but
# absent from the userspace dossier. Preserve the exact current descriptors
# (including flags) rather than treating this as new binary extraction.
# See rmapi/memory.rs CMD_MEM_SURFACE_INFO / CMD_MEM_PAGE_SIZE and
# analysis/closed-driver-580/rmapi-memory-constructor-spec.md section 7.
# Format: (class, command, flags, access right, parameter size, handler).
SUPPLEMENTAL_METHODS = (
(0x4789f2, 0x410110, 0x10208, 0, 16, 43653),
(0x4789f2, 0x410118, 0x8, 0, 8, 43651),
)
def render_table(data: dict, supplemental=()) -> tuple[str, int, int]:
class_ids = {entry["name"]: entry["classId"] for entry in data["class_defs"]}
def class_of(owner):
return class_ids[owner] if owner in class_ids else int(owner, 16)
methods = sorted(
(class_of(owner), method, flags, access, size, int(handler[3:-2]))
for method, handler, flags, access, size, owner, _name in data["methods"]
)
for method in supplemental:
matches = [row for row in methods if row[:2] == method[:2]]
if not matches:
methods.append(method)
elif any(row != method for row in matches):
raise ValueError(
f"conflicting supplemental control descriptor {method[0]:#x}/{method[1]:#x}"
)
methods.sort()
lines = [
"//! Exported control methods and NVOC class ancestry of the original (580.178.04).",
"//! Generated by tools/generate_rmapi_tables.py from the RM API dossier; do not edit.",
"",
"/// One `NVOC_EXPORTED_METHOD_DEF`: `class` is the NVOC class id whose table holds it,",
"/// `handler` the number in the original symbol `_nv<handler>rm`.",
"#[derive(Clone, Copy, Debug, PartialEq, Eq)]",
"pub struct ControlMethod {",
" pub class: u32,",
" pub id: u32,",
" pub flags: u32,",
" pub access_right: u32,",
" pub param_size: u32,",
" pub handler: u32,",
"}",
"const fn m(",
" class: u32,",
" id: u32,",
" flags: u32,",
" access_right: u32,",
" param_size: u32,",
" handler: u32,",
") -> ControlMethod {",
" ControlMethod {",
" class,",
" id,",
" flags,",
" access_right,",
" param_size,",
" handler,",
" }",
"}",
"/// Sorted by (class, id).",
"#[rustfmt::skip]",
f"pub static METHODS: [ControlMethod; {len(methods)}] = [",
]
lines += [f" m({c:#x}, {i:#x}, {f:#x}, {a}, {s}, {h})," for c, i, f, a, s, h in methods]
lines += [
"];",
"/// NVOC class id and its ancestors, nearest first (the cast table of the class).",
"#[rustfmt::skip]",
f"pub static ANCESTORS: [(u32, &[u32]); {len(data['class_defs'])}] = [",
]
for entry in sorted(data["class_defs"], key=lambda entry: entry["classId"]):
ancestors = ", ".join(f"{value:#x}" for value in entry["ancestors"])
lines.append(f" ({entry['classId']:#x}, &[{ancestors}]),")
lines += ["];", ""]
return "\n".join(lines), len(methods), len(data["class_defs"])
def main(argv=None) -> None:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--check", action="store_true", help="fail if control_table.rs is stale")
args = parser.parse_args(argv)
data = json.loads(DOSSIER.read_text(encoding="utf-8"))
text, method_count, class_count = render_table(data, SUPPLEMENTAL_METHODS)
if args.check:
if not TARGET.is_file() or TARGET.read_text(encoding="utf-8") != text:
raise SystemExit("control_table.rs is stale")
else:
TARGET.parent.mkdir(parents=True, exist_ok=True)
TARGET.write_text(text, encoding="utf-8")
print(method_count, "methods,", class_count, "classes")
if __name__ == "__main__":
main()