Files
nvdriver/tools/check_gv100_stall_routes_binary.py

225 lines
10 KiB
Python

#!/usr/bin/env python3
"""Run closed 580's GV100 PMC-route conversions on explicit route tables."""
import hashlib
from _binary_path import resolve_580_binary
import itertools
import json
from pathlib import Path
import struct
from elftools.elf.elffile import ELFFile
from unicorn import UC_ARCH_X86, UC_HOOK_CODE, UC_MODE_64, Uc
from unicorn.x86_const import (
UC_X86_REG_RAX, UC_X86_REG_RBP, UC_X86_REG_RCX, UC_X86_REG_RDI, UC_X86_REG_RDX,
UC_X86_REG_RIP, UC_X86_REG_RSI, UC_X86_REG_RSP,
)
ROOT = Path(__file__).resolve().parents[1]
ORIGINAL = resolve_580_binary()
DIGEST = "5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b"
TEXT, DATA, STACK, STOP = 0x10000000, 0x30000000, 0x40000000, 0x50000000
BSS, INDIRECT = 0x52000000, STOP + 0x100
GPU, THERMAL = DATA + 0x10000, DATA + 0x19000
INTR, TABLE, ENGINES, CHIP, RM = DATA, DATA + 0x2000, DATA + 0x3000, DATA + 0x4000, DATA + 0x5000
BINDINGS = {0x308: "_nv037659rm", 0x310: "_nv037657rm", 0x320: "_nv037667rm",
0x330: "_nv037647rm", 0x3b0: "_nv037628rm",
0x3a8: "_nv037553rm", 0x388: "_nv037700rm"}
EXECUTED = ("_nv005896rm", "_nv037523rm", "_nv037524rm", "_nv017883rm", "_nv017897rm",
"_nv017901rm", "_nv060218rm", "_nv060220rm", "_nv060224rm", "_nv060225rm",
"_nv060226rm", "_nv052478rm", "_nv037739rm", "_nv013843rm",
"_nv037630rm", "_nv037628rm", "_nv017882rm", "_nv017898rm", "_nv013844rm",
"_nv037700rm")
assert hashlib.sha256(ORIGINAL.read_bytes()).hexdigest() == DIGEST
with ORIGINAL.open("rb") as stream:
elf = ELFFile(stream)
symbols = list(elf.get_section_by_name(".symtab").iter_symbols())
by_name = {symbol.name: symbol for symbol in symbols}
text = bytearray(elf.get_section_by_name(".text").data())
text_section = elf.get_section_index(".text")
rodata_section = elf.get_section_index(".rodata")
bss_section = elf.get_section_index(".bss")
ranges = [(by_name[name]["st_value"], by_name[name]["st_size"]) for name in EXECUTED]
fixed_loader = by_name["_nv037647rm"]["st_value"]
boundaries = []
for relocation in elf.get_section_by_name(".rela.text").iter_relocations():
offset = relocation["r_offset"]
kind = relocation["r_info_type"]
target = symbols[relocation["r_info_sym"]]
if fixed_loader <= offset < fixed_loader + by_name["_nv037647rm"]["st_size"]:
if target["st_shndx"] == rodata_section and kind == 11:
boundaries.append(target["st_value"] + relocation["r_addend"])
if not any(start <= offset < start + size for start, size in ranges):
continue
if target.name == "__x86_indirect_thunk_rax":
address = INDIRECT
else:
bases = {text_section: TEXT, bss_section: BSS, rodata_section: 0x56000000}
assert target["st_shndx"] in bases, target.name
address = bases[target["st_shndx"]] + target["st_value"]
value = address + relocation["r_addend"]
if kind in (2, 4):
value -= TEXT + offset
else:
assert kind == 11, kind
struct.pack_into("<i", text, offset, value)
assert boundaries == [0x4d3bf60, 0x4d3c050], boundaries
fixed = elf.get_section_by_name(".rodata").data()[slice(*boundaries)]
cpu = Uc(UC_ARCH_X86, UC_MODE_64)
for address, size in ((TEXT, (len(text) + 4095) & ~4095), (DATA, 0x20000), (BSS, 0x200000),
(STACK, 0x10000), (STOP, 0x1000)):
cpu.mem_map(address, size)
cpu.mem_write(TEXT, bytes(text))
cpu.mem_write(CHIP + 0x10, struct.pack("<H", 0x23))
cpu.mem_write(RM + 0x10, struct.pack("<H", 2))
def call(name, a, b, c):
for register, argument in ((UC_X86_REG_RDI, a), (UC_X86_REG_RSI, b),
(UC_X86_REG_RDX, c), (UC_X86_REG_RSP, STACK + 0xfff8),
(UC_X86_REG_RBP, STACK + 0x8000)):
cpu.reg_write(register, argument)
cpu.mem_write(STACK + 0xfff8, struct.pack("<Q", STOP))
cpu.emu_start(TEXT + by_name[name]["st_value"], STOP, count=20000)
assert cpu.reg_read(UC_X86_REG_RIP) == STOP, name
return cpu.reg_read(UC_X86_REG_RAX)
call("_nv005896rm", INTR, CHIP, RM)
for slot, name in BINDINGS.items():
assert struct.unpack("<Q", cpu.mem_read(INTR + slot, 8))[0] == TEXT + by_name[name]["st_value"]
zero_memory = TEXT + by_name["_nv052705rm"]["st_value"]
diagnostics = {TEXT + by_name[name]["st_value"] for name in ("_nv046745rm", "_nv047869rm")}
scope_mode = False
def intercept(emu, pc, _size, _user):
if scope_mode:
return
assert pc not in diagnostics, hex(pc)
if pc != zero_memory:
return
assert emu.reg_read(UC_X86_REG_RDI) == ENGINES
assert emu.reg_read(UC_X86_REG_RSI) == 0 and emu.reg_read(UC_X86_REG_RDX) == 24
emu.mem_write(ENGINES, bytes(24))
stack = emu.reg_read(UC_X86_REG_RSP)
emu.reg_write(UC_X86_REG_RSP, stack + 8)
emu.reg_write(UC_X86_REG_RIP, struct.unpack("<Q", emu.mem_read(stack, 8))[0])
cpu.hook_add(UC_HOOK_CODE, intercept)
device = [(4, 8), (178, 0x100), (10, 0), (11, 0), (12, 1)]
bitsets = [(0, 0, 0), (0xffffffffffffffff, 0xffffffffffffffff, (1 << 51) - 1),
(16, 0, 0), (0, 0, 1 << 50), (0, 0, 1 << 28), (0x1c00, 0, 0)]
pending_cases = [1 << bit for bit in range(32)] + [0, 0xffffffff, 0x90000100, 0x43881100]
rows = []
for profile, dynamic in enumerate((b"", b"".join(struct.pack("<HxxIII", e, m, 0, 0) for e, m in device))):
row_size = 16
table_data = fixed + dynamic
cpu.mem_write(TABLE, table_data)
cpu.mem_write(INTR + 0x430, struct.pack("<QQII", TABLE, 0, row_size, 0) +
struct.pack("<I", len(table_data) // row_size))
for pending, requested in itertools.product(pending_cases, bitsets):
cpu.mem_write(ENGINES, b"\xff" * 24)
cpu.reg_write(UC_X86_REG_RCX, ENGINES)
call("_nv037524rm", 0, INTR, pending)
decoded = struct.unpack("<QQQ", cpu.mem_read(ENGINES, 24))
cpu.mem_write(ENGINES, struct.pack("<QQQ", *requested))
encoded = call("_nv037523rm", 0, INTR, ENGINES) & 0xffffffff
rows.append(" ".join(f"{value:x}" for value in (profile, pending, *requested, *decoded, encoded)))
out = ROOT / "target/gv100-stall/original-routes.txt"
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text("\n".join(rows) + "\n")
report = {
"original_sha256": DIGEST, "chip_hal": "0x23", "rm_hal": 2,
"bindings": {hex(slot): name for slot, name in BINDINGS.items()},
"fixed_table_rodata": [hex(offset) for offset in boundaries],
"fixed_rows": list(struct.iter_unpack("<HxxIII", fixed)),
"cases": len(rows), "oracle_sha256": hashlib.sha256(out.read_bytes()).hexdigest(),
"scope": "Original binder and both conversion loops including vector iteration and bitset access. Table allocation and memset supplied by the fixture. Device-specific rows are modeled. No GPU MMIO."
}
(ROOT / "reports/gv100-stall-routes-original.json").write_text(json.dumps(report, indent=2) + "\n")
print(f"{len(rows)} original bidirectional route cases")
# Execute the actual scoped wait dispatch and PMC sampler with modeled leaves.
scope_mode = True
cpu.mem_write(GPU + 0x2110, struct.pack("<Q", INTR))
cpu.mem_write(GPU + 0x1f58, struct.pack("<Q", THERMAL))
cpu.mem_write(THERMAL + 0x21d, b"\x01")
cpu.mem_write(INTR + 0x3f6, b"\x01")
cpu.mem_write(TABLE, fixed)
cpu.mem_write(INTR + 0x430, struct.pack("<QQIII", TABLE, 0, 16, 0, len(fixed) // 16))
def return_value(emu, value=0):
rsp = emu.reg_read(UC_X86_REG_RSP)
emu.reg_write(UC_X86_REG_RSP, rsp + 8)
emu.reg_write(UC_X86_REG_RAX, value)
emu.reg_write(UC_X86_REG_RIP, struct.unpack("<Q", emu.mem_read(rsp, 8))[0])
def scope_leaf(name):
def run(emu, address, size, unused):
a, b, c, d = (emu.reg_read(r) for r in (UC_X86_REG_RDI, UC_X86_REG_RSI, UC_X86_REG_RDX, UC_X86_REG_RCX))
value = 0
if name == "zero":
emu.mem_write(a, bytes(c))
value = a
elif name == "init":
assert b == 0xb3
emu.mem_write(a, bytes(24))
elif name == "read":
events.append(f"r:{d:x}")
value = {0: 0x140000a1, 0x100: sample}[d]
elif name == "enter":
emu.mem_write(a, struct.pack("<Q", 0x12345))
events.append(name)
elif name == "leave":
assert a == 0x12345
events.append(name)
elif name == "augment":
bits = struct.unpack("<Q", emu.mem_read(c, 8))[0]
emu.mem_write(c, struct.pack("<Q", bits | augmented))
events.append(name)
elif name == "dispatch":
events.append(f"source:{c:x}")
emu.mem_write(d, bytes(1))
if disconnect:
emu.mem_write(GPU + 0x915, bytes(1))
value = 0x55 if c == 1 else 0
elif name != "noop":
events.append(name)
return_value(emu, value)
return run
def scope_thunk(emu, address, size, unused):
emu.reg_write(UC_X86_REG_RIP, emu.reg_read(UC_X86_REG_RAX))
cpu.hook_add(UC_HOOK_CODE, scope_thunk, begin=INDIRECT, end=INDIRECT)
for name, purpose in (("_nv031390rm", "noop"), ("_nv047869rm", "noop"),
("_nv046745rm", "noop"), ("_nv046747rm", "noop"),
("_nv017883rm", "init"), ("_nv052705rm", "zero"),
("_nv053907rm", "read"), ("_nv054076rm", "enter"),
("_nv054075rm", "leave"), ("_nv013841rm", "expire"),
("_nv037553rm", "augment"), ("_nv037731rm", "dispatch"),
("_nv037695rm", "finish"), ("_nv040073rm", "thermal")):
address = TEXT + by_name[name]["st_value"]
cpu.hook_add(UC_HOOK_CODE, scope_leaf(purpose), begin=address, end=address)
rows = []
for live, disconnect, sample, augmented in itertools.product(
(0, 1), (0, 1), (0, 1 << 8, 1 << 20, 1 << 24, 1 << 26, 1 << 28, 0xffffffff), (0, 6)
):
events = []
cpu.mem_write(GPU + 0x915, bytes([live]))
call("_nv052478rm", GPU, 0, 0)
fields = " ".join(f"{value:x}" for value in (live, disconnect, sample, augmented))
rows.append(fields + ";" + " ".join(events))
(ROOT / "target/gv100-stall/original-pmu-scope.txt").write_text("\n".join(rows) + "\n")
print(f"{len(rows)} original GV100 PMU scoped dispatch cases")