Files
nvdriver/tools/check_gv100_nonstall_binary.py

783 lines
38 KiB
Python

#!/usr/bin/env python3
"""Run the selected original GV100 non-stall and PTIMER IRQ instructions."""
import hashlib
from _binary_path import resolve_580_binary
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, UC_X86_REG_R8, UC_X86_REG_R9,
)
ROOT = Path(__file__).resolve().parents[1]
ORIGINAL = resolve_580_binary()
DIGEST = "5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b"
TEXT, DATA, STACK, STOP = 0x10000000, 0x30000000, 0x40000000, 0x50000000
INTR, TABLE, ENGINES, CHIP, RM = DATA, DATA + 0x2000, DATA + 0x3000, DATA + 0x4000, DATA + 0x5000
BINDINGS = {0x118: "_nv037625rm", 0x120: "_nv037734rm",
0x138: "_nv037713rm", 0x300: "_nv037779rm"}
TIMER_BINDINGS = {0x1e8: "_nv059571rm", 0x1a8: "_nv059639rm",
0x208: "_nv059576rm", 0x200: "_nv059651rm"}
GPU, TIMER, INDIRECT = DATA + 0x10000, DATA + 0x18000, STOP + 0x100
EXECUTED = ("_nv005896rm", "_nv006016rm", "_nv037572rm", "_nv017883rm", "_nv017897rm",
"_nv060218rm", "_nv060220rm", "_nv060224rm", "_nv060225rm", "_nv060226rm",
"_nv059625rm", "_nv016000rm", "_nv055564rm", "_nv015990rm",
"_nv015981rm", "_nv015982rm", "_nv015987rm", "_nv015988rm",
"_nv015989rm", "_nv015992rm", "_nv015993rm", "_nv015994rm",
"_nv028101rm", "_nv028063rm", "_nv028344rm", "_nv040361rm", "_nv015986rm",
"_nv028192rm", "_nv028190rm", "_nv028203rm", "_nv027888rm",
"_nv040320rm", "_nv040815rm", "_nv043705rm",
"_nv027655rm", "_nv028130rm", "_nv042890rm", "_nv042917rm",
"_nv006034rm", "_nv052350rm", "_nv052357rm", "_nv052361rm",
"_nv042848rm", "_nv042924rm", "_nv042925rm", "_nv042861rm",
"_nv042866rm", "_nv042896rm", "_nv042906rm", "_nv043113rm",
*BINDINGS.values(), *TIMER_BINDINGS.values())
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")
ranges = [(by_name[name]["st_value"], by_name[name]["st_size"]) for name in EXECUTED]
for relocation in elf.get_section_by_name(".rela.text").iter_relocations():
offset = relocation["r_offset"]
if not any(start <= offset < start + size for start, size in ranges):
continue
kind = relocation["r_info_type"]
target = symbols[relocation["r_info_sym"]]
if target.name == "__x86_indirect_thunk_rax":
address = INDIRECT
else:
assert target["st_shndx"] == text_section, target.name
address = TEXT + 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)
cpu = Uc(UC_ARCH_X86, UC_MODE_64)
for address, size in ((TEXT, (len(text) + 4095) & ~4095), (DATA, 0x20000),
(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, *arguments):
registers = (UC_X86_REG_RDI, UC_X86_REG_RSI, UC_X86_REG_RDX, UC_X86_REG_RCX,
UC_X86_REG_R8, UC_X86_REG_R9)
for register, argument in zip(registers, arguments):
cpu.reg_write(register, argument)
rsp = STACK + 0xffc8
cpu.reg_write(UC_X86_REG_RSP, rsp)
cpu.reg_write(UC_X86_REG_RBP, STACK + 0x8000)
cpu.mem_write(rsp, struct.pack("<" + "Q" * (1 + len(arguments[6:])), STOP, *arguments[6:]))
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)
for binder, owner, bindings in (
("_nv005896rm", INTR, BINDINGS), ("_nv006016rm", TIMER, TIMER_BINDINGS)
):
call(binder, owner, CHIP, RM)
for slot, name in bindings.items():
assert struct.unpack("<Q", cpu.mem_read(owner + slot, 8))[0] == TEXT + by_name[name]["st_value"]
HOOKS = {
TEXT + by_name[name]["st_value"]: name for name in (
"_nv052705rm", "_nv046745rm", "_nv046747rm", "_nv047869rm", "_nv047868rm",
"_nv037736rm", "_nv053907rm", "_nv053912rm", "_nv052743rm", "_nv052747rm",
"_nv030544rm", "_nv043253rm", "_nv043263rm", "_nv059578rm",
"_nv030608rm", "_nv043255rm", "_nv059505rm", "_nv037737rm",
"_nv059509rm", "_nv015976rm", "_nv015977rm", "_nv054348rm",
"_nv043721rm", "_nv049631rm",
"_nv027655rm", "_nv028130rm",
"_nv031518rm", "_nv031522rm", "_nv042848rm", "_nv053913rm",
"_nv054098rm", "_nv014034rm", "_nv031482rm", "_nv042934rm",
"_nv052461rm", "_nv052478rm",
)
}
trace = []
sample = 0
failed_engine = 0xffff
TIMER_CALLBACK, TIMER_LOCK, THREAD = STOP + 0x200, DATA + 0x1c000, DATA + 0x1d000
ALARM, COUNTDOWN = STOP + 0x300, STOP + 0x400
FIFO, SUBSYSTEM, FIFO_MODE, DEADLINE = DATA + 0x7000, DATA + 0x8000, DATA + 0x9000, DATA + 0xa000
timer_service_trace = False
rearm_head = None
rearm_now = 0
rearm_locked = False
weighted_trace = False
preempt_trace = False
preempt_reads = []
preempt_statuses = []
preempt_runlist = 0
restriction = DATA + 0x6000
SWITCH_RUNLIST, SWITCH_VTABLE, SWITCH_CONTEXT = DATA + 0x500, DATA + 0x1000, DATA + 0x5800
REARM = STOP + 0x700
switch_trace = False
switch_outgoing = 0
switch_incoming = 0
switch_admitted = 0
context_trace = False
context_address = 0
context_lock_balance = 0
wrapper_trace = False
wrapper_inner_restricted = False
wrapper_owned = False
wrapper_lookups = 0
lpwr_trace = False
lpwr_statuses = []
mutex_trace = False
mutex_reads = []
engine_trace = False
engine_scenario = 0
engine_id = 0
ENGINE_DOMAIN, QUEUE_PARENT, QUEUE = DATA + 0x6000, DATA + 0x4000, DATA + 0x400
ENGINE_ALLOW, ENGINE_ALT = STOP + 0x800, STOP + 0x900
PMU, LPWR, MUTEX_OWNER = DATA + 0x3000, DATA + 0x8000, DATA + 0x5000
CONTEXT_FIFO, CONTEXT_DESC = DATA + 0x200, DATA + 0xf000
def intercept(emu, pc, _size, _user):
global rearm_locked, context_lock_balance, wrapper_lookups
if pc == INDIRECT:
emu.reg_write(UC_X86_REG_RIP, emu.reg_read(UC_X86_REG_RAX))
return
name = {TIMER_CALLBACK: "timer_callback", ALARM: "alarm", COUNTDOWN: "countdown",
REARM: "rearm", ENGINE_ALLOW: "engine_allow",
ENGINE_ALT: "engine_alt"}.get(pc) or HOOKS.get(pc)
if name is None:
return
if lpwr_trace and name in ("_nv027655rm", "_nv028130rm"):
return
if engine_trace and name == "_nv042848rm":
return
a, b, c, d, x = (emu.reg_read(reg) for reg in (
UC_X86_REG_RDI, UC_X86_REG_RSI, UC_X86_REG_RDX, UC_X86_REG_RCX, UC_X86_REG_R8,
))
value = 0
if name == "_nv052705rm":
if engine_trace:
assert b == 0 and c in (16, 24)
emu.mem_write(a, bytes(c))
else:
assert a == ENGINES and b == 0 and c == 24
emu.mem_write(ENGINES, bytes(24))
elif name == "_nv053907rm":
assert a == GPU + 0x4120
trace.append(f"r:{d:x}")
if mutex_trace:
offset, value = mutex_reads.pop(0)
assert d == offset
else:
assert d in (0x104, 0x9100, 0x2638)
value = preempt_reads.pop(0) if d == 0x2638 else sample
elif name == "_nv053912rm":
assert a == GPU + 0x4120
trace.append(f"w:{d:x}:{x & 0xffffffff:x}")
elif mutex_trace and name == "_nv053913rm":
assert a == GPU + 0x4120 and d in (0x10a5a0, 0x10a48c)
trace.append(f"w:{d:x}:{x & 0xffffffff:x}")
elif context_trace and name in ("_nv052743rm", "_nv052747rm"):
assert a == TIMER_LOCK
context_lock_balance += 1 if name == "_nv052743rm" else -1
elif context_trace and name == "_nv043721rm":
assert a == CONTEXT_DESC and b == 1 and c == 0
value = context_address
elif context_trace and name == "_nv049631rm":
trace.append("sfence")
elif name == "_nv037736rm":
assert a == GPU and b == INTR
index = c & 0xffff
trace.append(f"d:{index:x}")
value = int(index == failed_engine)
elif timer_service_trace and name in ("_nv052743rm", "_nv052747rm"):
assert a == TIMER_LOCK
rearm_locked = name == "_nv052743rm"
trace.append("lock" if name == "_nv052743rm" else "unlock")
elif name == "timer_callback":
assert a == GPU and b == THREAD
trace.append("callback")
value = 0x40 # Callback failure leaves the interrupt claimed.
elif name == "_nv030544rm":
value = FIFO if switch_trace else FIFO_MODE
elif name == "_nv043253rm":
assert a == FIFO + 0x90 and b == 0 and rearm_locked
value = DEADLINE if rearm_head is not None else 0
elif name == "_nv043263rm":
assert a == FIFO + 0x90 and b == DEADLINE and rearm_locked
value = rearm_head
elif name == "_nv059578rm":
assert a == TIMER and c == THREAD and rearm_locked
emu.mem_write(b, struct.pack("<Q", rearm_now))
trace.append("sample")
elif name == "alarm":
assert a == GPU and b == TIMER and d == THREAD and rearm_locked
trace.append(f"a:{c:x}")
elif name == "countdown":
assert a == GPU and b == TIMER and x == THREAD and rearm_locked
trace.append(f"c:{c & 0xffffffff:x}:{d:x}")
elif weighted_trace and name in ("_nv047868rm", "_nv047869rm"):
code = b & 0xffffffff
if code in (0x13851122, 0x13d11122):
trace.append(f"{code:x}:{x & 0xffffffff:x}")
else:
trace.append(f"{code:x}")
elif preempt_trace and name == "_nv030608rm":
value = FIFO
elif preempt_trace and name == "_nv043255rm":
assert a == FIFO + 0x428 and b == preempt_runlist
if wrapper_trace:
if wrapper_lookups == 1:
emu.mem_write(restriction, bytes([wrapper_inner_restricted]))
wrapper_lookups += 1
trace.append("lookup")
value = restriction
elif preempt_trace and name == "_nv059505rm":
assert a == GPU + 0x1e08 and b == DEADLINE and c == 0x3e1
trace.append(f"timeout:{c:x}")
value = preempt_statuses.pop(0)
elif preempt_trace and name == "_nv037737rm":
assert a == GPU and c == 0 and d == 0
trace.append("recover")
elif preempt_trace and name == "_nv047869rm":
code = b & 0xffffffff
if code == 0x3570000:
trace.append("restricted")
elif code == 0x3e31000:
trace.append("expired")
elif wrapper_trace and code in (0x650000, 0x6b4100):
trace.append("outer:restricted" if code == 0x650000 else "outer:invalid")
elif switch_trace:
switch_labels = {
0xabd1000: "outgoing",
0xac81000: "preempt:before",
0xa501000: "incoming",
0xadf1000: "incoming:record",
0xaeb1000: "preempt:after",
}
if code in switch_labels:
trace.append(f"{switch_labels[code]}:{c & 0xffffffff:x}")
elif switch_trace and name == "_nv059509rm":
assert a == GPU + 0x1e08 and d == 0
trace.append(f"begin:{c:x}")
elif switch_trace and name in ("_nv015976rm", "_nv015977rm"):
assert a == SWITCH_RUNLIST and b == GPU and c == FIFO
index = d - SWITCH_CONTEXT
assert index in (0, 1, 2)
trace.append(("unload:" if name == "_nv015976rm" else "load:") + str(index))
value = switch_outgoing if name == "_nv015976rm" else switch_incoming
elif switch_trace and name == "_nv054348rm":
assert a == GPU
value = switch_admitted
elif name == "rearm":
assert a == SWITCH_RUNLIST and b == GPU and c == THREAD
trace.append(name)
elif wrapper_trace and name == "_nv027655rm":
assert a == GPU and b == CONTEXT_FIFO
trace.append("lpwr:get")
value = int(wrapper_owned)
elif wrapper_trace and name == "_nv028130rm":
assert a == GPU and b == CONTEXT_FIFO and wrapper_owned
trace.append("lpwr:put")
elif lpwr_trace and name == "_nv031518rm":
assert a == MUTEX_OWNER and b == 6 and c == DEADLINE and d == 0
token = struct.unpack("<I", emu.mem_read(c, 4))[0]
value = lpwr_statuses.pop(0)
trace.append(f"get:{token:x}")
emu.mem_write(c, struct.pack("<I", token + 7))
elif lpwr_trace and name == "_nv031522rm":
assert a == MUTEX_OWNER and b == 6 and c == DEADLINE
token = struct.unpack("<I", emu.mem_read(c, 4))[0]
trace.append(f"put:{token:x}")
elif lpwr_trace and name == "_nv042848rm":
assert a == GPU and b == LPWR and c in (0, 2)
mask = struct.unpack("<I", emu.mem_read(LPWR + 0xe0, 4))[0]
emu.mem_write(LPWR + 0xe0, struct.pack("<I", mask & ~(1 << c)))
trace.append(f"disable:{c:x}")
elif engine_trace and name == "_nv054098rm":
value = 1
elif engine_trace and name == "_nv014034rm":
assert a == GPU and b == engine_id
trace.append("prepare")
emu.mem_write(c, bytes([1]))
value = 0x11 if engine_scenario == 4 else 0
elif engine_trace and name == "_nv031482rm":
assert a == GPU and b == 1
trace.append("restore")
elif engine_trace and name == "_nv042934rm":
assert a == GPU and b == ENGINE_DOMAIN
trace.append("flush")
if engine_scenario == 8:
emu.mem_write(ENGINE_DOMAIN + 0xe0, bytes(4))
elif engine_trace and name == "_nv052461rm":
assert a == GPU and b == QUEUE and d == 0x14
trace.append("post:" + bytes(emu.mem_read(c, d)).hex())
value = 0x11 if engine_scenario == 3 else 0
elif engine_trace and name == "_nv059509rm":
assert a == GPU + 0x1e08 and c == d == 0
trace.append("begin")
elif engine_trace and name == "_nv052478rm":
assert a == GPU and b == QUEUE_PARENT
trace.append("service")
emu.mem_write(ENGINE_DOMAIN + 0x10c + engine_id * 0x108, struct.pack("<I", 2))
elif engine_trace and name == "_nv059505rm":
assert a == GPU + 0x1e08 and c == 0x950
trace.append("check")
value = 0x65 if engine_scenario == 5 else 0
elif engine_trace and name in ("engine_allow", "engine_alt"):
assert a == GPU and b == ENGINE_DOMAIN and c == engine_id
trace.append("allow" if name == "engine_allow" else "alternate")
value = 0x11
elif engine_trace and name == "_nv047869rm":
status = b & 0xffffffff
if status == 0x9520000:
trace.append("timeout")
if status in (0xfbc0000, 0x11490000):
trace.append("underflow")
stack = emu.reg_read(UC_X86_REG_RSP)
emu.reg_write(UC_X86_REG_RAX, value)
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)
fixed_offset = 0x4d3bf60
with ORIGINAL.open("rb") as stream:
raw = ELFFile(stream).get_section_by_name(".rodata").data()
fixed = raw[fixed_offset:fixed_offset + 15 * 16]
routes = fixed + struct.pack("<HxxIII", 178, 0x100, 0, 0) + struct.pack("<HxxIII", 4, 0x100, 0, 0)
cpu.mem_write(TABLE, routes)
rows = []
for operation, name in enumerate(("_nv037625rm", "_nv037734rm")):
for flags in ((0, 1, 0, 0, 0), (1, 0, 0, 0, 0), (1, 1, 1, 0, 0),
(1, 1, 0, 1, 0), (1, 1, 0, 0, 1), (1, 1, 0, 0, 0)):
enabled, connected, lost, blocked, rail = flags
# Service is reached only after the outer handler has admitted power.
if operation == 1 and rail:
continue
for offset, value in ((0x911, enabled), (0x915, connected),
(0x917, blocked), (0x918, lost)):
cpu.mem_write(GPU + offset, bytes([value]))
cpu.mem_write(GPU + 0x69e4, struct.pack("<I", 3 if rail else 0))
for table in (0, 1):
cpu.mem_write(INTR + 0x430, struct.pack("<QQIII", TABLE, 0, 16, 0, len(routes) // 16 if table else 0))
for sample in (0, 0x100, 0xffffffff, 0x80000000):
failed_engine = 178
trace.clear()
status = call(name, GPU, INTR, ENGINES, 0) & 0xffffffff
engines = struct.unpack("<QQQ", cpu.mem_read(ENGINES, 24))
values = (operation, *flags, table, sample, status, *engines)
rows.append(" ".join(f"{value:x}" for value in values) + ";" + " ".join(trace))
timer_rows = []
for kind in (0, 1):
# The legacy branch uses +0x248 one for the alarm, zero for countdown.
cpu.mem_write(TIMER + 0x248, bytes([1 - kind]))
for sample in range(4):
trace.clear()
handled = call("_nv059625rm", GPU, TIMER, 0) & 0xff
timer_rows.append(f"{kind:x} {sample:x} {handled:x};" + " ".join(trace))
timer_service_rows = []
timer_service_trace = True
cpu.mem_write(TIMER + 0x2500, struct.pack("<Q", TIMER_LOCK))
for registered in (1, 0):
call("_nv059643rm", TIMER, TIMER_CALLBACK if registered else 0)
for kind in (0, 1):
cpu.mem_write(TIMER + 0x248, bytes([1 - kind]))
for sample in (0, 1, 2, 3, 0xffffffff):
trace.clear()
handled = call("_nv059625rm", GPU, TIMER, THREAD) & 0xff
timer_service_rows.append(
f"{kind:x} {sample:x} {registered:x} {handled:x};" + " ".join(trace)
)
out = ROOT / "target/gv100-stall"
out.mkdir(parents=True, exist_ok=True)
for address, value in ((GPU + 0x22d8, SUBSYSTEM), (SUBSYSTEM + 0x7e0, FIFO),
(GPU + 0x1f60, TIMER), (FIFO + 0xa0, TIMER_LOCK),
(TIMER + 0x1e0, ALARM), (TIMER + 0x210, COUNTDOWN)):
cpu.mem_write(address, struct.pack("<Q", value))
rearm_rows = []
for fifo_mode in (0, 1):
for alternate in (0, 1):
cpu.mem_write(FIFO_MODE + 0x7cb, bytes([fifo_mode]))
cpu.mem_write(TIMER + 0x24d, bytes([alternate]))
for rearm_now, rearm_head in ((25, None), (25, 1), (25, 10025), (25, 10026),
(0xffffff00, 0x2ffffffff),
(0xffffffffffffd8ef, 0xffffffffffffd8ef),
(0xffffffffffffd8f0, 0), (0xffffffffffffffff, 0)):
trace.clear()
call("_nv016000rm", GPU, THREAD)
assert not rearm_locked
head = "-" if rearm_head is None else f"{rearm_head:x}"
rearm_rows.append(f"{fifo_mode:x} {alternate:x} {rearm_now:x} {head};" + " ".join(trace))
for name, contents in (("original-nonstall.txt", rows), ("original-ptimer-ack.txt", timer_rows),
("original-ptimer-service.txt", timer_service_rows),
("original-fifo-rearm.txt", rearm_rows)):
(out / name).write_text("\n".join(contents) + "\n")
group, policy, members = DATA + 0xb000, DATA + 0xc000, DATA + 0xe000
cpu.mem_write(group + 0x90, struct.pack("<Q", policy))
cpu.mem_write(group + 0xe8, struct.pack("<Q", members))
cpu.mem_write(policy + 0x54, struct.pack("<I", 1))
rotation_rows = []
for count in (0, 1, 3, 5):
cpu.mem_write(group + 0xc4, struct.pack("<I", count))
for current in range(count + 1):
for pattern in range(24):
inputs = []
for member in range(count):
eligibility = (pattern >> (member % 3)) & 1
remaining = (pattern + member) % 5
threshold = (pattern + member * 2) % 4
limit = (pattern + member * 3) % 4
flags = ((pattern + member) & 1, (pattern >> 2) & 1, (pattern >> 3) & 1)
inputs.extend((eligibility, remaining, threshold, limit, *flags))
base = members + member * 0x68
cpu.mem_write(base + 8, bytes([eligibility]))
cpu.mem_write(base + 0x38, struct.pack("<III", remaining, threshold, limit))
cpu.mem_write(base + 0x60, bytes(flags))
cpu.mem_write(group + 0xb4, struct.pack("<I", current))
# Keep previous in the valid member extent when testing the
# independent switch predicate on the post-selection state.
previous = pattern % count if count else 0
cpu.mem_write(group + 0xb8, struct.pack("<I", previous))
call("_nv055564rm", GPU, group)
selected = struct.unpack("<I", cpu.mem_read(group + 0xb4, 4))[0]
switch = call("_nv015990rm", group) & 0xff if count else 2
outputs = [selected, switch]
for member in range(count):
base = members + member * 0x68
outputs.append(struct.unpack("<I", cpu.mem_read(base + 0x38, 4))[0])
outputs.append(cpu.mem_read(base + 0x60, 1)[0])
rotation_rows.append(" ".join(f"{v:x}" for v in (count, current, previous, *inputs))
+ ";" + " ".join(f"{v:x}" for v in outputs))
(out / "original-fifo-rotation.txt").write_text("\n".join(rotation_rows) + "\n")
weighted_trace = True
weighted_rows = []
write32 = lambda address, value: cpu.mem_write(address, struct.pack("<I", value))
write64 = lambda address, value: cpu.mem_write(address, struct.pack("<Q", value))
read32 = lambda address: struct.unpack("<I", cpu.mem_read(address, 4))[0]
read64 = lambda address: struct.unpack("<Q", cpu.mem_read(address, 8))[0]
for selector in (0, 2, 3, 4, 5):
write32(policy + 0x54, selector)
for scan, fallback_enabled in ((0, 0), (1, 0), (0, 1), (1, 1)):
cpu.mem_write(group + 0xdbc1, bytes([scan, fallback_enabled]))
for count in (0, 1, 3, 5):
write32(group + 0xc4, count)
for pattern in range(16):
current = pattern % (count + 1)
fixed = (pattern + 1) % (count + 1)
elapsed = (pattern * 240) & 0xffffffff
charge = (0, 4, 6_000_000, 600_000)[pattern % 4]
usage_limit = (0, 4, 500_000, 15)[pattern % 4]
cursor = (pattern % (count + 1) - 1) & 0xffffffff
for field, value in ((0xb4, current), (0xbc, fixed), (0xb0, elapsed),
(0xac, charge), (0xdbc4, cursor)):
write32(group + field, value)
write64(group + 0xdbb8, usage_limit)
inputs = []
for i in range(count + 1):
position = members + i * 0x68
eligible = (pattern >> (i % 3)) & 1
runtime = ((1 << 63) + (pattern * 7 - i * 211)) & ((1 << 64) - 1)
usage = (i * 3 + pattern) * (100_000 if pattern % 5 == 0 else 1)
debt = ((800_000, 1_000_000, 1_000_001, 0)[pattern % 4]
if i == count else i * (pattern % 3))
remaining, threshold, limit = (pattern + i) % 5, pattern % 2, i % 4
selected_flag = (pattern + i) & 1
inputs.extend((eligible, runtime, usage, debt, remaining, threshold, limit, selected_flag))
cpu.mem_write(position + 8, bytes([eligible]))
for field, value in ((0x20, runtime), (0x28, usage), (0x30, debt)):
write64(position + field, value)
for field, value in ((0x38, remaining), (0x3c, threshold), (0x40, limit)):
write32(position + field, value)
cpu.mem_write(position + 0x60, bytes([selected_flag]))
trace.clear()
call("_nv055564rm", GPU, group)
outputs = [read32(group + 0xb4), read32(group + 0xdbc4)]
for i in range(count + 1):
position = members + i * 0x68
outputs.extend((read64(position + 0x28), read64(position + 0x30),
read32(position + 0x38), cpu.mem_read(position + 0x60, 1)[0]))
header = (selector, scan, fallback_enabled, count, current, fixed,
elapsed, charge, usage_limit, cursor)
weighted_rows.append(" ".join(f"{v:x}" for v in (*header, *inputs))
+ ";" + " ".join(f"{v:x}" for v in outputs)
+ ";" + " ".join(trace))
(out / "original-fifo-weighted.txt").write_text("\n".join(weighted_rows) + "\n")
weighted_trace = False
preempt_trace = True
for slot, symbol in ((0x5d8, "_nv027676rm"), (0x5c0, "_nv027678rm"),
(0x1e8, "_nv028063rm"), (0x1e0, "_nv028344rm"),
(0x5c8, "_nv027674rm"), (0x5d0, "_nv027672rm")):
write64(FIFO + slot, TEXT + by_name[symbol]["st_value"])
preempt_rows = []
for preempt_runlist in (0, 4, 31):
mask = 1 << preempt_runlist
for gates in ((0, 0, 0, 0, 0), (1, 0, 0, 1, 0), (0, 0x100, 0, 1, 0),
(0, 0, 1, 1, 0), (0, 0, 0, 1, 1), (0, 0, 0, 1, 0)):
blocked, lost, disabled, enabled, override = gates
cpu.mem_write(GPU + 0x917, struct.pack("<BH", blocked, lost))
cpu.mem_write(GPU + 0x926, bytes([disabled]))
cpu.mem_write(GPU + 0x52f2, bytes([override, enabled]))
for restricted in (0, 1):
cpu.mem_write(restriction, bytes([restricted]))
for scenario in range(4):
masks = ([0], [mask, mask, 0], [mask, mask], [])[scenario]
statuses = ([], [0xf, 0], [0, 0x65], [])[scenario]
preempt_reads = list(masks)
preempt_statuses = list(statuses)
trace.clear()
status = call("_nv028101rm", GPU, FIFO, DEADLINE, preempt_runlist,
int(scenario == 3), 0) & 0xffffffff
header = (preempt_runlist, *gates, restricted, scenario, status)
preempt_rows.append(" ".join(f"{v:x}" for v in header) + ";" + " ".join(trace))
(out / "original-runlist-preempt.txt").write_text("\n".join(preempt_rows) + "\n")
switch_trace = True
timer_service_trace = False
preempt_runlist = 4
write64(SWITCH_RUNLIST, SWITCH_VTABLE)
write32(SWITCH_RUNLIST + 0x48, preempt_runlist)
write64(SWITCH_VTABLE + 0xb8, REARM)
write64(FIFO + 0x678, TEXT + by_name["_nv027773rm"]["st_value"])
write64(FIFO + 0x670, TEXT + by_name["_nv027806rm"]["st_value"])
write64(group + 0xa0, TIMER_LOCK)
write32(policy + 0x54, 4)
write32(group + 0xc4, 2)
write32(group + 0xac, 57)
switch_rows = []
for previous, selected, presence, selected_flag, current_flag, force in (
(0, 0, 3, 0, 0, 0), (0, 0, 3, 0, 0, 1), (0, 0, 3, 1, 0, 0),
(0, 1, 3, 0, 0, 1), (0, 1, 3, 1, 0, 1), (0, 1, 1, 0, 0, 1),
(0, 1, 2, 0, 0, 1), (0, 2, 5, 0, 0, 1), (2, 2, 5, 0, 0, 0),
):
for before, switch_admitted, blocked, restricted, fallback_enabled in (
(0, 0, 0, 0, 0), (1, 0, 0, 0, 0), (1, 1, 0, 0, 1),
(0, 1, 0, 1, 1), (1, 1, 0, 1, 1), (1, 1, 1, 0, 1),
(0, 1, 1, 0, 1),
):
for switch_outgoing, switch_incoming in ((0, 0), (0xf, 0), (0x11, 0x65)):
cpu.mem_write(GPU + 0x93b, bytes([1]))
cpu.mem_write(GPU + 0x917, struct.pack("<BH", blocked, 0))
cpu.mem_write(GPU + 0x926, bytes([0]))
cpu.mem_write(GPU + 0x52f2, bytes([0, 1]))
cpu.mem_write(FIFO + 0x7cf, bytes([before]))
cpu.mem_write(restriction, bytes([restricted]))
write32(group + 0xb8, previous)
write32(group + 0xbc, selected)
cpu.mem_write(group + 0xdbc0, bytes([0, 0, fallback_enabled]))
for i in range(3):
write64(members + i * 0x68, SWITCH_CONTEXT + i if presence & (1 << i) else 0)
cpu.mem_write(members + i * 0x68 + 0x60, bytes([0, 0, 0]))
cpu.mem_write(members + selected * 0x68 + 0x60, bytes([selected_flag, current_flag, force]))
trace.clear()
status = call("_nv015986rm", GPU, SWITCH_RUNLIST, group, THREAD) & 0xffffffff
final_force = cpu.mem_read(members + selected * 0x68 + 0x62, 1)[0]
expired = cpu.mem_read(group + 0xdbc0, 1)[0]
did_rearm = int(trace[-1:] == ["rearm"])
if did_rearm:
trace.pop()
inputs = (previous, selected, presence, selected_flag, current_flag, force,
before, switch_admitted, blocked, restricted, fallback_enabled,
switch_outgoing, switch_incoming, status, final_force, expired, did_rearm)
switch_rows.append(" ".join(f"{value:x}" for value in inputs) + ";" + " ".join(trace))
(out / "original-fifo-switch.txt").write_text("\n".join(switch_rows) + "\n")
switch_trace = False
context_trace = True
write64(CONTEXT_FIFO + 0x7e8, TIMER_LOCK)
write64(CONTEXT_FIFO + 0x3b8, TEXT + by_name["_nv028203rm"]["st_value"])
write64(FIFO + 0x200, TEXT + by_name["_nv040404rm"]["st_value"])
write64(FIFO + 0x348, DATA + 0x3000)
write32(FIFO + 0x338, 16)
context_rows = []
for runlist in (0, 4, 15):
preempt_runlist = runlist
for space, coherent in ((1, 0), (1, 1), (2, 0), (6, 0), (7, 0), (8, 0)):
write32(CONTEXT_DESC + 0x70, space)
write32(CONTEXT_DESC + 0x7c, coherent)
for context_address, command in ((0, 0), (0x12345678000, 0x12345678),
(0xfffffff000, 0x75643210)):
# The replacement admits only aligned representable descriptors.
context_address &= (1 << 40) - 1
for restricted, enabled in ((0, 1), (1, 1), (1, 0)):
cpu.mem_write(GPU + 0x917, bytes([0, 0, 0]))
cpu.mem_write(GPU + 0x926, bytes([0]))
cpu.mem_write(GPU + 0x52f2, bytes([0, enabled]))
cpu.mem_write(restriction, bytes([restricted]))
trace.clear()
context_lock_balance = 0
status = call("_nv028190rm", GPU, CONTEXT_FIFO, runlist, CONTEXT_DESC,
0xdeadbeef, 0, command, THREAD) & 0xffffffff
assert context_lock_balance == int(bool(restricted and enabled))
data = (runlist, space, coherent, context_address, command, restricted, enabled, status)
context_rows.append(" ".join(f"{value:x}" for value in data) + ";" + " ".join(trace))
(out / "original-fifo-context.txt").write_text("\n".join(context_rows) + "\n")
wrapper_trace = True
write64(CONTEXT_FIFO + 0x3a8, TEXT + by_name["_nv027888rm"]["st_value"])
write32(CONTEXT_DESC + 0x70, 2)
context_address = 0x12345000
wrapper_rows = []
for enabled, outer_restricted, wrapper_inner_restricted in (
(0, 0, 0), (1, 1, 0), (1, 0, 0), (1, 0, 1),
):
for preempt_runlist, descriptor_present in ((0, 1), (4, 1), (16, 1), (4, 0)):
for thread_has_lpwr, wrapper_owned in ((False, False), (False, True), (True, True)):
wrapper_lookups = 0
context_lock_balance = 0
cpu.mem_write(GPU + 0x52f2, bytes([0, enabled]))
cpu.mem_write(restriction, bytes([outer_restricted]))
cpu.mem_write(THREAD + 0x48, bytes([8 if thread_has_lpwr else 0]))
trace.clear()
status = call("_nv028192rm", GPU, CONTEXT_FIFO, DEADLINE, preempt_runlist,
CONTEXT_DESC if descriptor_present else 0,
0xdeadbeef, 0, 0x12345678, 1, THREAD) & 0xffffffff
inputs = (enabled, outer_restricted, wrapper_inner_restricted, preempt_runlist,
descriptor_present, thread_has_lpwr, wrapper_owned, status)
wrapper_rows.append(" ".join(f"{value:x}" for value in inputs) + ";" + " ".join(trace))
(out / "original-fifo-context-wrapper.txt").write_text("\n".join(wrapper_rows) + "\n")
wrapper_trace = False
lpwr_trace = True
write64(GPU + 0x1f50, MUTEX_OWNER)
lpwr_rows = []
for pmu_present, lpwr_present, enabled, mask, feature, already in (
(0, 1, 1, 5, 2, 0), (1, 0, 1, 5, 2, 0), (1, 1, 1, 0, 2, 0),
(1, 1, 1, 1, 0, 0), (1, 1, 0, 5, 2, 0), (1, 1, 1, 5, 2, 1),
(1, 1, 1, 4, 0, 0), (1, 1, 1, 1, 2, 0), (1, 1, 1, 5, 0, 0),
):
write64(GPU + 0x22c8, PMU if pmu_present else 0)
write64(PMU + 0x11c0, LPWR if lpwr_present else 0)
cpu.mem_write(PMU + 0x271, bytes([enabled]))
write32(LPWR + 0x130, feature)
for scenario, statuses in enumerate(([0], [0x63] * 19 + [0], [0x63] * 20, [0x42])):
write32(LPWR + 0xe0, mask)
write32(DEADLINE, 0)
cpu.mem_write(CONTEXT_FIFO + 0x838, bytes([already]))
lpwr_statuses = list(statuses)
trace.clear()
acquired = call("_nv027655rm", GPU, CONTEXT_FIFO, DEADLINE) & 0xff
if acquired:
call("_nv028130rm", GPU, CONTEXT_FIFO, DEADLINE)
held = cpu.mem_read(CONTEXT_FIFO + 0x838, 1)[0]
inputs = (pmu_present, lpwr_present, enabled, mask, feature, already, scenario, acquired,
held, read32(LPWR + 0xe0))
lpwr_rows.append(" ".join(f"{value:x}" for value in inputs) + ";" + " ".join(trace))
(out / "original-fifo-lpwr.txt").write_text("\n".join(lpwr_rows) + "\n")
lpwr_trace = False
mutex_trace = True
with ORIGINAL.open("rb") as stream:
data = ELFFile(stream).get_section_by_name(".data").data()
for offset in (0x6a350, 0x6a360):
assert [i for i, slot in enumerate(data[offset:offset + 16]) if slot == 6] == [8]
call("_nv006034rm", MUTEX_OWNER, CHIP)
for offset, name in ((0x38, "_nv052357rm"), (0x40, "_nv052350rm"), (0x48, "_nv052361rm")):
assert read64(MUTEX_OWNER + offset) == TEXT + by_name[name]["st_value"]
mutex_rows = []
for start_owner in (0, 0xa1230011):
for token_word in (0, 0xff, 0xffffffff, 0x12340036, 7, 0xfe):
for contended in (0, 1):
token = token_word & 0xff
free = 0xbacd0099
acquired = token not in (0, 0xff) and not contended
actual_owner = 0x88880000 | (0x11 if contended else token)
mutex_reads = [(0x10a5a0, start_owner), (0x10a488, token_word)]
if token not in (0, 0xff):
mutex_reads.append((0x10a5a0, actual_owner))
if acquired:
mutex_reads.append((0x10a5a0, actual_owner))
mutex_reads.append((0x10a48c, free))
trace.clear()
call("_nv052357rm", GPU, MUTEX_OWNER, 8, DEADLINE)
write32(DEADLINE, 0)
status = call("_nv052350rm", GPU, MUTEX_OWNER, 8, DEADLINE) & 0xffffffff
actual_token = read32(DEADLINE)
if acquired:
assert status == 0 and actual_token == token
call("_nv052357rm", GPU, MUTEX_OWNER, 8, DEADLINE)
assert read32(DEADLINE) == actual_token
call("_nv052361rm", GPU, MUTEX_OWNER, 8, actual_token)
assert not mutex_reads
inputs = (start_owner, token_word, contended, free, status, actual_token)
mutex_rows.append(" ".join(f"{value:x}" for value in inputs) + ";" + " ".join(trace))
(out / "original-pmu-lpwr-mutex.txt").write_text("\n".join(mutex_rows) + "\n")
mutex_trace = False
preempt_trace = False
engine_trace = True
write64(GPU + 0x2120, QUEUE_PARENT)
write64(QUEUE_PARENT + 0xf68, QUEUE)
write64(ENGINE_DOMAIN + 0x48, ENGINE_ALLOW)
write64(ENGINE_DOMAIN + 0x68, ENGINE_ALT)
cpu.mem_write(GPU + 0x917, bytes(3))
cpu.mem_write(GPU + 0x926, bytes(1))
engine_rows = []
for engine_id in (0, 2, 20, 21):
state = ENGINE_DOMAIN + engine_id * 0x108
for mode in (0, 1):
for engine_scenario in range(10):
enabled = engine_scenario != 0
ready = engine_scenario != 1
count = 2 if engine_scenario == 6 else 0xfffffffe if engine_scenario == 9 else 0
requests = 3 if engine_scenario == 6 else 0
firmware = 2 if engine_scenario == 7 else 0
cpu.mem_write(ENGINE_DOMAIN + 0xdb, bytes([mode, 0]))
write32(ENGINE_DOMAIN + 0xe0, (1 << engine_id) if enabled else 0)
cpu.mem_write(state + 0xe9, bytes([ready]))
for off, value in ((0x104, count), (0x108, requests), (0x10c, firmware),
(0x110, count), (0x114, requests), (0x154, 0)):
write32(state + off, value)
cpu.mem_write(state + 0x118, bytes(1))
trace.clear()
assert call("_nv042848rm", GPU, ENGINE_DOMAIN, engine_id) & 0xffffffff == 0
outputs = [read32(state + offset) for offset in (0x104, 0x108, 0x10c, 0x110, 0x114)]
outputs.extend((cpu.mem_read(state + 0x118, 1)[0], read32(state + 0x154)))
inputs = (engine_id, mode, engine_scenario, enabled, ready, count, requests, firmware)
engine_rows.append(" ".join(f"{value:x}" for value in (*inputs, *outputs)) + ";" + " ".join(trace))
(out / "original-fifo-lpwr-engine.txt").write_text("\n".join(engine_rows) + "\n")
report = {
"original_sha256": DIGEST, "chip_hal": "0x23", "rm_hal": 2,
"bindings": {hex(slot): name for slot, name in BINDINGS.items()},
"ptimer_bindings": {hex(slot): name for slot, name in TIMER_BINDINGS.items()},
"nonstall_cases": len(rows), "ptimer_cases": len(timer_rows),
"scope": "Original binder, PMC1 sample and dispatch loops, and legacy PTIMER condition/acknowledgment. MMIO, deferred source service, diagnostics and timer spin-lock leaves are fixture-supplied."
}
(ROOT / "reports/gv100-nonstall-original.json").write_text(json.dumps(report, indent=2) + "\n")
service_report = {
"original_sha256": DIGEST, "chip_hal": "0x23", "rm_hal": 2,
"executed": ["_nv006016rm", "_nv059643rm", "_nv059625rm", *TIMER_BINDINGS.values()],
"cases": len(timer_service_rows),
"oracle": "target/gv100-stall/original-ptimer-service.txt",
"scope": "Original legacy PTIMER condition, acknowledgment and callback ordering. MMIO, timer spin-lock operations and the deadline callback body are fixture-supplied."
}
(ROOT / "reports/gv100-ptimer-service-original.json").write_text(
json.dumps(service_report, indent=2) + "\n"
)
print(f"{len(rows)} original non-stall, {len(timer_rows)} PTIMER acknowledgment, "
f"{len(timer_service_rows)} PTIMER service, {len(rearm_rows)} FIFO rearm, "
f"{len(rotation_rows)} FIFO rotation, {len(weighted_rows)} FIFO weighted, "
f"{len(preempt_rows)} runlist preemption, {len(switch_rows)} FIFO switch, "
f"{len(context_rows)} context command, {len(wrapper_rows)} context wrapper, "
f"{len(lpwr_rows)} LPWR, {len(mutex_rows)} physical mutex, "
f"and {len(engine_rows)} LPWR engine cases")