mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
175 lines
6.7 KiB
Python
175 lines
6.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Write src/nvidia/src/gpu/engine_set_tables.rs from the first-open spine dossier.
|
|
|
|
Input: analysis/closed-driver-580/first-open-spine.json (child table of the GPU object, the
|
|
engine order table and each class's stage slots, read from the original object; evidence in
|
|
the dossier). Six slot bodies of the JSON differ from what the constructed objects hold;
|
|
they are replaced by `CORRECTIONS`, whose values are the `class` lines of the instruction
|
|
oracle target/gpu-stage/original-engine-dispatch.txt (tools/
|
|
check_gpu_engine_dispatch_binary.py). The Rust test
|
|
`gpu::engine_set::tests::tables_equal_the_constructed_objects` compares every stage slot of
|
|
every constructed class with that oracle, so a stale table fails there.
|
|
|
|
The output is passed through rustfmt. `--check` exits non-zero when the checked-in file
|
|
differs from what would be written.
|
|
"""
|
|
import argparse
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
SOURCE = ROOT / "analysis/closed-driver-580/first-open-spine.json"
|
|
TARGET = ROOT / "src/nvidia/src/gpu/engine_set_tables.rs"
|
|
SLOTS = ("ConstructEngine", "InitMissing", "PreInitLocked", "PreInitUnlocked", "InitLocked",
|
|
"InitUnlocked", "PreLoad", "Load", "PostLoad", "PreUnload", "Unload", "PostUnload",
|
|
"StateDestroy", "IsPresent")
|
|
# (class name, slot) -> body symbol number, as the constructed object dispatches.
|
|
# Pmu: the engine object is a derived allocation whose class block holds other bodies than
|
|
# the base block the dossier read. OBJDPAUX: the dossier's own correction of 2026-11-19
|
|
# (argument order of the HAL binder), not carried into its JSON.
|
|
CORRECTIONS = {
|
|
("Pmu", "ConstructEngine"): 51982, ("Pmu", "PreInitLocked"): 52516,
|
|
("Pmu", "StateDestroy"): 4598, ("Pmu", "Unload"): 52517,
|
|
("OBJDPAUX", "InitLocked"): 26428, ("OBJDPAUX", "StateDestroy"): 26423,
|
|
}
|
|
|
|
|
|
def number(name):
|
|
if not (name.startswith("_nv") and name.endswith("rm")):
|
|
raise SystemExit(f"unexpected symbol name: {name!r}")
|
|
return int(name[3:-2])
|
|
|
|
|
|
def find_rustfmt() -> str:
|
|
env_rustfmt = os.environ.get("RUSTFMT")
|
|
if env_rustfmt:
|
|
return env_rustfmt
|
|
which = shutil.which("rustfmt")
|
|
if which:
|
|
return which
|
|
candidates = []
|
|
cargo_home = os.environ.get("CARGO_HOME")
|
|
if cargo_home:
|
|
candidates.append(Path(cargo_home) / "bin/rustfmt")
|
|
candidates.append(Path.home() / ".cargo/bin/rustfmt")
|
|
for candidate in candidates:
|
|
if candidate.is_file():
|
|
return str(candidate)
|
|
raise SystemExit("rustfmt not found; set RUSTFMT or add rustfmt to PATH")
|
|
|
|
|
|
def render():
|
|
data = json.loads(SOURCE.read_text(encoding="utf-8"))
|
|
lines = [
|
|
"//! Generated by tools/gen_engine_set_tables.py from",
|
|
"//! analysis/closed-driver-580/first-open-spine.json. Do not edit by hand.",
|
|
"//! Symbol numbers are the digits of the original names (`_nv043631rm` is 43631).",
|
|
"use super::engine_set::{Binding, Class, Order};",
|
|
"",
|
|
"const fn class(wrapper: u32, body: u32) -> Option<Binding> {",
|
|
" Some(Binding {",
|
|
" wrapper,",
|
|
" body,",
|
|
" hal_slot: 0,",
|
|
" })",
|
|
"}",
|
|
"const fn hal(wrapper: u32, body: u32, hal_slot: u16) -> Option<Binding> {",
|
|
" Some(Binding {",
|
|
" wrapper,",
|
|
" body,",
|
|
" hal_slot,",
|
|
" })",
|
|
"}",
|
|
"",
|
|
"/// The child fields of the GPU object in creation order (`_nv030241rm`).",
|
|
f"pub static CLASSES: [Class; {len(data['children'])}] = [",
|
|
]
|
|
used = set()
|
|
for child in data["children"]:
|
|
name = child["name"] or f"class_{child['class_id']:06x}"
|
|
slots = []
|
|
for slot in SLOTS:
|
|
entry = child.get("stage_slots", {}).get(slot)
|
|
if entry is None:
|
|
slots.append("None")
|
|
continue
|
|
wrapper = number(entry["wrapper"])
|
|
through = child.get("stage_bodies_via_hal", {}).get(slot)
|
|
body = number(through["function"]) if through else number(entry["body"])
|
|
if (name, slot) in CORRECTIONS:
|
|
body = CORRECTIONS[name, slot]
|
|
used.add((name, slot))
|
|
if through:
|
|
slots.append(f"hal({wrapper}, {body}, {int(through['object_slot'], 16):#x})")
|
|
else:
|
|
slots.append(f"class({wrapper}, {body})")
|
|
lines += [
|
|
" Class {",
|
|
f" gpu_offset: {child['gpu_offset']:#x},",
|
|
f" fields: {child['slots']},",
|
|
f" class_id: {child['class_id']:#08x},",
|
|
f" name: \"{name}\",",
|
|
f" early: {'true' if child['early'] else 'false'},",
|
|
f" gv100_instances: {child['gv100_instances'] or 0},",
|
|
" stage: [",
|
|
]
|
|
lines += [f" {slot}," for slot in slots]
|
|
lines += [" ],", " },"]
|
|
if used != set(CORRECTIONS):
|
|
raise SystemExit(f"unused CORRECTIONS entries: {sorted(set(CORRECTIONS) - used)}")
|
|
lines += [
|
|
"];",
|
|
"",
|
|
"/// The engine order table `.rodata+0x4c60ee0` (`_nv030434rm`): class and list flags",
|
|
"/// (1 init, 2 load, 4 unload, 8 destroy).",
|
|
f"pub static ORDER: [Order; {len(data['order_list'])}] = [",
|
|
]
|
|
for entry in data["order_list"]:
|
|
lines += [
|
|
" Order {",
|
|
f" class_id: {int(entry['class_id'], 16):#08x},",
|
|
f" flags: {entry['flags']},",
|
|
" },",
|
|
]
|
|
lines += ["];", ""]
|
|
return formatted("\n".join(lines))
|
|
|
|
|
|
def formatted(text):
|
|
"""The text as rustfmt leaves it (the workspace check formats every file)."""
|
|
rustfmt = find_rustfmt()
|
|
return subprocess.run(
|
|
[rustfmt, "--edition", "2024"],
|
|
input=text,
|
|
text=True,
|
|
check=True,
|
|
capture_output=True,
|
|
cwd=ROOT,
|
|
).stdout
|
|
|
|
|
|
def main(argv=None):
|
|
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
|
parser.add_argument("--check", action="store_true", help="exit non-zero if checked-in file differs")
|
|
args = parser.parse_args(argv)
|
|
|
|
text = render()
|
|
if args.check:
|
|
if not TARGET.exists() or TARGET.read_text(encoding="utf-8") != text:
|
|
print(f"{TARGET.relative_to(ROOT)} is not what the dossier gives; run this tool")
|
|
return 1
|
|
print(json.dumps({"checked": str(TARGET.relative_to(ROOT))}))
|
|
return 0
|
|
TARGET.parent.mkdir(parents=True, exist_ok=True)
|
|
TARGET.write_text(text, encoding="utf-8")
|
|
print(json.dumps({"written": str(TARGET.relative_to(ROOT))}))
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|