#!/usr/bin/env python3 """Coverage of the GV100 first-open stage callbacks by the Rust engine set, and a ranking of the missing bodies on the compute path. Inputs (all on disk; no emulation here): target/gpu-stage/original-engine-live.txt the callback walk of the original passes over the constructed GPU and the class slot tables (tools/check_gpu_engine_live_binary.py) src/nvidia/src/gpu/engine_bodies_more.rs `CONNECTED`: what the dispatcher answers reports/gv100-engine-callback-survey.json each callback run alone as original code reports/gv100-engine-call-trees.json static call trees (decompiler-derived) reports/original-trace-b3-segment-map.json transcript segments the original object's symbol table (nm) body sizes Statuses of a callback: connected a verified Rust body answers it behind `MoreEngines`, and the live oracle compares it inside the original passes verified-blocked a verified Rust body exists for the callback, but its inputs are state that callbacks or constructors without a body produce (`BLOCKED`) part a verified Rust function reproduces a named part of the body (`PART`) none nothing `BLOCKED`, `PART`, `COMPUTE_PATH` and `TRANSCRIPT` are statements of this file: the first two restate the module headers under src/nvidia/src and analysis/closed-driver-580/first-open-integration-plan.md section 2; the compute path is the plan's level table (section 3.1) plus the engines whose state those bodies take; the transcript lines are the segment map's attribution (its confidence is carried along). Ranking. A missing body m (a stage callback up to PostLoad, or a ConstructEngine without a verified Rust constructor) of a compute-path engine blocks a verified callback v when * v is of the same engine (an engine is constructed only when all its callbacks exist: plan section 3.1), or * m is among the producers of v's inputs (`BLOCKED`), directly or through another blocked verified callback. Bodies are ranked by the number of verified callbacks they block, then by dispatch position. `verified_after_in_walk` is the other reading of "blocks": a pass stops at the first callback without a body, so it counts the verified callback instances of compute-path engines that are dispatched after the body's first position. `first_missing_in_walk` lists the missing callbacks of compute-path engines in dispatch order. This is a planning aid derived from the tables in this file, not evidence about the driver. `--check` verifies that the checked-in reports/first-open-coverage.json is what the inputs give. `--markdown` prints the tables for the integration plan. """ import json import os import re import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] def find_original_rm_object(): candidates = [] if os.environ.get("NV_RS_RM_OBJECT"): candidates.append(Path(os.environ["NV_RS_RM_OBJECT"])) if os.environ.get("NV_RS_ANALYSIS_ROOT"): candidates.append( Path(os.environ["NV_RS_ANALYSIS_ROOT"]) / "extracted/kernel/nvidia/nv-kernel.o_binary" ) candidates.extend([ Path("/usr/src/nvidia-580.178.04/nvidia/nv-kernel.o_binary"), Path("/usr/src/nvidia-srv-580.178.04/nvidia/nv-kernel.o_binary"), Path("/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia/" "nv-kernel.o_binary"), ]) for candidate in candidates: if candidate.is_file(): return candidate raise SystemExit("nv-kernel.o_binary not found (set NV_RS_RM_OBJECT or NV_RS_ANALYSIS_ROOT)") LIVE = ROOT / "target/gpu-stage/original-engine-live.txt" REPORT = ROOT / "reports/first-open-coverage.json" SPINE_PATH = ROOT / "analysis/closed-driver-580/first-open-spine.json" PASS_OF = {"PreInitUnlocked": "PreInit", "PreInitLocked": "PreInit", "InitUnlocked": "Init", "InitLocked": "Init", "PreLoad": "PreLoad", "Load": "Load", "PostLoad": "PostLoad"} SLOT_ORDER = ("PreInitUnlocked", "PreInitLocked", "InitUnlocked", "InitLocked", "PreLoad", "Load", "PostLoad") # KernelNvlink has no object in the emulated attach but is present on a physical V100 # (plan section 1.4): its three callbacks, from the spine dossier. PHYSICAL_ONLY = (("KernelNvlink", "PreInitLocked", 42087), ("KernelNvlink", "Load", 42082), ("KernelNvlink", "PostLoad", 42085)) # Constructors with a verified Rust body (plan section 3.1, "Verified outside table 2"). VERIFIED_CONSTRUCTORS = {"OBJMC": "gpu/mc_init.rs::construct_engine", "Intr": "gpu/intr_init.rs::construct_engine", "OBJBUS": "gpu/bus_stage.rs::construct_engine"} # Verified bodies that cannot be connected yet: module, oracle report, and the producers of # their inputs that have no (complete) body. `survey` restates what the original callback # does when run alone on the constructed state (reports/gv100-engine-callback-survey.json). BLOCKED = { ("OBJFIFO", "Load"): { "rust": "fifo/load.rs", "oracle": "gpu-fifo-load-validation.json", "needs": [("OBJFIFO", "ConstructEngine"), ("OBJFIFO", "InitLocked"), ("KernelFifo", "ConstructEngine"), ("KernelFifo", "InitLocked")], "inputs": "the KernelFifo engine table and PBDMA count, the channel-id managers and " "runlist owner buffers of OBJFIFO InitLocked, the context-switch timeout of " "the constructor, the GPU override table GPU+6a38 (pre-stage)", }, ("Graphics", "Load"): { "rust": "gpu/gr_load_sequence.rs, gr_load.rs, gr_zbc.rs, memsys_zbc.rs", "oracle": "gpu-graphics-load-validation.json", "needs": [("Graphics", "ConstructEngine"), ("Graphics", "PreInitLocked"), ("Graphics", "InitLocked"), ("GraphicsManager", "InitLocked"), ("KernelGraphics", "InitLocked")], "inputs": "Graphics+15a2/+50/+188c and the GRinfo record (InitLocked and " "GraphicsManager), the netlist lists, GPU+911 (pre-stage step 5d); the " "survey run also stops in a MemorySystem callee (_nv045272rm), whose " "producer is not established", }, ("OBJACR", "InitLocked"): { "rust": "gpu/acr_load.rs", "oracle": "gpu-acr-load-validation.json", "needs": [("OBJACR", "ConstructEngine"), ("OBJACR", "PreInitLocked"), ("OBJLSFM", "ConstructEngine"), ("OBJLSFM", "PreInitLocked"), ("OBJLSFM", "InitLocked"), ("MemoryManager", "InitLocked")], "inputs": "the region requests OBJLSFM InitLocked registers, the constructor's " "properties (OBJACR+37f, +385, +388), the placement of the region " "descriptors in framebuffer memory", }, ("OBJACR", "Load"): { "rust": "gpu/acr_load.rs, acr_load_bar2.rs", "oracle": "gpu-acr-load-validation.json", "needs": [("OBJACR", "InitLocked"), ("OBJLSFM", "InitLocked"), ("KernelBus", "InitLocked"), ("OBJSEC2", "ConstructEngine"), ("OBJSEC2", "InitUnlocked"), ("Pmu", "ConstructEngine")], "inputs": "the region records of InitLocked, the composed region image, BAR2, the " "SEC2 Falcon object, the PMU function at +2f8", }, ("Pmu", "Load"): { "rust": "gpu/pmu_ls_start.rs, pmu_fbq.rs, pmu_irq_service.rs", "oracle": "gpu-pmu-ls-start-validation.json", "needs": [("Pmu", "ConstructEngine"), ("Pmu", "InitLocked"), ("OBJACR", "Load"), ("KernelBus", "InitLocked")], "inputs": "instance block and surface of Pmu InitLocked, the authenticated image " "descriptor (boot vector, OS word), BAR2, the Lpwr and GCX children", }, ("OBJSEC2", "Load"): { "rust": "gpu/falcon_ls_start.rs", "oracle": "gpu-falcon-ls-start-validation.json", "needs": [("OBJSEC2", "ConstructEngine"), ("OBJSEC2", "InitUnlocked"), ("OBJLSFM", "InitLocked"), ("OBJACR", "Load"), ("Pmu", "Load")], "inputs": "the light-secure registration, the image the HS ACR authenticated, the PMU " "command transport", }, } # Bodies of which a verified Rust function reproduces a named part. PART = { ("KernelBus", "InitLocked"): "mmu/bar2_setup.rs + mmu/placement.rs: the BAR2 part " "_nv039592rm", ("MemorySystem", "Load"): "gpu/nvdec_hs_run.rs + nvdec_hs_inputs.rs: the NVDEC HS step " "_nv045171rm", ("Graphics", "PreInitLocked"): "gpu/clock_gating.rs + clock_gating_providers.rs: the " "callee _nv033505rm", ("Graphics", "InitLocked"): "gpu/gr_init.rs: geometry, tile map, SM ids, 0x400100", ("OBJLSFM", "PreInitLocked"): "gpu/lsfm_mask.rs: the mask at OBJLSFM+198", ("OBJLSFM", "InitLocked"): "gpu/wpr_blob.rs, lsf_entry.rs: the region image", ("Pmu", "InitLocked"): "gpu/pmu_surface_size.rs, pmu_bar2.rs: surface and instance block", ("KernelGraphics", "PostLoad"): "gpu/gr_fecs_start.rs: _nv033633rm", } # The engines a compute first open needs, in the plan's level order, with the engines whose # state their bodies take. COMPUTE_PATH = ("OBJMC", "KernelMc", "Intr", "OBJTMR", "OBJBUS", "KernelBus", "OBJGMMU", "KernelGmmu", "MemorySystem", "KernelMemorySystem", "MemoryManager", "OBJLSFM", "OBJACR", "Pmu", "OBJSEC2", "KernelFifo", "OBJFIFO", "GraphicsManager", "Graphics", "KernelGraphics") # Transcript lines the segment map attributes to a callback: (first, last, segment ids). TRANSCRIPT = { ("MemorySystem", "PreInitUnlocked"): (37526, 37590, (11,)), ("MemorySystem", "PreInitLocked"): (37526, 37590, (11,)), ("KernelMemorySystem", "PreInitLocked"): (37526, 37590, (11,)), ("KernelBus", "PreInitLocked"): (37604, 37609, (13,)), ("Graphics", "PreInitLocked"): (37610, 37712, (14,)), ("OBJACR", "PreInitLocked"): (37713, 37722, (15,)), ("MemorySystem", "InitUnlocked"): (73826, 73937, (30,)), ("MemorySystem", "InitLocked"): (73826, 73937, (30,)), ("MemoryManager", "InitLocked"): (73938, 74913, (31,)), ("KernelGmmu", "InitLocked"): (107705, 107713, (34,)), ("KernelBus", "InitLocked"): (74914, 138650, tuple(range(32, 41))), ("KernelFifo", "InitLocked"): (138782, 138793, (43,)), ("OBJFIFO", "InitLocked"): (138782, 138793, (43,)), ("OBJSEC2", "InitUnlocked"): (138782, 138793, (43,)), ("KernelMemorySystem", "PreLoad"): (138803, 138824, (45,)), ("KernelBus", "PreLoad"): (138803, 138824, (45,)), ("MemorySystem", "Load"): (139260, 140404, (51, 52, 53)), ("KernelGmmu", "Load"): (140553, 140572, (55,)), ("KernelBus", "Load"): (140591, 140620, (57,)), ("OBJLSFM", "Load"): (140591, 140620, (57,)), ("OBJACR", "Load"): (140591, 147277, (57, 58, 59, 60, 61, 62)), ("Pmu", "Load"): (147278, 147456, (63,)), ("Graphics", "Load"): (156714, 158348, (66,)), ("KernelGraphics", "Load"): (156714, 158348, (66,)), ("OBJSEC2", "Load"): (164966, 165083, (71,)), ("OBJFIFO", "Load"): (165084, 165427, (72,)), ("KernelBus", "PostLoad"): (165442, 166379, (74,)), ("KernelGraphics", "PostLoad"): (166380, 167097, (75,)), ("OBJFIFO", "PostLoad"): (167098, 167361, (76,)), ("KernelFifo", "PostLoad"): (167098, 167361, (76,)), } def symbol(number): return f"_nv{number:06d}rm" def connected(): """`CONNECTED` of gpu/engine_bodies_more.rs as {(class id, slot): body}.""" text = (ROOT / "src/nvidia/src/gpu/engine_bodies_more.rs").read_text() constants = {} for path in ("engine_bodies.rs", "engine_bodies_more.rs"): source = (ROOT / "src/nvidia/src/gpu" / path).read_text() for name, value in re.findall(r"pub const (\w+): u32 = (0x[0-9a-f_]+);", source): constants[name] = int(value.replace("_", ""), 16) block = text[text.index("pub const CONNECTED"):] block = block[:block.index("];")] found = {} for name, slot, body in re.findall(r"\(\s*(?:super::engine_bodies::)?(\w+),\s*Slot::(\w+)," r"\s*(\d+),?\s*\)", block): found[(constants[name], slot)] = int(body) declared = int(re.search(r"CONNECTED: \[\(u32, Slot, u32\); (\d+)\]", text).group(1)) assert len(found) == declared, (len(found), declared) return found def walk(): """The first-open walk and the slot tables from the live oracle.""" callbacks, classes = [], {} for line in LIVE.read_text().splitlines(): fields = line.split(" ") if fields[0] == "class": slots = {} for item in fields[3:]: if item != "-": name, value = item.split("=") slots[name] = int(value.split(":")[1]) classes[int(fields[1], 16)] = slots elif fields[0] == "callback": callbacks.append((int(fields[1], 16), fields[2], int(fields[4]))) return callbacks, classes def sizes(): original = find_original_rm_object() listing = subprocess.run(["nm", "-S", "--defined-only", str(original)], capture_output=True, text=True, check=True).stdout return {fields[3]: int(fields[1], 16) for fields in map(str.split, listing.splitlines()) if len(fields) == 4} def build(): spine = json.loads(SPINE_PATH.read_text()) names = {child["class_id"]: child["name"] for child in spine["children"]} callbacks, classes = walk() answered = connected() size = sizes() survey = {(entry["class"], entry["slot"]): entry for entry in json.loads( (ROOT / "reports/gv100-engine-callback-survey.json").read_text())["callbacks"]} trees = json.loads((ROOT / "reports/gv100-engine-call-trees.json").read_text())["classes"] segments = {segment["id"]: segment for segment in json.loads( (ROOT / "reports/original-trace-b3-segment-map.json").read_text())["segments"]} by_name = {name: class_id for class_id, name in names.items()} def status_of(name, slot, class_id, body): if answered.get((class_id, slot)) == body: return "connected" if (name, slot) in BLOCKED: return "verified-blocked" if (name, slot) in PART: return "part" return "none" # One row per (class, slot), with its instances and first position. rows, order = {}, [] for position, (descriptor, slot, body) in enumerate(callbacks): class_id = descriptor >> 8 name = names[class_id] key = (name, slot) if key not in rows: rows[key] = {"class": name, "class_id": f"{class_id:x}", "slot": slot, "pass": PASS_OF[slot], "body": symbol(body), "instances": 0, "first_position": position, "status": status_of(name, slot, class_id, body)} order.append(key) rows[key]["instances"] += 1 for name, slot, body in PHYSICAL_ONLY: rows[(name, slot)] = {"class": name, "class_id": f"{by_name[name]:x}", "slot": slot, "pass": PASS_OF[slot], "body": symbol(body), "instances": 1, "first_position": None, "status": status_of(name, slot, by_name[name], body), "note": "no object in the emulated attach; present on a " "physical V100"} order.append((name, slot)) used = set(answered) for key in order: row = rows[key] if row["status"] == "connected": used.discard((int(row["class_id"], 16), row["slot"])) if key in BLOCKED: row["rust"] = BLOCKED[key]["rust"] row["oracle"] = BLOCKED[key]["oracle"] row["blocked_by"] = [f"{name} {slot}" for name, slot in BLOCKED[key]["needs"]] row["inputs"] = BLOCKED[key]["inputs"] if key in PART: row["part"] = PART[key] assert not used, f"CONNECTED names callbacks outside the walk: {used}" counts = {} for row in rows.values(): entry = counts.setdefault(row["pass"], {"rows": 0, "connected": 0, "verified-blocked": 0, "part": 0, "none": 0, "instances": 0}) entry["rows"] += 1 entry["instances"] += row["instances"] entry[row["status"]] += row["instances"] total = {key: sum(entry[key] for entry in counts.values()) for key in ("rows", "instances", "connected", "verified-blocked", "part", "none")} # Missing bodies of the compute path. verified = {key for key, row in rows.items() if row["status"] in ("connected", "verified-blocked")} def missing(name, slot): if slot == "ConstructEngine": return (name not in VERIFIED_CONSTRUCTORS and "ConstructEngine" in classes.get(by_name[name], {})) return (name, slot) in rows and rows[(name, slot)]["status"] in ("part", "none") def needs(key, seen=()): """Every producer a verified callback waits for, through other blocked ones.""" found = set() for producer in BLOCKED.get(key, {}).get("needs", ()): found.add(producer) if producer in BLOCKED and producer not in seen: found |= needs(producer, seen + (key,)) return found walk_verified = [position for position, (descriptor, slot, _body) in enumerate(callbacks) if (names[descriptor >> 8], slot) in verified and names[descriptor >> 8] in COMPUTE_PATH] candidates = [] for name in COMPUTE_PATH: slots = [slot for slot in ("ConstructEngine",) + SLOT_ORDER if missing(name, slot)] for slot in slots: candidates.append((name, slot)) ranking = [] for name, slot in candidates: key = (name, slot) blocked = sorted( f"{other[0]} {other[1]}" for other in verified if other != key and (other[0] == name or key in needs(other))) body = classes[by_name[name]][slot] tree = trees.get(name, {}).get("stages", {}).get(slot, {}) observed = survey.get(key, {}) window = TRANSCRIPT.get(key) entry = { "class": name, "slot": slot, "body": symbol(body), "body_bytes": size.get(symbol(body)), "status": "constructor without a Rust body" if slot == "ConstructEngine" else rows[key]["status"], "part": PART.get(key), "first_position": rows[key]["first_position"] if key in rows else None, "blocks": blocked, "blocks_count": len(blocked), "verified_after_in_walk": None if key not in rows else sum( position > rows[key]["first_position"] for position in walk_verified), "call_tree": {"functions": tree.get("functions"), "bytes": tree.get("bytes"), "registers_read": tree.get("registers_read"), "registers_written": tree.get("registers_written"), "unresolved_hal_slots": tree.get("unresolved_hal_slots")} if tree else None, "survey": {"completed": observed.get("completed"), "statuses": observed.get("statuses"), "stopped": observed.get("stopped"), "reads": observed.get("reads"), "writes": observed.get("writes"), "callee_calls": observed.get("callee_calls"), "body_state_changes": observed.get("body_state_changes"), "registers_read": observed.get("registers_read"), "registers_written": observed.get("registers_written")} if observed else None, "transcript": {"first_line": window[0], "last_line": window[1], "segments": list(window[2]), "confidence": sorted({segments[number]["confidence"] for number in window[2]})} if window else None, } ranking.append(entry) ranking.sort(key=lambda entry: (-entry["blocks_count"], entry["first_position"] if entry["first_position"] is not None else -1, entry["class"], entry["slot"])) for rank, entry in enumerate(ranking, 1): entry["rank"] = rank return { "evidence_category": "derived table: the callback walk is an instruction-emulation " "oracle; statuses and dependencies restate module headers and " "the integration plan; the ranking is a planning aid", "tool": "tools/first_open_coverage.py", "walk": "target/gpu-stage/original-engine-live.txt (189 callbacks on the emulated " "attach) plus KernelNvlink's three on a physical V100", "counts_by_pass": counts, "total": total, "connected": [f"{row['class']} {row['slot']} {row['body']}" for row in rows.values() if row["status"] == "connected"], "verified_blocked": [rows[key] for key in order if rows[key]["status"] == "verified-blocked"], "part": [rows[key] for key in order if rows[key]["status"] == "part"], "callbacks": [rows[key] for key in order], "compute_path": list(COMPUTE_PATH), "first_missing_in_walk": [ f"{entry['class']} {entry['slot']} {entry['body']} (position " f"{entry['first_position']})" for entry in sorted((entry for entry in ranking if entry["first_position"] is not None), key=lambda entry: entry["first_position"])], "ranking": ranking, } def markdown(report): lines = ["| Pass | rows | dispatched | connected | verified, blocked | part | no body |", "|---|---|---|---|---|---|---|"] for name in ("PreInit", "Init", "PreLoad", "Load", "PostLoad"): entry = report["counts_by_pass"][name] lines.append(f"| {name} | {entry['rows']} | {entry['instances']} | {entry['connected']} " f"| {entry['verified-blocked']} | {entry['part']} | {entry['none']} |") total = report["total"] lines.append(f"| **Total** | **{total['rows']}** | **{total['instances']}** | " f"**{total['connected']}** | **{total['verified-blocked']}** | " f"**{total['part']}** | **{total['none']}** |") lines += ["", "| callback | body | Rust | blocked by | inputs |", "|---|---|---|---|---|"] for row in report["verified_blocked"]: lines.append(f"| {row['class']} {row['slot']} | `{row['body']}` | {row['rust']} | " f"{'; '.join(row['blocked_by'])} | {row['inputs']} |") lines += ["", "| rank | missing body | symbol | bytes (body / tree) | blocks | later in " "walk | registers (static tree; survey run: reads / writes / callees) | " "transcript lines | survey [E] |", "|---|---|---|---|---|---|---|---|---|"] for entry in report["ranking"]: tree = entry["call_tree"] or {} observed = entry["survey"] or {} static = (f"r {len(tree.get('registers_read') or [])} / " f"w {len(tree.get('registers_written') or [])}" if tree else "-") ran = (f"r {observed.get('reads')} / w {observed.get('writes')} / " f"c {observed.get('callee_calls')}" if observed and observed.get("reads") is not None else "-") later = entry["verified_after_in_walk"] window = entry["transcript"] lines_text = (f"{window['first_line']}-{window['last_line']} " f"({', '.join(window['confidence'])})" if window else "-") if not observed: outcome = "not a stage callback" if entry["slot"] == "ConstructEngine" else "-" elif observed.get("completed"): outcome = "completes, status " + ",".join(observed.get("statuses") or []) else: outcome = "stops: " + (observed.get("stopped") or "")[:70] lines.append( f"| {entry['rank']} | {entry['class']} {entry['slot']}" + (" (part)" if entry["part"] else "") + f" | `{entry['body']}` | {entry['body_bytes']} / {tree.get('bytes', '-')} | " f"{entry['blocks_count']} | {'-' if later is None else later} | {static}; {ran} | " f"{lines_text} | {outcome} |") return "\n".join(lines) def main(): report = build() text = json.dumps(report, indent=1) + "\n" if "--check" in sys.argv: if not REPORT.is_file() or REPORT.read_text() != text: print("reports/first-open-coverage.json is stale", file=sys.stderr) return 1 print("reports/first-open-coverage.json is current") return 0 REPORT.write_text(text) if "--markdown" in sys.argv: print(markdown(report)) else: print(json.dumps({"report": "reports/first-open-coverage.json", "total": report["total"], "ranked_missing_bodies": len(report["ranking"])})) return 0 if __name__ == "__main__": sys.exit(main())