mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 14:38:47 +00:00
- Updated tools/post_reboot.sh to check kernel oops taint bit and stuck driver tasks instead of <86400s uptime - Level 7 hardware regression passed on 0000:b3:00.0 (module 37e6fa430835eee2b426019db3ad70eeb7a9e9070c09c84bd9b973cf56cbe529, 107 inventory words, 0 static mismatches, CUDA baseline verified before and after) - Updated .gitignore to exclude build archives (*.a, *.rlib), __pycache__, and raw trace dumps
1018 lines
53 KiB
Python
1018 lines
53 KiB
Python
#!/usr/bin/env python3
|
|
"""GV100 ACR bootstrap and LS Falcon boot analysis from the original driver's trace.
|
|
|
|
Derives reports/gv100-acr-bootstrap-analysis.json from
|
|
* target/trace/b3-bar0.txt BAR0 transcript of 0000:b3:00.0
|
|
* target/trace/b3-bar12-rle.txt run-length extract of the same GPU's
|
|
BAR1/BAR2 events (made by --extract-from)
|
|
* target/firmware/.../gv100.fw the firmware container
|
|
* the original kernel object packed descriptors, symbols, relocations
|
|
* the symbol map and the HAL bindings report
|
|
|
|
The BAR1/BAR2 extract is produced from the root-owned full mmiotrace with a
|
|
read-only pipe; nothing else needs privileges:
|
|
|
|
sudo -n cat reports/original-mmiotrace-b3-first/mmiotrace.txt | \
|
|
python3 tools/analyze_acr_bootstrap.py --extract-from -
|
|
|
|
Extract lines:
|
|
E <line> <R|W> <width> <bar> <offset> <value> <time>
|
|
Z <bar> <first offset> <count> <first line> <last line> <t0> <t1>
|
|
consecutive byte-wide writes of zero at ascending addresses
|
|
U <bar> <first offset> <count> <first line> <last line> <t0> <t1> <opcode>
|
|
consecutive events mmiotrace could not decode. f3,a4 is rep movsb:
|
|
the address and length are recorded, the data and the direction are not.
|
|
M <line> <text> lost-event markers (trace-wide, not per device)
|
|
|
|
Evidence categories are kept apart in the output: transcript_observation,
|
|
container_contents, original_code (verified_in_disassembly / pseudocode_reading),
|
|
existing_rust, external_knowledge and inference. Nothing here touches a GPU.
|
|
"""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import struct
|
|
import sys
|
|
import zlib
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
ORIGINAL = Path("/home/geodd/nvidia-driver/analysis-580.178.04")
|
|
RM_OBJECT = ORIGINAL / "extracted/kernel/nvidia/nv-kernel.o_binary"
|
|
SYMBOL_MAP = ORIGINAL / "decompiled/kernel-rm-all/original-symbol-export-map.jsonl"
|
|
OBJECT_SHA256 = "5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b"
|
|
BAR1, BAR1_SIZE = 0x39a000000000, 0x800000000
|
|
BAR2, BAR2_SIZE = 0x39a800000000, 0x2000000
|
|
# Address bases of the project's analysis database (as tools/extract_gv100_firmware.py).
|
|
RODATA_BASE, DATA_BASE, TEXT_BASE = 0x0111d660, 0x00f7e890, 0x0616f810
|
|
|
|
FALCONS = {"NVDEC": 0x84000, "SEC2": 0x87000, "PMU": 0x10a000, "FECS": 0x409000,
|
|
"GPCCS": 0x41a000, "FBFLCN": 0x9a4000}
|
|
FALCON_REGISTERS = {
|
|
0x000: "IRQSSET", 0x004: "IRQSCLR", 0x008: "IRQSTAT", 0x010: "IRQMSET", 0x014: "IRQMCLR",
|
|
0x018: "IRQMASK", 0x01c: "IRQDEST", 0x040: "MAILBOX0", 0x044: "MAILBOX1", 0x048: "ITFEN",
|
|
0x04c: "IDLESTATE", 0x050: "CURCTX", 0x054: "NXTCTX", 0x058: "CTXACK", 0x080: "OS",
|
|
0x084: "RM", 0x090: "DEBUG1", 0x0a4: "+0a4", 0x0dc: "+0dc", 0x100: "CPUCTL",
|
|
0x104: "BOOTVEC", 0x108: "HWCFG", 0x10c: "DMACTL", 0x110: "DMATRFBASE",
|
|
0x114: "DMATRFMOFFS", 0x118: "DMATRFCMD", 0x11c: "DMATRFFBOFFS", 0x12c: "HWCFG1",
|
|
0x130: "CPUCTL_ALIAS", 0x180: "IMEMC", 0x184: "IMEMD", 0x188: "IMEMT", 0x1c0: "DMEMC",
|
|
0x1c4: "DMEMD", 0x240: "SCTL", 0x3c0: "ENGINE_RESET"}
|
|
NAMED = {0x200: "PMC_ENABLE", 0x100cb8: "MMU_INVALIDATE_PDB", 0x100cbc: "MMU_INVALIDATE",
|
|
0x100cec: "MMU_INVALIDATE_PDB_HI", 0x100c80: "MMU_CTRL", 0x100cd0: "VPR_INFO",
|
|
0x100cd4: "WPR_INFO", 0x100cd8: "VPR_WPR_WRITE", 0x70000: "PFLUSH",
|
|
0x2270: "RUNLIST_BASE", 0x2274: "RUNLIST_SUBMIT", 0x810090: "USERMODE_DOORBELL",
|
|
0x2254: "PBDMA_TIMESLICE?", 0x88004: "PCI_COMMAND"}
|
|
|
|
|
|
def sha256(data):
|
|
return hashlib.sha256(data).hexdigest()
|
|
|
|
|
|
# ---------------------------------------------------------------- extraction
|
|
|
|
def extract(source, destination):
|
|
"""Run-length extract of one GPU's BAR1/BAR2 events from the full mmiotrace."""
|
|
run = None
|
|
count = {"E": 0, "Z": 0, "U": 0, "M": 0}
|
|
|
|
def flush(out):
|
|
nonlocal run
|
|
if run:
|
|
kind, bar, first, n, l0, l1, t0, t1, extra = run
|
|
out.write(f"{kind} {bar} {first:x} {n} {l0} {l1} {t0} {t1}{extra}\n")
|
|
count[kind] += 1
|
|
run = None
|
|
|
|
with open(destination, "w") as out:
|
|
out.write("# 0000:b3:00.0 BAR1/BAR2 run-length extract; see tools/analyze_acr_bootstrap.py\n")
|
|
for number, line in enumerate(source, 1):
|
|
if " 0x39a" not in line:
|
|
if line.startswith("MARK") or "LOST" in line:
|
|
flush(out)
|
|
out.write(f"M {number} {line.strip()}\n")
|
|
count["M"] += 1
|
|
continue
|
|
part = line.split()
|
|
if part[0] in ("R", "W"):
|
|
width, time, address, value = int(part[1]), part[2], int(part[4], 16), int(part[5], 16)
|
|
kind = "Z" if part[0] == "W" and width == 1 and value == 0 else "E"
|
|
opcode = ""
|
|
elif part[0] == "UNKNOWN":
|
|
time, address, kind, width, value = part[1], int(part[3], 16), "U", 1, 0
|
|
opcode = " " + part[4]
|
|
else:
|
|
continue
|
|
if BAR1 <= address < BAR1 + BAR1_SIZE:
|
|
bar, offset = 1, address - BAR1
|
|
elif BAR2 <= address < BAR2 + BAR2_SIZE:
|
|
bar, offset = 2, address - BAR2
|
|
else:
|
|
continue
|
|
if kind == "E":
|
|
flush(out)
|
|
out.write(f"E {number} {part[0]} {width} {bar} {offset:x} {value:x} {time}\n")
|
|
count["E"] += 1
|
|
continue
|
|
if (run and run[0] == kind and run[1] == bar and run[2] + run[3] == offset
|
|
and run[8] == opcode):
|
|
run[3] += 1
|
|
run[5] = number
|
|
run[7] = time
|
|
else:
|
|
flush(out)
|
|
run = [kind, bar, offset, 1, number, number, time, time, opcode]
|
|
flush(out)
|
|
return count
|
|
|
|
|
|
def load_extract(path):
|
|
events = []
|
|
for line in open(path):
|
|
part = line.split()
|
|
if part[0] == "E":
|
|
events.append({"kind": part[2], "line": int(part[1]), "last_line": int(part[1]),
|
|
"width": int(part[3]), "bar": int(part[4]), "offset": int(part[5], 16),
|
|
"value": int(part[6], 16), "count": 1, "t0": float(part[7]),
|
|
"t1": float(part[7])})
|
|
elif part[0] in ("Z", "U"):
|
|
events.append({"kind": part[0], "bar": int(part[1]), "offset": int(part[2], 16),
|
|
"count": int(part[3]), "line": int(part[4]), "last_line": int(part[5]),
|
|
"t0": float(part[6]), "t1": float(part[7]), "width": 1,
|
|
"opcode": part[8] if len(part) > 8 else ""})
|
|
elif part[0] == "M":
|
|
events.append({"kind": "M", "line": int(part[1]), "text": " ".join(part[2:])})
|
|
return events
|
|
|
|
|
|
def word_runs(events):
|
|
"""Join consecutive same-width E writes/reads at ascending addresses."""
|
|
runs = []
|
|
for event in events:
|
|
if event["kind"] in ("R", "W"):
|
|
last = runs[-1] if runs else None
|
|
if (last and last["kind"] == event["kind"] and last["width"] == event["width"]
|
|
and last["bar"] == event["bar"]
|
|
and last["offset"] + last["count"] * last["width"] == event["offset"]):
|
|
last["count"] += 1
|
|
last["last_line"] = event["line"]
|
|
last["t1"] = event["t1"]
|
|
last["values"].append(event["value"])
|
|
continue
|
|
runs.append(dict(event, values=[event["value"]]))
|
|
elif event["kind"] != "M":
|
|
runs.append(dict(event))
|
|
return runs
|
|
|
|
|
|
# ---------------------------------------------------------------- transcript
|
|
|
|
def load_transcript(path):
|
|
rows = []
|
|
for number, line in enumerate(open(path), 1):
|
|
part = line.split()
|
|
if part[0] in ("R", "W") and len(part) >= 4:
|
|
rows.append((number, part[0], int(part[1], 16), int(part[2], 16), float(part[3])))
|
|
return rows
|
|
|
|
|
|
def register_name(register):
|
|
for falcon, base in FALCONS.items():
|
|
if base <= register < base + 0x1000:
|
|
return f"{falcon}.{FALCON_REGISTERS.get(register - base, '+%03x' % (register - base))}"
|
|
return NAMED.get(register, "%06x" % register)
|
|
|
|
|
|
def sequence(rows, first, last, limit=400):
|
|
"""Collapsed register sequence for lines first..last (identical accesses and data
|
|
streams are run-length joined; BAR2 TLB invalidations become one token)."""
|
|
out = []
|
|
for number, op, register, value, _ in rows:
|
|
if number < first:
|
|
continue
|
|
if number > last:
|
|
break
|
|
name = register_name(register)
|
|
stream = name.endswith(("IMEMD", "DMEMD"))
|
|
item = out[-1] if out else None
|
|
if item and item["op"] == op and item["reg"] == name and (stream or item["value"] == value):
|
|
item["last"] = number
|
|
item["n"] += 1
|
|
else:
|
|
out.append({"first": number, "last": number, "op": op, "reg": name, "value": value, "n": 1})
|
|
text = []
|
|
index = 0
|
|
while index < len(out):
|
|
item = out[index]
|
|
# R MMU_CTRL, W PDB, W PDB_HI, W INVALIDATE, R MMU_CTRL...
|
|
if (item["reg"] == "MMU_INVALIDATE_PDB" and index + 2 < len(out)
|
|
and out[index + 2]["reg"] == "MMU_INVALIDATE"):
|
|
pdb = item["value"]
|
|
text.append(f"{item['first']}-{out[index + 2]['last']} TLB invalidate pdb={pdb:#x} "
|
|
f"cmd={out[index + 2]['value']:#x}")
|
|
index += 3
|
|
continue
|
|
if item["reg"] == "MMU_CTRL":
|
|
index += 1
|
|
continue
|
|
span = f"{item['first']}" if item["first"] == item["last"] else f"{item['first']}-{item['last']}"
|
|
if item["reg"].endswith(("IMEMD", "DMEMD")):
|
|
text.append(f"{span} {item['op']} {item['reg']} {item['n']} words ({item['n'] * 4} bytes)")
|
|
else:
|
|
text.append(f"{span} {item['op']} {item['reg']} {item['value']:#x}"
|
|
+ (f" x{item['n']}" if item["n"] > 1 else ""))
|
|
index += 1
|
|
if len(text) > limit:
|
|
text = text[:limit] + [f"... {len(text) - limit} more"]
|
|
return text
|
|
|
|
|
|
def falcon_streams(rows):
|
|
streams, current = [], {}
|
|
for number, op, register, value, time in rows:
|
|
for falcon, base in FALCONS.items():
|
|
if not base <= register < base + 0x1000:
|
|
continue
|
|
offset = register - base
|
|
if op == "W" and offset in (0x180, 0x1c0):
|
|
memory = "IMEM" if offset == 0x180 else "DMEM"
|
|
stream = {"falcon": falcon, "memory": memory, "control": value,
|
|
"offset": value & 0xfffffc, "secure": bool(value >> 28 & 1),
|
|
"auto_increment_write": bool(value >> 24 & 1), "control_line": number,
|
|
"first_line": None, "last_line": None, "tags": [], "words": []}
|
|
current[(falcon, memory)] = stream
|
|
streams.append(stream)
|
|
elif op == "W" and offset == 0x188 and (falcon, "IMEM") in current:
|
|
stream = current[(falcon, "IMEM")]
|
|
stream["tags"].append({"line": number, "tag": value, "at_word": len(stream["words"])})
|
|
elif op == "W" and offset in (0x184, 0x1c4):
|
|
stream = current.get((falcon, "IMEM" if offset == 0x184 else "DMEM"))
|
|
if stream is not None:
|
|
stream["words"].append(value)
|
|
stream["first_line"] = stream["first_line"] or number
|
|
stream["last_line"] = number
|
|
for stream in streams:
|
|
stream["data"] = b"".join(struct.pack("<I", word) for word in stream["words"])
|
|
return [stream for stream in streams if stream["words"]]
|
|
|
|
|
|
# ---------------------------------------------------------------- original object
|
|
|
|
class Elf:
|
|
"""Minimal ELF64 relocatable reader: sections, symbols, RELA entries."""
|
|
|
|
def __init__(self, path):
|
|
self.raw = raw = Path(path).read_bytes()
|
|
shoff, = struct.unpack_from("<Q", raw, 0x28)
|
|
shentsize, shnum, shstrndx = struct.unpack_from("<HHH", raw, 0x3a)
|
|
self.sections = []
|
|
for index in range(shnum):
|
|
name, kind, _, _, offset, size, link, info, _, entsize = struct.unpack_from(
|
|
"<IIQQQQIIQQ", raw, shoff + index * shentsize)
|
|
self.sections.append({"name_offset": name, "type": kind, "offset": offset,
|
|
"size": size, "link": link, "info": info})
|
|
strings = self.sections[shstrndx]
|
|
for section in self.sections:
|
|
start = strings["offset"] + section["name_offset"]
|
|
section["name"] = raw[start:raw.index(b"\0", start)].decode()
|
|
self.by_name = {section["name"]: index for index, section in enumerate(self.sections)}
|
|
symtab = self.sections[self.by_name[".symtab"]]
|
|
strtab = self.sections[symtab["link"]]
|
|
self.symbols = []
|
|
for index in range(symtab["size"] // 24):
|
|
name, info, _, shndx, value, size = struct.unpack_from(
|
|
"<IBBHQQ", raw, symtab["offset"] + index * 24)
|
|
start = strtab["offset"] + name
|
|
self.symbols.append((raw[start:raw.index(b"\0", start)].decode(), info & 15, shndx,
|
|
value, size))
|
|
text = self.by_name[".text"]
|
|
self.functions = {}
|
|
for name, kind, shndx, value, size in self.symbols:
|
|
if kind == 2 and shndx == text:
|
|
self.functions.setdefault(name, (value, size))
|
|
self.bases = {self.by_name[".rodata"]: RODATA_BASE, self.by_name[".data"]: DATA_BASE,
|
|
text: TEXT_BASE}
|
|
|
|
def data(self, name):
|
|
section = self.sections[self.by_name[name]]
|
|
return self.raw[section["offset"]:section["offset"] + section["size"]]
|
|
|
|
def relocations(self, name):
|
|
section = self.sections[self.by_name[name]]
|
|
for index in range(section["size"] // 24):
|
|
offset, info, addend = struct.unpack_from("<QQq", self.raw, section["offset"] + index * 24)
|
|
yield offset, info & 0xffffffff, self.symbols[info >> 32], addend
|
|
|
|
def function_view(self, name):
|
|
"""Bytes of a function, its ordered call/reference targets and string operands."""
|
|
if not hasattr(self, "_text_relocations"):
|
|
self._text_relocations = sorted(self.relocations(".rela.text"))
|
|
self._by_value = {}
|
|
text = self.by_name[".text"]
|
|
for symbol, kind, shndx, value, _ in self.symbols:
|
|
if kind == 2 and shndx == text:
|
|
self._by_value.setdefault(value, symbol)
|
|
start, size = self.functions[name]
|
|
body = self.data(".text")[start:start + size]
|
|
targets = []
|
|
import bisect
|
|
low = bisect.bisect_left(self._text_relocations, (start,))
|
|
for offset, kind, symbol, addend in self._text_relocations[low:]:
|
|
if offset >= start + size:
|
|
break
|
|
target_name, target_kind, shndx, value, _ = symbol
|
|
if target_kind == 3: # section symbol
|
|
section = self.sections[shndx]["name"] if shndx < len(self.sections) else "?"
|
|
where = value + addend + (4 if kind in (2, 4) else 0)
|
|
if section == ".text":
|
|
target_name = self._by_value.get(where, f".text+{where:#x}")
|
|
elif shndx in self.bases:
|
|
target_name = f"{self.bases[shndx] + where:#x}"
|
|
elif "str" in section or section.startswith(".rodata"):
|
|
data = self.data(section)
|
|
target_name = "str:" + data[where:data.index(b"\0", where)].decode("latin1")
|
|
else:
|
|
target_name = f"{section}+{where:#x}"
|
|
elif shndx in self.bases and target_kind != 2:
|
|
target_name = f"{self.bases[shndx] + value + addend + (4 if kind in (2, 4) else 0):#x}"
|
|
targets.append((offset - start, target_name))
|
|
return body, targets
|
|
|
|
|
|
def packed_descriptors(elf):
|
|
"""Every relocation-backed packed descriptor in .rodata that decodes."""
|
|
rodata = elf.data(".rodata")
|
|
index = elf.by_name[".rodata"]
|
|
pointers = {}
|
|
for offset, kind, symbol, addend in elf.relocations(".rela.rodata"):
|
|
if symbol[2] == index and kind == 1:
|
|
pointers[offset] = symbol[3] + addend
|
|
found = {}
|
|
for offset, storage in pointers.items():
|
|
if offset < 8 or offset + 16 > len(rodata):
|
|
continue
|
|
size, stored = struct.unpack_from("<II", rodata, offset - 8)
|
|
flags, = struct.unpack_from("<I", rodata, offset + 8)
|
|
if not (4 <= size <= 1 << 24 and 4 <= stored <= 1 << 24 and storage + stored <= len(rodata)
|
|
and flags < 256):
|
|
continue
|
|
packed = rodata[storage:storage + stored]
|
|
if flags & 1:
|
|
try:
|
|
data = zlib.decompressobj(-15).decompress(packed, size + 1)
|
|
except zlib.error:
|
|
continue
|
|
if len(data) > size:
|
|
continue
|
|
elif stored == size:
|
|
data = packed
|
|
else:
|
|
continue
|
|
found[RODATA_BASE + offset - 8] = {"size": size, "stored": stored, "flags": flags,
|
|
"data": data + bytes(size - len(data))}
|
|
return found, {RODATA_BASE + key: RODATA_BASE + value for key, value in pointers.items()}
|
|
|
|
|
|
def bundle(elf_rodata, pointers, address):
|
|
count, = struct.unpack_from("<I", elf_rodata, address - RODATA_BASE)
|
|
entries = []
|
|
for index in range(count):
|
|
entry = address + 8 + 16 * index
|
|
tag, = struct.unpack_from("<I", elf_rodata, entry - RODATA_BASE)
|
|
entries.append((tag, pointers.get(entry + 8)))
|
|
return entries
|
|
|
|
|
|
def load_container(path):
|
|
raw = Path(path).read_bytes()
|
|
assert raw[:8] == b"NVRSFW01"
|
|
_, count = struct.unpack_from("<II", raw, 8)
|
|
records = {}
|
|
for index in range(count):
|
|
descriptor, group, tag, size, stored, flags, offset, _ = struct.unpack_from(
|
|
"<8I", raw, 48 + 64 * index)
|
|
packed = raw[offset:offset + stored]
|
|
data = zlib.decompressobj(-15).decompress(packed) if flags & 1 else packed
|
|
records[descriptor] = {"bundle": group, "tag": tag, "size": size,
|
|
"data": data + bytes(size - len(data))}
|
|
return records, sha256(raw)
|
|
|
|
|
|
# ---------------------------------------------------------------- analysis parts
|
|
|
|
def words(data):
|
|
return list(struct.unpack("<%dI" % (len(data) // 4), data[:len(data) // 4 * 4]))
|
|
|
|
|
|
def decode_bl_dmem_desc(data):
|
|
"""RM_FLCN_BL_DMEM_DESC, public rmflcnbl.h (84 bytes)."""
|
|
value = words(data)
|
|
return {
|
|
"reserved": [f"{word:#x}" for word in value[0:4]],
|
|
"signature": [f"{word:#x}" for word in value[4:8]],
|
|
"ctxDma": value[8],
|
|
"codeDmaBase": f"{value[9] | value[10] << 32:#x}",
|
|
"nonSecureCodeOff": f"{value[11]:#x}", "nonSecureCodeSize": f"{value[12]:#x}",
|
|
"secureCodeOff": f"{value[13]:#x}", "secureCodeSize": f"{value[14]:#x}",
|
|
"codeEntryPoint": f"{value[15]:#x}",
|
|
"dataDmaBase": f"{value[16] | value[17] << 32:#x}",
|
|
"dataSize": f"{value[18]:#x}", "argc": value[19], "argv": f"{value[20]:#x}"}
|
|
|
|
|
|
def identify(data, container, descriptors):
|
|
"""Where a byte string occurs in the container records and the object's descriptors."""
|
|
hits = []
|
|
stripped = data.rstrip(b"\0")
|
|
if len(stripped) < 16:
|
|
return hits
|
|
for address, record in sorted(descriptors.items()):
|
|
if record["size"] < len(stripped):
|
|
continue
|
|
position = record["data"].find(stripped)
|
|
if position < 0:
|
|
continue
|
|
whole = record["data"][position:position + len(data)] == data
|
|
hits.append({"descriptor": f"{address:#x}", "descriptor_bytes": record["size"],
|
|
"at": f"{position:#x}", "match": "exact" if whole else "exact up to zero padding",
|
|
"covers_whole_descriptor": position == 0 and len(data) == record["size"],
|
|
"in_container": address in container,
|
|
"container_tag": (f"{container[address]['bundle']:#x}/{container[address]['tag']:#x}"
|
|
if address in container else None)})
|
|
return hits
|
|
|
|
|
|
def blob_layout(runs, load_first_time, limit_time):
|
|
"""WPR image written by _nv043215rm: headers by rep movsb, images by 32-bit stores."""
|
|
window = [run for run in runs if run["bar"] == 2 and load_first_time <= run["t0"] <= limit_time]
|
|
copies = [run for run in window if run["kind"] == "W" and run["width"] == 4 and run["count"] >= 1024]
|
|
if not copies:
|
|
return None
|
|
first, last = copies[0], copies[-1]
|
|
# The terminator is the first single 32-bit all-ones store after the last image.
|
|
terminator = next(run for run in window if run["t0"] > last["t1"] and run["kind"] == "W"
|
|
and run["count"] == 1 and run["values"] == [0xffffffff])
|
|
# 24-byte runs give the mapping base (first header at blob offset 0).
|
|
headers = [run for run in window if run["kind"] == "U" and run["count"] == 24
|
|
and run["t0"] < terminator["t0"] and run["offset"] < first["offset"]]
|
|
base = headers[0]["offset"]
|
|
page_table = [run for run in window if run["kind"] == "U" and run["offset"] >= 0xf00000
|
|
and run["t0"] < headers[0]["t0"]]
|
|
entries = []
|
|
for index, header in enumerate(headers):
|
|
limit = headers[index + 1]["t0"] if index + 1 < len(headers) else terminator["t0"]
|
|
mine = [run for run in window if header["t0"] <= run["t0"] < limit]
|
|
lsb = next(run for run in mine if run["kind"] == "U" and run["count"] == 240)
|
|
image = next(run for run in mine if run["kind"] == "W" and run["width"] == 4 and run["count"] >= 1024)
|
|
descriptor = next((run for run in mine if run["kind"] == "U" and run["count"] == 84), None)
|
|
data = b"".join(struct.pack("<I", value) for value in image["values"])
|
|
entries.append({
|
|
"index": index,
|
|
"wpr_header": {"blob_offset": header["offset"] - base, "bytes": 24,
|
|
"full_trace_lines": [header["line"], header["last_line"]],
|
|
"data": "not recorded (rep movsb)"},
|
|
"lsb_header": {"blob_offset": lsb["offset"] - base, "bytes": 240,
|
|
"full_trace_lines": [lsb["line"], lsb["last_line"]],
|
|
"data": "not recorded (rep movsb)"},
|
|
"bl_dmem_desc": None if descriptor is None else {
|
|
"blob_offset": descriptor["offset"] - base, "bytes": 84,
|
|
"full_trace_lines": [descriptor["line"], descriptor["last_line"]],
|
|
"data": "not recorded (rep movsb)"},
|
|
"image": {"blob_offset": image["offset"] - base, "bytes": len(data),
|
|
"full_trace_lines": [image["line"], image["last_line"]],
|
|
"seconds": round(image["t1"] - image["t0"], 6),
|
|
"sha256": sha256(data), "first_bytes": data[:8].hex()},
|
|
"_data": data})
|
|
return {"bar2_mapping_base": base, "entries": entries,
|
|
"terminator": {"blob_offset": terminator["offset"] - base, "value": "0xffffffff",
|
|
"full_trace_line": terminator["line"]},
|
|
"page_table_run_before_first_header": None if not page_table else {
|
|
"bar2_offset": f"{page_table[-1]['offset']:#x}", "bytes": page_table[-1]["count"],
|
|
"entries_of_8_bytes": page_table[-1]["count"] // 8,
|
|
"full_trace_lines": [page_table[-1]["line"], page_table[-1]["last_line"]]},
|
|
"first_time": headers[0]["t0"], "last_time": terminator["t0"]}
|
|
|
|
|
|
def placement_model(image_sizes, has_bl_data):
|
|
"""Arithmetic of src/nvidia/src/gpu/lsf_entry.rs (initial_cursor + Entry::place),
|
|
with the bootloader-data reservation made optional per entry."""
|
|
def align(value, to):
|
|
return (value + to - 1) & ~(to - 1)
|
|
cursor = align(align((len(image_sizes) + 1) * 24, 512), 256) + 12
|
|
out = []
|
|
for size, bl in zip(image_sizes, has_bl_data):
|
|
lsb = align(cursor, 256)
|
|
image = align(lsb + 240, 4096)
|
|
end = image + size
|
|
out.append({"lsb_header": lsb, "image": image, "bl_dmem_desc": align(end, 256) if bl else None})
|
|
cursor = align(end, 256) + 256 if bl else end
|
|
return out, align(cursor, 4096)
|
|
|
|
|
|
def disassembly_checks(elf):
|
|
"""Byte and relocation facts read from the original object, not from pseudocode."""
|
|
checks = []
|
|
|
|
def ordered(targets, names):
|
|
position = 0
|
|
sequence_ = [name for _, name in targets]
|
|
for name in names:
|
|
try:
|
|
position = sequence_.index(name, position) + 1
|
|
except ValueError:
|
|
return False
|
|
return True
|
|
|
|
def present(targets, names):
|
|
"""Every name is a call target; text order is not execution order."""
|
|
found = [name for _, name in targets]
|
|
return all(found.count(name) >= names.count(name) for name in names)
|
|
|
|
rodata = elf.data(".rodata")
|
|
|
|
def strings_of(targets):
|
|
out = []
|
|
for _, name in targets:
|
|
if name.startswith("0x"):
|
|
start = int(name, 16) - RODATA_BASE
|
|
if 0 <= start < len(rodata):
|
|
text = rodata[start:rodata.index(b"\0", start)]
|
|
if 4 <= len(text) < 64 and all(32 <= byte < 127 for byte in text):
|
|
out.append(text.decode())
|
|
return out
|
|
|
|
def add(identifier, function, claim, passed, detail):
|
|
checks.append({"id": identifier, "function": function, "claim": claim,
|
|
"passed": bool(passed), "detail": detail})
|
|
|
|
body, targets = elf.function_view("_nv016753rm")
|
|
compare = body.find(bytes.fromhex("6683bfe44d000000"))
|
|
after = body[compare:compare + 0x30]
|
|
calls = [name for _, name in targets if name.startswith("_nv")]
|
|
add("ce-branch", "_nv016753rm",
|
|
"The shadow copy takes the copy-engine path only when the 16-bit GPU field at +0x4de4 "
|
|
"is zero and the saved OBJACR+0x385 byte is non-zero; otherwise it allocates a CPU buffer "
|
|
"and copies through CPU mappings.",
|
|
compare > 0 and b"\x0f\x85" in after and bytes.fromhex("807d2700") in after
|
|
and bytes.fromhex("0fb68685030000") in body
|
|
and ordered(targets, ["_nv019039rm", "_nv019032rm", "_nv044027rm", "_nv019035rm", "_nv052687rm"])
|
|
and bytes.fromhex("41b840000000") in body,
|
|
{"cmpw_0x4de4_at": f"+{compare:#x}", "movzbl_0x385": True,
|
|
"calls_in_order": [name for name in calls if name in (
|
|
"_nv019039rm", "_nv019032rm", "_nv044027rm", "_nv019035rm", "_nv052687rm",
|
|
"_nv043739rm", "_nv052695rm", "_nv043773rm", "_nv016932rm")],
|
|
"r8d_flags_before_nv044027rm": "0x40 (TRANSFER_FLAGS_PREFER_CE in the public g_mem_mgr_nvoc.h)"})
|
|
|
|
body, targets = elf.function_view("_nv016731rm")
|
|
strings = strings_of(targets)
|
|
add("ce-registry", "_nv016731rm",
|
|
"The OBJACR constructor reads the registry value RMAcrUseCeForShadowCopy.",
|
|
"RMAcrUseCeForShadowCopy" in strings,
|
|
{"registry_strings": [text for text in strings if text.startswith(("RM", "Rm"))]})
|
|
|
|
body, targets = elf.function_view("_nv043215rm")
|
|
add("blob-writer", "_nv043215rm",
|
|
"The function calls the map and unmap pair, the copy routine four times, the boot "
|
|
"descriptor builder _nv043231rm, the sub-descriptor creator, _nv028614rm and _nv028571rm, "
|
|
"and holds the immediates 0x18, 0xf0 and 0xffffffff. The execution order (header, LSB "
|
|
"header, descriptor, image, terminator) is read from pseudocode and equals the trace.",
|
|
present(targets, ["_nv044028rm", "_nv052695rm", "_nv052695rm", "_nv043231rm", "_nv052695rm",
|
|
"_nv052695rm", "_nv043696rm", "_nv028614rm", "_nv028571rm", "_nv044029rm"])
|
|
and b"\x18\x00\x00\x00" in body and b"\xf0\x00\x00\x00" in body and b"\xff\xff\xff\xff" in body,
|
|
{"calls_in_text_order": [name for _, name in targets if name.startswith("_nv0")
|
|
and name not in ("_nv047869rm", "_nv046747rm")]})
|
|
|
|
body, targets = elf.function_view("_nv016931rm")
|
|
add("bootstrap-order", "_nv016931rm",
|
|
"OBJACR+0x128 calls the LSFM image writer _nv043215rm, _nv016747rm, the HS image launch "
|
|
"_nv016741rm (two call sites) and _nv016974rm. Their execution order is read from "
|
|
"pseudocode and equals the trace (image, shadow copy and HS launch, region check).",
|
|
present(targets, ["_nv043215rm", "_nv016747rm", "_nv016741rm", "_nv016741rm", "_nv016974rm"]),
|
|
{"calls_in_text_order": [name for _, name in targets if name.startswith("_nv0")
|
|
and name not in ("_nv047869rm", "_nv046747rm", "_nv046745rm")]})
|
|
|
|
body, targets = elf.function_view("_nv016956rm")
|
|
add("acr-load", "_nv016956rm",
|
|
"OBJACR Load calls _nv016973rm and the SEC2 function _nv055814rm directly; the bootstrap "
|
|
"itself is reached through the object's function table (indirect calls).",
|
|
ordered(targets, ["_nv016973rm", "_nv055814rm"]),
|
|
{"direct_calls": [name for _, name in targets if name.startswith("_nv0")
|
|
and name not in ("_nv047869rm",)]})
|
|
|
|
body, targets = elf.function_view("_nv045174rm")
|
|
add("nvdec-runner", "_nv045174rm",
|
|
"A memory-system function prepares the NVDEC image with _nv018167rm and patches its "
|
|
"signature with _nv016965rm before an indirect Falcon launch.",
|
|
ordered(targets, ["_nv018167rm", "_nv016965rm"]),
|
|
{"direct_calls": [name for _, name in targets if name.startswith("_nv0")]})
|
|
|
|
body, targets = elf.function_view("_nv028570rm")
|
|
add("direct-hs-load", "_nv028570rm",
|
|
"The Falcon function at +0x228 loads IMEM twice (_nv028523rm), DMEM once (_nv028452rm), "
|
|
"writes one register and optionally waits (_nv028782rm): the shape of the NVDEC run.",
|
|
ordered(targets, ["_nv028523rm", "_nv028523rm", "_nv028452rm", "_nv028674rm", "_nv028782rm"]),
|
|
{"direct_calls": [name for _, name in targets if name.startswith("_nv0")]})
|
|
|
|
for function, address, what in (
|
|
("_nv018329rm", 0x1147220, "OBJBSP+0x288: NVDEC LS image descriptor"),
|
|
("_nv018230rm", 0x1146eb0, "OBJBSP+0x260: NVDEC HS image bundle"),
|
|
("_nv052099rm", 0x1143718, "PMU class +0x318: PMU LS image bundle"),
|
|
("_nv055721rm", 0x1140490, "OBJSEC2+0x2d8: SEC2 LS image bundle"),
|
|
("_nv055663rm", 0x11401d8, "OBJSEC2+0x3a0: SEC2 HS boot loader bundle"),
|
|
("_nv016889rm", 0x11430c8, "OBJACR+0x1f0: HS ACR image bundle"),
|
|
("_nv016860rm", 0x1140830, "OBJACR+0x358: 3,584-byte HS image bundle"),
|
|
("_nv016882rm", 0x1141ea0, "OBJACR+0x2a0: 14,336-byte HS image bundle"),
|
|
("_nv016853rm", 0x1141350, "OBJACR+0x2d0: 6,144-byte HS image bundle")):
|
|
body, targets = elf.function_view(function)
|
|
add("getter-" + function, function, f"{what} is the object at {address:#x}.",
|
|
any(name == f"{address:#x}" for _, name in targets),
|
|
{"references": [name for _, name in targets]})
|
|
return checks
|
|
|
|
|
|
RUST_MODULES = [
|
|
# (step ids, module, original function(s), oracle report, what it covers)
|
|
("gpu/firmware_pack.rs", "container format", None, "parses gv100.fw records"),
|
|
("gpu/firmware_unpack.rs", "_nv017871rm/_nv017875rm", "reports/gpu-firmware-unpack-validation.json",
|
|
"raw DEFLATE unpack of a packed descriptor"),
|
|
("gpu/firmware_signature.rs", "_nv016965rm", "reports/gpu-acr-signature-oracle.json",
|
|
"signature word placement into an HS image"),
|
|
("gpu/falcon_imem.rs", "_nv028523rm/_nv028579rm", "reports/gpu-falcon-imem-oracle.json",
|
|
"IMEM block transfer with tags"),
|
|
("gpu/falcon_boot.rs", "_nv028470rm", "reports/gpu-falcon-boot-parent-oracle.json",
|
|
"HS virtual-DMA launch parent (reset, DMEM descriptor, boot loader, start, wait)"),
|
|
("gpu/acr_image.rs", "_nv016741rm/_nv016953rm", "reports/gpu-acr-parent-package-oracle.json",
|
|
"HS image framebuffer allocation and copy prefix; WPR region allocation"),
|
|
("gpu/acr_wpr_region.rs", "_nv016745rm", "reports/gpu-acr-wpr-region-validation.json",
|
|
"WPR region readback through 0x100cd4"),
|
|
("gpu/wpr_shadow.rs", "_nv016753rm (CPU branch)", "reports/gpu-wpr-cpu-shadow-oracle.json",
|
|
"primary to shadow copy through CPU mappings and the 0x78-byte ACR descriptor fields"),
|
|
("gpu/lsf_image.rs", "_nv027605rm/_nv029864rm", "reports/gpu-lsf-whole-image-oracle.json",
|
|
"FECS and GPCCS LS image assembly"),
|
|
("gpu/lsf_entry.rs", "_nv043182rm/_nv043236rm/_nv028607rm", "reports/gpu-lsf-entry-oracle.json",
|
|
"WPR and LSB headers, placement, boot descriptor of FECS/GPCCS"),
|
|
("gpu/gr_images.rs", "_nv033231rm", "reports/gr-images-firmware-validation.json",
|
|
"FECS/GPCCS code and data views of the netlist"),
|
|
("gpu/gr_netlist.rs", "netlist decode", "reports/gr-netlist-validation.json", "netlist regions"),
|
|
("gpu/fecs_mailbox.rs", "_nv033685rm/_nv031747rm/_nv055403rm", None, "FECS mailbox methods"),
|
|
("gpu/mc_reset.rs", "_nv043609rm", "reports/gpu-mc-reset-validation.json", "PMC engine reset"),
|
|
("gpu/pmu_reset.rs", "_nv052252rm", "reports/gpu-pmu-reset-binary.json", "PMU reset register"),
|
|
("gpu/pmu_dmem.rs", "PMU DMEM port", "reports/gv100-pmu-dmem-validation.json", "PMU DMEM access"),
|
|
("gpu/pmu_init.rs", "PMU INIT message", "reports/gv100-pmu-init-validation.json",
|
|
"INIT message on the DMEM queue route"),
|
|
("gpu/pmu_queue.rs", "PMU command queue", "reports/gv100-pmu-queue-publish-validation.json",
|
|
"direct-DMEM command queue publication"),
|
|
("gpu/pmu_sequence.rs", "PMU command transaction", "reports/gv100-pmu-sequence-validation.json",
|
|
"sequence table"),
|
|
("fifo/init.rs", "_nv028308rm leaves", None, "FIFO initialization leaves"),
|
|
("fifo/reset.rs", "_nv028309rm", None, "host reset through PMC bit 8"),
|
|
("fifo/context.rs", "_nv028190rm/_nv028203rm", None, "runlist submit command"),
|
|
("mmu/bar2.rs", "BAR2 formats", None, "BAR2 window plan"),
|
|
("mmu/vram.rs", "framebuffer ranges", None, "VRAM arena ownership"),
|
|
]
|
|
|
|
|
|
def rust_inventory():
|
|
out = []
|
|
source = ROOT / "src/nvidia/src"
|
|
for module, original, oracle, covers in RUST_MODULES:
|
|
path = source / module
|
|
out.append({"module": "src/nvidia/src/" + module, "exists": path.exists(),
|
|
"lines": len(path.read_text().splitlines()) if path.exists() else 0,
|
|
"original": original, "covers": covers,
|
|
"original_instruction_oracle": oracle,
|
|
"oracle_report_present": bool(oracle) and (ROOT / oracle).exists()})
|
|
return out
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__,
|
|
formatter_class=argparse.RawTextHelpFormatter)
|
|
parser.add_argument("--transcript", type=Path, default=ROOT / "target/trace/b3-bar0.txt")
|
|
parser.add_argument("--extract", type=Path, default=ROOT / "target/trace/b3-bar12-rle.txt")
|
|
parser.add_argument("--extract-from", help="full mmiotrace path or - for stdin; writes --extract")
|
|
parser.add_argument("--firmware", type=Path,
|
|
default=ROOT / "target/firmware/nvidia-rs/580.178.04/gv100.fw")
|
|
parser.add_argument("--rm-object", type=Path, default=RM_OBJECT)
|
|
parser.add_argument("--symbol-map", type=Path, default=SYMBOL_MAP)
|
|
parser.add_argument("--notes", type=Path, default=ROOT / "tools/acr_bootstrap_notes.json")
|
|
parser.add_argument("--out", type=Path, default=ROOT / "reports/gv100-acr-bootstrap-analysis.json")
|
|
parser.add_argument("--dump-dir", type=Path,
|
|
help="also write the reconstructed images and streams here")
|
|
parser.add_argument("--check", action="store_true", help="fail if the report would change")
|
|
arguments = parser.parse_args()
|
|
|
|
if arguments.extract_from:
|
|
source = sys.stdin if arguments.extract_from == "-" else open(arguments.extract_from)
|
|
arguments.extract.parent.mkdir(parents=True, exist_ok=True)
|
|
print("extract:", extract(source, arguments.extract))
|
|
return
|
|
|
|
problems = []
|
|
rows = load_transcript(arguments.transcript)
|
|
time_of = {number: time for number, _, _, _, time in rows}
|
|
events = load_extract(arguments.extract)
|
|
runs = word_runs(events)
|
|
container, container_sha = load_container(arguments.firmware)
|
|
object_bytes = arguments.rm_object.read_bytes()
|
|
if sha256(object_bytes) != OBJECT_SHA256:
|
|
raise SystemExit("unexpected kernel object")
|
|
elf = Elf(arguments.rm_object)
|
|
descriptors, pointers = packed_descriptors(elf)
|
|
rodata = elf.data(".rodata")
|
|
sizes = {}
|
|
for line in open(arguments.symbol_map):
|
|
row = json.loads(line)
|
|
sizes.setdefault(row["name"], row["ELF_size"])
|
|
notes = json.loads(arguments.notes.read_text())
|
|
|
|
def size_of(names):
|
|
return {name: sizes.get(name) for name in names}
|
|
|
|
# ---- Falcon streams
|
|
streams = [stream for stream in falcon_streams(rows) if stream["control_line"] > 138825]
|
|
stream_report = []
|
|
for stream in streams:
|
|
entry = {key: stream[key] for key in ("falcon", "memory", "control_line", "first_line",
|
|
"last_line", "secure")}
|
|
entry.update({"control": f"{stream['control']:#x}", "offset": f"{stream['offset']:#x}",
|
|
"bytes": len(stream["data"]), "sha256": sha256(stream["data"]),
|
|
"tags": [f"{tag['tag']:#x}@word{tag['at_word']}" for tag in stream["tags"]][:4]
|
|
+ (["..."] if len(stream["tags"]) > 4 else []),
|
|
"tag_count": len(stream["tags"]),
|
|
"identified": identify(stream["data"], container, descriptors)})
|
|
if len(stream["data"]) <= 84:
|
|
entry["words"] = [f"{word:#x}" for word in stream["words"]]
|
|
stream_report.append(entry)
|
|
if arguments.dump_dir:
|
|
arguments.dump_dir.mkdir(parents=True, exist_ok=True)
|
|
(arguments.dump_dir / f"{stream['falcon']}-{stream['memory']}-{stream['control_line']}.bin"
|
|
).write_bytes(stream["data"])
|
|
|
|
def stream_at(line):
|
|
return next(stream for stream in streams if stream["control_line"] == line)
|
|
|
|
# ---- WPR image
|
|
layout = blob_layout(runs, time_of[138825], time_of[140621])
|
|
names = notes["blob_entry_names"]
|
|
blob_entries = []
|
|
for entry in layout["entries"]:
|
|
data = entry.pop("_data")
|
|
hits = identify(data, container, descriptors)
|
|
entry["image"]["identified"] = hits
|
|
entry["falcon_by_inference"] = names[entry["index"]] if entry["index"] < len(names) else None
|
|
blob_entries.append(entry)
|
|
if arguments.dump_dir:
|
|
(arguments.dump_dir / f"wpr-image-{entry['index']}.bin").write_bytes(data)
|
|
model, total = placement_model([entry["image"]["bytes"] for entry in blob_entries],
|
|
[entry["bl_dmem_desc"] is not None for entry in blob_entries])
|
|
model_matches = all(
|
|
expected["lsb_header"] == entry["lsb_header"]["blob_offset"]
|
|
and expected["image"] == entry["image"]["blob_offset"]
|
|
and expected["bl_dmem_desc"] == (entry["bl_dmem_desc"] or {}).get("blob_offset")
|
|
for expected, entry in zip(model, blob_entries))
|
|
if not model_matches:
|
|
problems.append("placement model disagrees with the traced offsets")
|
|
existing_images = {}
|
|
for name in ("fecs", "gpccs"):
|
|
path = ROOT / f"analysis/lsf-580/{name}-original-image.bin"
|
|
if path.exists():
|
|
existing_images[name.upper()] = sha256(path.read_bytes())
|
|
for entry in blob_entries:
|
|
expected = existing_images.get(entry["falcon_by_inference"])
|
|
if expected:
|
|
entry["image"]["equals_existing_original_image_fixture"] = expected == entry["image"]["sha256"]
|
|
|
|
# ---- BAR2 activity between the blob and the SEC2 start
|
|
start_time = time_of[141316]
|
|
between = [run for run in runs if run["bar"] == 2 and layout["last_time"] < run["t0"] < start_time]
|
|
hs_upload = max((run for run in between if run["kind"] == "U" and run["offset"] < 0xf00000),
|
|
key=lambda run: run["count"])
|
|
channel_words = [run for run in between if run["kind"] == "W" and run["width"] in (4, 8)
|
|
and run["t0"] < hs_upload["t0"]]
|
|
ramfc = {f"{run['offset'] + 4 * index:#x}": f"{value:#x}" for run in channel_words
|
|
for index, value in enumerate(run["values"]) if run["width"] == 4 and value not in (1,)}
|
|
zero_fills = [{"bar2_offset": f"{run['offset']:#x}", "bytes": run["count"],
|
|
"full_trace_lines": [run["line"], run["last_line"]]}
|
|
for run in between if run["kind"] == "Z" and run["t0"] < hs_upload["t0"]]
|
|
|
|
# ---- PMU queue style
|
|
head_writes = [(number, value) for number, op, register, value, _ in rows
|
|
if op == "W" and register == 0x10a804 and number > 147456][:24]
|
|
element_runs = [run for run in runs if run["kind"] == "U" and run["bar"] == 2
|
|
and run["count"] == 2048 and run["t0"] > time_of[147456]]
|
|
|
|
# ---- bundles and descriptors used
|
|
def describe_bundle(address):
|
|
out = []
|
|
for tag, target in bundle(rodata, pointers, address):
|
|
record = descriptors.get(target)
|
|
item = {"tag": f"{tag:#x}", "descriptor": f"{target:#x}" if target else None,
|
|
"in_container": target in container}
|
|
if record:
|
|
item.update({"bytes": record["size"], "sha256": sha256(record["data"])})
|
|
if record["size"] in (4, 16):
|
|
item["value"] = record["data"].hex()
|
|
if record["size"] in (24, 36):
|
|
item["words"] = [f"{word:#x}" for word in words(record["data"])]
|
|
out.append(item)
|
|
return out
|
|
|
|
bundles = {name: {"address": f"{address:#x}", "getter": getter, "bound_at": slot,
|
|
"entries": describe_bundle(address)}
|
|
for name, address, getter, slot in (
|
|
("nvdec_hs", 0x1146eb0, "_nv018230rm", "OBJBSP+0x260"),
|
|
("acr_hs_load", 0x11430c8, "_nv016889rm", "OBJACR+0x1f0"),
|
|
("sec2_hs_boot_loader", 0x11401d8, "_nv055663rm", "OBJSEC2+0x3a0"),
|
|
("pmu_ls", 0x1143718, "_nv052099rm", "PMU class+0x318"),
|
|
("sec2_ls", 0x1140490, "_nv055721rm", "OBJSEC2+0x2d8"),
|
|
("acr_3584", 0x1140830, "_nv016860rm", "OBJACR+0x358"),
|
|
("acr_14336", 0x1141ea0, "_nv016882rm", "OBJACR+0x2a0"),
|
|
("acr_6144", 0x1141350, "_nv016853rm", "OBJACR+0x2d0"))}
|
|
nvdec_ls = descriptors[0x1147220]
|
|
missing = []
|
|
for label, address in (("NVDEC HS image (run in MemorySystem Load)", 0x114b3a8),
|
|
("NVDEC HS descriptor", 0x114b3c0), ("NVDEC HS patch location", 0x114b3d8),
|
|
("NVDEC HS patch signature index", 0x114b3f0),
|
|
("NVDEC HS debug signature", 0x114b408),
|
|
("NVDEC HS production signature", 0x114b420),
|
|
("NVDEC LS image", 0x1147220), ("PMU LS image", 0x114f6f8),
|
|
("PMU LS descriptor", 0x114f6e0), ("SEC2 LS image", 0x1153b38),
|
|
("SEC2 LS descriptor", 0x1153b50), ("SEC2 LS signature", 0x1153b68)):
|
|
record = descriptors[address]
|
|
missing.append({"what": label, "descriptor": f"{address:#x}", "bytes": record["size"],
|
|
"sha256": sha256(record["data"]), "in_container": address in container})
|
|
|
|
# ---- NVDEC signature patch check
|
|
nvdec_dmem = stream_at(140219)["data"]
|
|
nvdec_checks = {
|
|
"imem_equals_descriptor_0x114b3a8_first_0xe00_bytes":
|
|
stream_at(139307)["data"] + stream_at(139373)["data"] == descriptors[0x114b3a8]["data"][:0xe00],
|
|
"dmem_first_16_bytes_equal_tag_0xe_signature": nvdec_dmem[:16] == descriptors[0x114b420]["data"],
|
|
"dmem_rest_zero": not any(nvdec_dmem[16:]),
|
|
"descriptor_data_section_all_zero": not any(descriptors[0x114b3a8]["data"][0xe00:]),
|
|
"descriptor_tag_0x18_words": [f"{word:#x}" for word in words(descriptors[0x114b3c0]["data"])]}
|
|
if not all(value for value in list(nvdec_checks.values())[:4]):
|
|
problems.append("NVDEC stream does not reproduce from descriptor 0x114b3a8")
|
|
|
|
# ---- SEC2 boot loader and descriptors
|
|
sec2_hs_desc = decode_bl_dmem_desc(stream_at(141159)["data"])
|
|
sec2_ls_desc = decode_bl_dmem_desc(stream_at(165052)["data"])
|
|
acr_desc_words = words(descriptors[0x114fd70]["data"])
|
|
wpr_base = (0x7fde802 >> 4) << 12
|
|
wpr_reads = [(number, value) for number, op, register, value, _ in rows
|
|
if register == 0x100cd4 and 147253 <= number <= 147277]
|
|
sec2_image = next(entry for entry in blob_entries if entry["falcon_by_inference"] == "SEC2")
|
|
sec2_code = int(sec2_ls_desc["codeDmaBase"], 16)
|
|
|
|
checks = disassembly_checks(elf)
|
|
for check in checks:
|
|
if not check["passed"]:
|
|
problems.append("disassembly check failed: " + check["id"])
|
|
|
|
steps = []
|
|
for step in notes["steps"]:
|
|
item = dict(step)
|
|
first, last = step["transcript_lines"]
|
|
item["time"] = [time_of.get(first), time_of.get(last)]
|
|
item["register_sequence"] = sequence(rows, first, last, step.get("sequence_limit", 120))
|
|
steps.append(item)
|
|
|
|
gap_table = []
|
|
for row in notes["gap_table"]:
|
|
item = dict(row)
|
|
item["original_bytes"] = size_of(row["original_functions"])
|
|
item["original_bytes_total"] = sum(value or 0 for value in item["original_bytes"].values())
|
|
gap_table.append(item)
|
|
|
|
report = {
|
|
"scope": notes["scope"],
|
|
"inputs": {
|
|
"transcript": str(arguments.transcript.relative_to(ROOT)),
|
|
"transcript_sha256": sha256(arguments.transcript.read_bytes()),
|
|
"bar12_extract": str(arguments.extract.relative_to(ROOT)),
|
|
"bar12_extract_sha256": sha256(arguments.extract.read_bytes()),
|
|
"bar12_extract_source": "reports/original-mmiotrace-b3-first/mmiotrace.txt (root-owned)",
|
|
"firmware_container_sha256": container_sha,
|
|
"original_object_sha256": OBJECT_SHA256,
|
|
"lost_event_markers_in_full_trace": sum(event["kind"] == "M" and "MARK" in event["text"] and "Lost" in event["text"]
|
|
for event in events),
|
|
"last_lost_event_marker_full_trace_line": max(
|
|
(event["line"] for event in events if event["kind"] == "M" and "ost" in event["text"]),
|
|
default=None),
|
|
"first_load_event_full_trace_line": next(
|
|
run["line"] for run in runs if run["t0"] >= time_of[138825]),
|
|
},
|
|
"evidence_categories": notes["evidence_categories"],
|
|
"transcript_observation": {
|
|
"steps": steps,
|
|
"falcon_memory_loads": stream_report,
|
|
"wpr_image": {
|
|
"bar2_mapping_base": f"{layout['bar2_mapping_base']:#x}",
|
|
"page_table_run_before_first_header": layout["page_table_run_before_first_header"],
|
|
"entries": blob_entries,
|
|
"terminator": layout["terminator"],
|
|
"total_bytes_from_last_reservation": total,
|
|
"mapped_bytes_from_page_table_run": (
|
|
layout["page_table_run_before_first_header"]["entries_of_8_bytes"] * 4096
|
|
if layout["page_table_run_before_first_header"] else None),
|
|
"placement_model_of_lsf_entry_rs_matches": model_matches,
|
|
"placement_model": model,
|
|
"header_bytes_recorded": False,
|
|
"note": notes["wpr_image_note"],
|
|
},
|
|
"between_blob_and_sec2_start": {
|
|
"zero_filled_allocations": zero_fills,
|
|
"channel_and_runlist_words": ramfc,
|
|
"hs_image_upload": {"bar2_offset": f"{hs_upload['offset']:#x}", "bytes": hs_upload["count"],
|
|
"full_trace_lines": [hs_upload["line"], hs_upload["last_line"]],
|
|
"data": "not recorded (rep movsb)",
|
|
"equals_size_of": "bundle 0x11430c8 tags 0x24 and 0x26 (18,176 bytes)"},
|
|
},
|
|
"wpr_info_after_acr": [{"line": number, "value": f"{value:#x}"} for number, value in wpr_reads],
|
|
"wpr_region_from_readback": {"start": f"{wpr_base:#x}",
|
|
"end_block": f"{(0x7fdf403 >> 4) << 12:#x}",
|
|
"bytes_if_128k_inclusive": ((0x7fdf403 >> 4) << 12) + 0x20000 - wpr_base},
|
|
"pmu_command_queue": {
|
|
"head_register_0x10a804_writes_after_ls_start": head_writes,
|
|
"bar2_runs_of_2048_bytes_after_ls_start": len(element_runs),
|
|
"first_2048_byte_runs": [{"bar2_offset": f"{run['offset']:#x}",
|
|
"full_trace_lines": [run["line"], run["last_line"]]}
|
|
for run in element_runs[:6]],
|
|
},
|
|
},
|
|
"container_contents": {
|
|
"bundles": bundles,
|
|
"nvdec_ls_descriptor": {"descriptor": "0x1147220", "getter": "_nv018329rm (OBJBSP+0x288)",
|
|
"bytes": nvdec_ls["size"], "sha256": sha256(nvdec_ls["data"]),
|
|
"in_container": 0x1147220 in container},
|
|
"loaded_on_hardware_but_absent_from_container": [row for row in missing if not row["in_container"]],
|
|
"nvdec_hs_reproduction": nvdec_checks,
|
|
"sec2_boot_loader": {"imem_stream_equals_first_512_bytes_of": "0x1153d60 (bundle 0x11401d8 tag 0x23)",
|
|
"check": stream_at(141182)["data"] == container[0x1153d60]["data"][:512],
|
|
"metadata_tag_0x12_words": [f"{word:#x}" for word in
|
|
words(container[0x1153d78]["data"])]},
|
|
},
|
|
"decoded_structures": {
|
|
"sec2_hs_boot_descriptor": {
|
|
"source": "transcript lines 141159-141180, DMEM offset 0, 84 bytes",
|
|
"structure": "RM_FLCN_BL_DMEM_DESC (public src/nvidia/arch/nvalloc/common/inc/rmflcnbl.h)",
|
|
"fields": sec2_hs_desc,
|
|
"cross_checks": {
|
|
"nonSecureCodeSize_equals_descriptor_tag_0x19_word1": int(sec2_hs_desc["nonSecureCodeSize"], 16) == acr_desc_words[1],
|
|
"secureCodeOff_and_size_equal_tag_0x19_words_5_6": [int(sec2_hs_desc["secureCodeOff"], 16), int(sec2_hs_desc["secureCodeSize"], 16)] == acr_desc_words[5:7],
|
|
"dataDmaBase_minus_codeDmaBase_equals_tag_0x19_word2": int(sec2_hs_desc["dataDmaBase"], 16) - int(sec2_hs_desc["codeDmaBase"], 16) == acr_desc_words[2],
|
|
"dataSize_equals_tag_0x19_word3": int(sec2_hs_desc["dataSize"], 16) == acr_desc_words[3]},
|
|
"notes": notes["sec2_hs_descriptor_notes"]},
|
|
"acr_descriptor_inside_the_hs_image": notes["acr_descriptor"],
|
|
"sec2_ls_boot_descriptor": {
|
|
"source": "transcript lines 165052-165073, DMEM offset 0, 84 bytes",
|
|
"structure": "RM_FLCN_BL_DMEM_DESC",
|
|
"fields": sec2_ls_desc,
|
|
"cross_checks": {
|
|
"codeDmaBase_minus_wpr_start": f"{sec2_code - wpr_base:#x}",
|
|
"sec2_image_blob_offset": f"{sec2_image['image']['blob_offset']:#x}",
|
|
"code_base_is_image_plus": f"{sec2_code - wpr_base - sec2_image['image']['blob_offset']:#x}",
|
|
"inside_wpr": wpr_base <= sec2_code < wpr_base + 0xe0000},
|
|
"notes": notes["sec2_ls_descriptor_notes"]},
|
|
"pmu_ls_arguments": {
|
|
"source": "transcript lines 147434-147446, DMEM offset 0xffd0, 48 bytes",
|
|
"words": [f"{word:#x}" for word in stream_at(147434)["words"]],
|
|
"notes": notes["pmu_arguments_notes"]},
|
|
"fbflcn_arguments": {
|
|
"source": "transcript lines 147479-147493, DMEM offset 0, 56 bytes",
|
|
"words": [f"{word:#x}" for word in stream_at(147479)["words"]],
|
|
"notes": "Not part of the path to FECS/GPCCS; listed because it sits between the PMU start and the PMU INIT message."},
|
|
},
|
|
"original_code": {
|
|
"verified_in_disassembly": checks,
|
|
"pseudocode_reading": notes["pseudocode_reading"],
|
|
"hal_values_from_reports_gv100_engine_hal_bindings": notes["hal_values"],
|
|
},
|
|
"existing_rust": {"modules": rust_inventory(), "findings": notes["rust_findings"]},
|
|
"external_knowledge": notes["external_knowledge"],
|
|
"inference": notes["inference"],
|
|
"answers": notes["answers"],
|
|
"gap_table_note": "original_bytes are the sizes of the named functions only (symbol map), "
|
|
"not of their callees; they bound the top-level logic to translate, not the "
|
|
"whole call tree.",
|
|
"gap_table": gap_table,
|
|
"recommended_order": notes["recommended_order"],
|
|
"surprises": notes["surprises"],
|
|
"unknowns": notes["unknowns"],
|
|
"problems": problems,
|
|
}
|
|
text = json.dumps(report, indent=1) + "\n"
|
|
if arguments.check:
|
|
if not arguments.out.exists() or arguments.out.read_text() != text:
|
|
raise SystemExit("the report is stale")
|
|
else:
|
|
arguments.out.write_text(text)
|
|
print(f"{len(steps)} steps, {len(stream_report)} Falcon loads, {len(blob_entries)} WPR entries, "
|
|
f"{sum(check['passed'] for check in checks)}/{len(checks)} disassembly checks, "
|
|
f"{len(problems)} problems")
|
|
for problem in problems:
|
|
print("problem:", problem)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|