Files
nvdriver/tools/check_gpu_clock_gating_providers_binary.py

784 lines
38 KiB
Python

#!/usr/bin/env python3
"""Run the original providers of the GV100 clock-gating table loads.
tools/check_gpu_clock_gating_binary.py runs the table loaders with their inputs
and services supplied by the fixture. This harness runs the original functions
that produce those inputs and services, and writes an oracle for
src/nvidia/src/gpu/clock_gating_providers.rs.
Executed original code:
- _nv031034rm (feature query) with the GPU-object function at +6e8 the binder
_nv005982rm selects for GV100 (_nv031029rm), _nv031133rm and _nv031134rm
(feature record), reading the two tables at .data+0x41120 and .data+0x40c00;
- _nv030843rm, the GPU-object function at +2d0 that reads the registry words
the feature query uses;
- _nv034073rm (stores the five fields the OBJBUS function at +300 reads),
_nv032989rm (Graphics+c78), _nv034023rm, _nv041838rm;
- _nv000333rm with _nv034037rm (the Graphics object the loaders write through);
- _nv033225rm (Graphics+a50), _nv031724rm, _nv033987rm, _nv037841rm,
_nv006535rm, _nv005671rm, _nv005738rm, _nv005757rm, _nv003332rm, _nv003389rm,
_nv003413rm, _nv037840rm (the register object at Graphics+1758 whose +50
pointer is Graphics+17a8), and its 32-bit write _nv003747rm, _nv037850rm,
_nv031390rm, _nv037851rm reached through the +40 slot of the vtable the
constructor stores;
- _nv033667rm (Graphics PreInitLocked) with _nv017885rm, _nv017897rm,
Graphics+d10 (_nv033245rm), Graphics+1348 (_nv033433rm) and everything
tools/check_gpu_clock_gating_binary.py lists beneath _nv033505rm;
- the property initializers _nv005782rm (Graphics), _nv005803rm (GPU+22c8
object), _nv005773rm (its +11d8 object) and _nv005825rm (GPU object) with
chip HAL 0x23 and RM HAL 2.
Fixture-supplied leaves: the log and assertion routines, the registry readers,
register read _nv053907rm and write _nv053912rm, the thread-local lookup
_nv059517rm, _nv033983rm, _nv034062rm, _nv034063rm, _nv031779rm, _nv031723rm,
the allocator and memory fill, and below the register object's write
_nv031391rm, _nv031156rm, _nv059477rm, _nv013540rm and _nv049615rm. No
hardware is involved.
"""
import bisect
from _binary_path import resolve_580_binary
import hashlib
import itertools
import json
from pathlib import Path
import re
import struct
import sys
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_R8, UC_X86_REG_R9, 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"
TABLES = ROOT / "src/nvidia/src/gpu/clock_gating_feature_tables.rs"
TEXT, SDATA, DATA, STACK, STOP, RODATA, BSS = (0x10000000, 0x20000000, 0x30000000, 0x40000000,
0x50000000, 0x60000000, 0x70000000)
(GPU, GR, CHIP, RM, LPWR, CHILD, GRMGR, INFO, KMIG, PARENT, MAPPING, HEAP, THREAD) = (
DATA, DATA + 0x10000, DATA + 0x20000, DATA + 0x21000, DATA + 0x22000, DATA + 0x25000,
DATA + 0x40000, DATA + 0x42000, DATA + 0x44000, DATA + 0x49000, DATA + 0x4a000,
DATA + 0x4b000, DATA + 0x4c000)
INDIRECT_RAX, INDIRECT_R8, INDIRECT_R11 = STOP + 0x100, STOP + 0x110, STOP + 0x120
FEATURES_AT, FEATURES_COUNT = 0x41120, 0x20 # .data, 24-byte rows
ENGINES_AT, ENGINES_COUNT = 0x40c00, 0x29 # .data, 32-byte rows
APERTURE_METADATA = (0x4da9740, 0x4da9808) # .rodata, the register object's class data
SENTINEL, GRAPHICS = 0xb33b1500, 0xd334df00
ROOTS = ("_nv031034rm", "_nv031133rm", "_nv031134rm", "_nv031029rm", "_nv030843rm",
"_nv034073rm", "_nv032989rm", "_nv000333rm", "_nv033225rm", "_nv031724rm",
"_nv003747rm", "_nv037850rm", "_nv033667rm", "_nv033433rm", "_nv033245rm",
"_nv005978rm", "_nv005980rm", "_nv005982rm", "_nv005886rm", "_nv005887rm", "_nv005888rm",
"_nv005889rm", "_nv005890rm", "_nv005782rm", "_nv005803rm", "_nv005773rm",
"_nv005825rm", "_nv033738rm", "_nv033764rm", "_nv030977rm", "_nv030976rm",
"_nv030423rm", "_nv030728rm", "_nv030519rm", "_nv030891rm", "_nv030902rm",
"_nv030894rm")
HOOKED = ("_nv047869rm", "_nv047868rm", "_nv046745rm", "_nv046747rm", "_nv049786rm",
"_nv049785rm", "_nv052687rm", "_nv052701rm", "_nv052705rm", "_nv054347rm",
"_nv036619rm", "_nv030844rm", "_nv053907rm", "_nv053912rm", "_nv059517rm",
"_nv033983rm", "_nv034062rm", "_nv034063rm", "_nv031779rm", "_nv031723rm",
"_nv031391rm", "_nv031156rm", "_nv059477rm", "_nv013540rm", "_nv049615rm",
"_nv042890rm", "_nv042924rm", "_nv042925rm")
# Registry values _nv030843rm reads that the clock-gating path uses, in the
# order it reads them, with the GPU field each one sets.
KEYS = ("RMPowerFeature", "RMDisableFeatureDisablement", "RMPowerFeature2", "RMElcg", "RMBlcg",
"RMFspg", "RMSlcg", "RMClkSlowDown", "RmWar1760398")
WORDS = (0x6a6c, 0x6a70, 0x6a98, 0x6a78, 0x6a80, 0x6a84, 0x6a88)
assert hashlib.sha256(ORIGINAL.read_bytes()).hexdigest() == DIGEST
bindings = json.loads((ROOT / "reports/gv100-engine-hal-bindings.json").read_text())
assert bindings["original_sha256"] == 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())
data = bytearray(elf.get_section_by_name(".data").data())
rodata = bytearray(elf.get_section_by_name(".rodata").data())
bss_size = elf.get_section_by_name(".bss")["sh_size"]
indexes = {name: elf.get_section_index(name) for name in (".text", ".data", ".rodata", ".bss")}
text_section = indexes[".text"]
starts = sorted((symbol["st_value"], symbol["st_size"], symbol.name) for symbol in symbols
if symbol["st_shndx"] == text_section and symbol["st_size"])
relocations = sorted((relocation["r_offset"], relocation["r_info_type"],
relocation["r_info_sym"], relocation["r_addend"])
for relocation in elf.get_section_by_name(".rela.text").iter_relocations())
data_relocations = [(relocation["r_offset"], relocation["r_info_type"],
relocation["r_info_sym"], relocation["r_addend"])
for relocation in elf.get_section_by_name(".rela.data").iter_relocations()]
rodata_relocations = [(relocation["r_offset"], relocation["r_info_type"],
relocation["r_info_sym"], relocation["r_addend"])
for relocation in elf.get_section_by_name(".rela.rodata").iter_relocations()
if APERTURE_METADATA[0] <= relocation["r_offset"] < APERTURE_METADATA[1]]
bases = {indexes[".text"]: TEXT, indexes[".data"]: SDATA, indexes[".rodata"]: RODATA,
indexes[".bss"]: BSS}
FEATURES = [struct.unpack_from("<6I", data, FEATURES_AT + 24 * index)
for index in range(FEATURES_COUNT)]
ENGINES = [struct.unpack_from("<8I", data, ENGINES_AT + 32 * index)
for index in range(ENGINES_COUNT)]
# Columns the original instructions never read are zero or a name pointer.
assert all(row[4:] == (0, 0) for row in FEATURES)
assert all(row[1] == 0 and row[6:] == (0, 0) for row in ENGINES)
assert all(row[1] < 13 and row[2] < 32 for row in FEATURES)
assert all(row[3] < 8 and row[4] < 32 for row in ENGINES)
table_bytes = bytes(data[ENGINES_AT:FEATURES_AT + 24 * FEATURES_COUNT])
TABLE_DIGEST = hashlib.sha256(table_bytes).hexdigest()
assert TABLE_DIGEST == "eb6c6ebfabb25d5733fc58d94095ae68d4a1f01e6fc691b7f02f17da8005fb4c", TABLE_DIGEST
def rust_tables():
return (
"//! Feature tables of the GPU object, copied from the .data of the original\n"
"//! object by tools/check_gpu_clock_gating_providers_binary.py (--write-tables).\n"
"//! The same tool compares every number below with the object on each run. Do\n"
"//! not edit by hand.\n\n"
f"/// The {FEATURES_COUNT:#x} rows _nv031034rm and _nv031134rm search at .data+{FEATURES_AT:#x}:\n"
"/// (feature, record word, shift, mask).\n"
"#[rustfmt::skip]\n"
"pub const FEATURES: &[(u32, u32, u32, u32)] = &[\n" + "".join(
f" ({row[0]:#x}, {row[1]:#x}, {row[2]:#x}, {row[3]:#x}),\n" for row in FEATURES)
+ "];\n\n"
f"/// The {ENGINES_COUNT:#x} rows they search at .data+{ENGINES_AT:#x}: (engine descriptor, feature,\n"
"/// record word, shift, mask).\n"
"#[rustfmt::skip]\n"
"pub const ENGINE_FEATURES: &[(u32, u32, u32, u32, u32)] = &[\n" + "".join(
f" ({row[0]:#x}, {row[2]:#x}, {row[3]:#x}, {row[4]:#x}, {row[5]:#x}),\n"
for row in ENGINES) + "];\n")
if "--write-tables" in sys.argv:
TABLES.write_text(rust_tables())
assert TABLES.read_text() == rust_tables(), f"{TABLES} is not the generated text"
# Relocate the executed code. Data references go to the section images below.
offsets = [entry[0] for entry in relocations]
entries = {symbol[0]: symbol[2] for symbol in starts}
executed, pending = [], list(ROOTS)
THUNKS = {"__x86_indirect_thunk_rax": INDIRECT_RAX, "__x86_indirect_thunk_r8": INDIRECT_R8,
"__x86_indirect_thunk_r11": INDIRECT_R11}
while pending:
name = pending.pop()
if name in executed or name in HOOKED:
continue
executed.append(name)
start, size = by_name[name]["st_value"], by_name[name]["st_size"]
for offset, kind, index, addend in relocations[bisect.bisect_left(offsets, start):
bisect.bisect_left(offsets, start + size)]:
target = symbols[index]
if target.name in THUNKS:
address = THUNKS[target.name]
else:
assert target["st_shndx"] in bases, (name, target.name)
address = bases[target["st_shndx"]] + target["st_value"]
# Follow direct calls and tail calls only, not stored pointers.
if (target["st_shndx"] == text_section and kind in (2, 4)
and text[offset - 1] in (0xe8, 0xe9)):
callee = entries.get(target["st_value"] + addend + 4)
if callee and callee not in HOOKED:
pending.append(callee)
value = address + addend
if kind in (2, 4):
value -= TEXT + offset
else:
assert kind == 11, kind
struct.pack_into("<i", text, offset, value)
# Pointers stored in the data the executed code reads: the clock-gating table
# descriptors and the register object's class data.
for image, entries_, low, high in ((data, data_relocations, 0x46c40, 0x47720 + 24 * 0x1e),
(rodata, rodata_relocations, *APERTURE_METADATA)):
for offset, kind, index, addend in entries_:
if low <= offset < high:
assert kind == 1, kind
target = symbols[index]
struct.pack_into("<Q", image, offset,
bases[target["st_shndx"]] + target["st_value"] + addend)
cpu = Uc(UC_ARCH_X86, UC_MODE_64)
for address, size in ((TEXT, (len(text) + 4095) & ~4095), (SDATA, (len(data) + 4095) & ~4095),
(RODATA, (len(rodata) + 4095) & ~4095), (BSS, (bss_size + 4095) & ~4095),
(DATA, 0x50000), (STACK, 0x10000), (STOP, 0x1000)):
cpu.mem_map(address, size)
cpu.mem_write(TEXT, bytes(text))
cpu.mem_write(SDATA, bytes(data))
cpu.mem_write(RODATA, bytes(rodata))
case, trace = {}, []
ARGUMENTS = (UC_X86_REG_RDI, UC_X86_REG_RSI, UC_X86_REG_RDX, UC_X86_REG_RCX, UC_X86_REG_R8,
UC_X86_REG_R9)
def leave(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 text_at(emu, address):
out = bytearray()
while True:
byte = emu.mem_read(address + len(out), 1)[0]
if not byte:
return out.decode()
out.append(byte)
def leaf(name):
def run(emu, address, size, unused):
full = [emu.reg_read(register) for register in ARGUMENTS]
a, b, c, d, e, f = full
low = [value & 0xffffffff for value in full]
rsp = emu.reg_read(UC_X86_REG_RSP)
value = 0
if name in ("_nv047869rm", "_nv047868rm"):
trace.append(f"l:{low[0]:x}:{low[1]:x}")
elif name == "_nv046745rm":
trace.append(f"a:{low[0]:x}")
elif name == "_nv046747rm":
trace.append(f"as:{low[0]:x}:{low[1]:x}")
elif name == "_nv049786rm":
assert a == GPU
key = text_at(emu, b)
case["queried"].append(key)
found = case["registry"].get(key)
if found is None:
value = 0x57
else:
emu.mem_write(c, struct.pack("<I", found))
elif name == "_nv049785rm":
value = 0x57
elif name == "_nv052687rm":
value = HEAP
elif name in ("_nv052701rm", "_nv030844rm", "_nv054347rm", "_nv036619rm"):
pass
elif name == "_nv052705rm":
emu.mem_write(a, bytes([low[1] & 0xff]) * c)
value = a
elif name == "_nv053907rm":
assert (a, low[1], low[2]) == (GPU + 0x4120, 0, 0)
value = case["reads"].pop(0)
trace.append(f"r:{low[3]:x}:{value:x}")
elif name == "_nv053912rm":
assert (a, low[1], low[2], low[5]) == (GPU + 0x4120, 0, 0, 0)
trace.append(f"w:{low[3]:x}:{low[4]:x}")
elif name == "_nv059517rm":
assert a == case["tls_key"], hex(a)
value = case["tls"]
trace.append(f"t:{value:x}")
elif name == "_nv033983rm":
assert (a, b, low[2]) == (GPU, GRMGR, case["instance"]), full
assert struct.unpack("<I", emu.mem_read(e, 4))[0] == 0
emu.mem_write(e, struct.pack("<I", case["mig_value"]))
value = case["mig_status"]
trace.append(f"m:{low[2]:x}:{value:x}:{case['mig_value']:x}")
elif name in ("_nv034062rm", "_nv034063rm"):
raise AssertionError(name) # only reached for Graphics instances other than 0
elif name == "_nv031779rm":
trace.append(f"d:{a - GR:x}")
elif name == "_nv031723rm":
assert (a, b, c) == (GPU, GR, GR + 0x1658), full
value = case["status_1723"]
trace.append(f"c1723:{value:x}")
elif name == "_nv031391rm":
assert (a, b) == (GPU, 0), full
value = case["loop"]
trace.append(f"lp:{value:x}")
elif name == "_nv031156rm":
assert (a, low[2]) == (GPU, 0), full
value = case["sanity"]
trace.append(f"sc:{low[1]:x}:{value:x}")
elif name == "_nv059477rm":
assert b == GPU
emu.mem_write(a, struct.pack("<Q", THREAD))
elif name == "_nv013540rm":
stack = struct.unpack("<QQ", emu.mem_read(rsp + 8, 16))
assert (a, low[1], low[2], low[5], stack[1]) == (GPU, 0x11, 0x22, 0x20, THREAD), full
assert struct.unpack("<I", emu.mem_read(stack[0], 4))[0] == 0
emu.mem_write(stack[0], struct.pack("<I", case["filter"]))
trace.append(f"f:{low[3]:x}:{low[4]:x}:{case['filter']:x}")
elif name == "_nv049615rm":
assert (a, b) == (GPU, MAPPING), full
trace.append(f"o:{low[2]:x}:{low[3]:x}")
else:
raise AssertionError(name) # _nv042890rm and its two companions are never reached
leave(emu, value)
return run
for register, entry in ((UC_X86_REG_RAX, INDIRECT_RAX), (UC_X86_REG_R8, INDIRECT_R8)):
cpu.hook_add(UC_HOOK_CODE, lambda emu, address, size, source: emu.reg_write(
UC_X86_REG_RIP, emu.reg_read(source)), register, begin=entry, end=entry)
for hooked in HOOKED:
entry = TEXT + by_name[hooked]["st_value"]
cpu.hook_add(UC_HOOK_CODE, leaf(hooked), begin=entry, end=entry)
def call(name, *arguments):
for register, argument in zip(ARGUMENTS, arguments):
cpu.reg_write(register, argument)
rsp = STACK + 0xff00
cpu.reg_write(UC_X86_REG_RSP, rsp)
cpu.reg_write(UC_X86_REG_RBP, STACK + 0x8000)
cpu.mem_write(rsp, struct.pack("<Q", STOP))
cpu.emu_start(TEXT + by_name[name]["st_value"], STOP, count=4000000)
assert cpu.reg_read(UC_X86_REG_RIP) == STOP, name
return cpu.reg_read(UC_X86_REG_RAX)
def q(address, value):
cpu.mem_write(address, struct.pack("<Q", value))
def d(address, value):
cpu.mem_write(address, struct.pack("<I", value))
def b(address, value):
cpu.mem_write(address, bytes([value]))
def pointer(address):
return struct.unpack("<Q", cpu.mem_read(address, 8))[0]
def word(address):
return struct.unpack("<I", cpu.mem_read(address, 4))[0]
def byte(address):
return cpu.mem_read(address, 1)[0]
def function_at(address):
return entries.get(address - TEXT)
# The property initializers, on storage filled with a marker so that a byte
# they leave alone is told from one they clear.
cpu.mem_write(CHIP + 0x10, struct.pack("<H", 0x23))
cpu.mem_write(RM + 0x10, struct.pack("<H", 2))
properties = {}
for label, binder, base, fields in (
("Graphics", "_nv005782rm", GR, (0x1596,)),
("GPU+22c8 object", "_nv005803rm", LPWR, (0x244, 0x269, 0x280)),
("+11d8 object", "_nv005773rm", CHILD, (0x183, 0x184, 0x189, 0x18b)),
("GPU", "_nv005825rm", GPU, (0x921, 0x92d, 0x52f2, 0x52f3, 0x6d41, 0x6d62))):
values = {}
for marker in (0xee, 0x11):
cpu.mem_write(base, bytes([marker]) * 0x8000)
q(GPU + 0x80, CHIP)
q(GPU + 0x88, RM)
# _nv005782rm takes (object, RM owner, chip owner); the others the chip
# owner first (reports/gv100-engine-hal-bindings.json, argument_conventions).
call(binder, base, *((RM, CHIP) if binder == "_nv005782rm" else (CHIP, RM)))
for field in fields:
values.setdefault(field, []).append(byte(base + field))
properties[label] = {
"initializer": binder,
"bytes": {f"{field:#x}": ("not written" if seen == [0xee, 0x11] else seen[0])
for field, seen in values.items()}}
assert all(seen == [0xee, 0x11] or seen[0] == seen[1] for seen in values.values())
assert properties == {
"Graphics": {"initializer": "_nv005782rm", "bytes": {"0x1596": 0}},
"GPU+22c8 object": {"initializer": "_nv005803rm",
"bytes": {"0x244": 1, "0x269": 0, "0x280": 0}},
"+11d8 object": {"initializer": "_nv005773rm",
"bytes": {"0x183": "not written", "0x184": "not written", "0x189": 0,
"0x18b": 0}},
"GPU": {"initializer": "_nv005825rm",
"bytes": {"0x921": 0, "0x92d": 0, "0x52f2": "not written",
"0x52f3": "not written", "0x6d41": "not written",
"0x6d62": "not written"}}}, properties
# Function tables, by the original binders.
cpu.mem_write(DATA, bytes(0x50000))
cpu.mem_write(CHIP + 0x10, struct.pack("<H", 0x23))
cpu.mem_write(RM + 0x10, struct.pack("<H", 2))
q(GPU + 0x80, CHIP)
q(GPU + 0x88, RM)
call("_nv005978rm", GPU)
call("_nv005980rm", GPU)
call("_nv005982rm", GPU)
for binder in ("_nv005886rm", "_nv005887rm", "_nv005888rm", "_nv005889rm", "_nv005890rm"):
call(binder, GR, CHIP, RM)
GPU_SLOTS = {0x6e8: "_nv031029rm", 0x2d0: "_nv030843rm", 0x5c8: "_nv030977rm",
0x740: "_nv030423rm", 0x748: "_nv030728rm", 0x750: "_nv030519rm",
0x758: "_nv030891rm", 0x760: "_nv030902rm", 0x768: "_nv030894rm"}
GR_SLOTS = {0xa50: "_nv033225rm", 0xc78: "_nv032989rm", 0xd10: "_nv033245rm",
0x1348: "_nv033433rm", 0x1478: "_nv033738rm", 0x1480: "_nv033764rm"}
bound = {}
for label, base, slots in (("GPU", GPU, GPU_SLOTS), ("Graphics", GR, GR_SLOTS)):
for slot, function in slots.items():
assert function_at(pointer(base + slot)) == function, (label, hex(slot))
bound[f"{label}+{slot:#x}"] = function
pristine = bytes(cpu.mem_read(DATA, 0x50000))
rows, counts = [], {}
def reset():
cpu.mem_write(DATA, pristine)
trace.clear()
case.clear()
case.update(queried=[], registry={}, reads=[])
def emit(kind, inputs, result, extra=()):
rows.append(f"{kind};" + " ".join(f"{value:x}" for value in inputs) + f";{result};"
+ " ".join(list(trace) + list(extra)))
counts[kind] = counts.get(kind, 0) + 1
def record_words():
return [word(GPU + 0x6d90 + 4 * index) for index in range(13)]
def changed(before, low=0x6a00, high=0x6e70):
"""Byte changes of the GPU image as `offset=value`."""
after = bytes(cpu.mem_read(GPU, 0x8000))
assert before[:low] == after[:low] and before[high:] == after[high:]
return [f"g{offset:x}={after[offset]:x}" for offset in range(low, high)
if before[offset] != after[offset]]
# F: _nv031034rm(gpu, feature, descriptor).
FEATURE_IDS = list(range(0x24)) + [0x40]
DESCRIPTORS = sorted({row[0] for row in ENGINES}) + [0x12345600]
PATTERNS = ((0, 0xffffffff, 0, 0xffffffff), (0x13579bdf, 0x2468ace1, 0xfedcba98, 0x0f1e2d3c),
(0xffffffff, 0x11111111, 0xffffffff, 0))
shifts = {row[0]: (row[2], row[3]) for row in FEATURES}
for feature, state, noise, d62 in itertools.product(FEATURE_IDS, range(4), (0, 0xa5a5a5a5),
(0, 1)):
shift, mask = shifts.get(feature, (0, 0))
selected = (state & mask) << shift | noise & ~(mask << shift) & 0xffffffff
wide = state == 2
for descriptor, pattern in itertools.product(DESCRIPTORS if wide else (GRAPHICS, SENTINEL),
PATTERNS if wide else PATTERNS[:1]):
reset()
# Only the word the feature number selects carries the state.
which = 0x6a98 if feature <= 2 else 0x6a70 if 0x11 <= feature <= 0x1f else 0x6a6c
values = {0x6a6c: noise ^ 0xffffffff, 0x6a70: noise ^ 0xffffffff, 0x6a98: noise ^ 0xffffffff,
0x6a78: pattern[0], 0x6a80: pattern[1], 0x6a84: pattern[2], 0x6a88: pattern[3]}
values[which] = selected
for offset, value in values.items():
d(GPU + offset, value)
b(GPU + 0x6d62, d62)
before = bytes(cpu.mem_read(GPU, 0x8000))
result = call("_nv031034rm", GPU, feature, descriptor) & 0xffffffff
emit("F", [feature, descriptor] + [values[offset] for offset in WORDS] + [d62],
f"{result:x}", changed(before))
# M: _nv031134rm(gpu, feature, descriptor, value); R: _nv031133rm(gpu, feature, descriptor, flag).
for feature, descriptor, value, fill in itertools.product(
FEATURE_IDS, DESCRIPTORS, (0, 1, 2, 3, 0xffffffff, 0x16), (0, 0xffffffff, 0xa5a55a5a)):
reset()
for index in range(13):
d(GPU + 0x6d90 + 4 * index, fill)
before = bytes(cpu.mem_read(GPU, 0x8000))
call("_nv031134rm", GPU, feature, descriptor, value)
changed(before, 0x6d90, 0x6dc4)
emit("M", [feature, descriptor, value, fill], "-",
[f"{value:x}" for value in record_words()])
for feature, descriptor, flag, fill in itertools.product(
FEATURE_IDS, DESCRIPTORS, (0, 1, 0x100, 0x80), (0, 0x5a5aa5a5)):
reset()
for index in range(13):
d(GPU + 0x6d90 + 4 * index, fill)
before = bytes(cpu.mem_read(GPU, 0x8000))
call("_nv031133rm", GPU, feature, descriptor, flag)
changed(before, 0x6d90, 0x6dc4)
# The original tests the low byte of the flag.
emit("R", [feature, descriptor, int(flag & 0xff != 0), fill], "-",
[f"{value:x}" for value in record_words()])
# W: _nv030843rm(gpu), the registry words. Every other key is absent.
REGISTRY_CASES = [{}]
REGISTRY_CASES.append({key: 0x10203040 + index for index, key in enumerate(KEYS)})
for key in KEYS:
for value in (0, 1, 2, 0xffffffff, 0x80000):
REGISTRY_CASES.append({key: value})
REGISTRY_CASES.append({"RMPowerFeature": 0x80000, "RMBlcg": 0xfffffff1, "RMPowerFeature2": 0x80,
"RMSlcg": 0xfffffffe})
queried_all = None
for registry, prior62, prior41 in itertools.product(REGISTRY_CASES, (0, 1), (0, 1)):
reset()
case["registry"] = dict(registry)
for offset in WORDS:
d(GPU + offset, 0xdeadbeef)
b(GPU + 0x6d62, prior62)
b(GPU + 0x6d41, prior41)
assert call("_nv030843rm", GPU) & 0xffffffff == 0
queried = [key for key in case["queried"] if key in KEYS]
assert queried == list(KEYS), queried
queried_all = queried_all or list(case["queried"])
assert case["queried"] == queried_all
mask = sum(1 << index for index, key in enumerate(KEYS) if key in registry)
emit("W", [mask] + [registry.get(key, 0) for key in KEYS] + [prior62, prior41], "0",
[f"{word(GPU + offset):x}" for offset in WORDS]
+ [f"{byte(GPU + 0x6d62):x}", f"{byte(GPU + 0x6d41):x}"])
trace.clear()
def objects(grmgr=1, info=1, kmig=0, gpu_92d=0, kmig_3eb0=0, kmig_3eb8=0, instance=0,
tls_key=1, valid=0, word_c=0):
q(GPU + 0x1fb8, GRMGR if grmgr else 0)
q(GPU + 0x1fc8, KMIG if kmig else 0)
for index in range(8):
q(GPU + 0x1fd8 + 8 * index, GR + 0x100000 * index if index else GR)
b(GPU + 0x92d, gpu_92d)
b(KMIG + 0x3eb0, kmig_3eb0)
q(KMIG + 0x3eb8, 0x1234 if kmig_3eb8 else 0)
q(GRMGR + 0x2b0, INFO if info else 0)
q(GRMGR + 0x2a8, 0x7151 if tls_key else 0)
d(GR + 0x1600, instance)
b(INFO + 0x1c, valid)
d(INFO + 0xc, word_c)
case.update(tls_key=0x7151, instance=instance)
# I: _nv034073rm(gpu, GPU+1fb8 object, a, b, c, d).
for values in ((6, 6, 7, 42), (0, 0, 0, 0), (0x1f, 0x1f, 0x1f, 0x3c1),
(0x11111111, 0x22222222, 0x33333333, 0x44444444)):
reset()
objects()
cpu.mem_write(INFO, b"\xcc" * 0x260)
before = bytes(cpu.mem_read(INFO, 0x260))
call("_nv034073rm", GPU, GRMGR, *values)
after = bytes(cpu.mem_read(INFO, 0x260))
assert before[:0xc] == after[:0xc] and before[0x1d:] == after[0x1d:]
emit("I", values, "-", [f"{value:x}" for value in struct.unpack_from("<4IB", after, 0xc)])
# C: Graphics+c78, _nv032989rm(gpu, graphics).
MIG = [(0, 0, 0, 0)] + [(1, *flags) for flags in itertools.product((0, 1), repeat=3)]
for (kmig, gpu_92d, kmig_3eb0, kmig_3eb8), instance, valid, word_c, (mig_status, mig_value) in (
itertools.product(MIG, (0, 1, 3), (0, 1), (0, 6, 0x80000001),
((0, 5), (0, 0), (0x56, 9)))):
in_use = kmig and gpu_92d and kmig_3eb0 and kmig_3eb8
if not in_use and (mig_status, mig_value) != (0, 5):
continue
reset()
objects(kmig=kmig, gpu_92d=gpu_92d, kmig_3eb0=kmig_3eb0, kmig_3eb8=kmig_3eb8,
instance=instance, valid=valid, word_c=word_c)
case.update(mig_status=mig_status, mig_value=mig_value)
before = bytes(cpu.mem_read(DATA, 0x50000))
result = call("_nv032989rm", GPU, GR) & 0xffffffff
assert bytes(cpu.mem_read(DATA, 0x50000)) == before
emit("C", [kmig, gpu_92d, kmig_3eb0, kmig_3eb8, instance, valid, word_c, mig_status,
mig_value], f"{result:x}")
# G: _nv000333rm(gpu): which GPU+1fd8 entry it returns, or none.
TLS = (0, 1, 2, 3, 5, 0xf, 0x10, 0x11, 0x100000001, 0xffffffffffffffff, 0x1fffffff1,
0xfffffffffffffffe)
for grmgr, tls_key, tls, (kmig, gpu_92d, kmig_3eb0, kmig_3eb8), (gpu_52f3, gpu_52f2) in (
itertools.product((0, 1), (0, 1), TLS, MIG, ((0, 0), (1, 0), (1, 1)))):
if not grmgr and (tls_key, tls) != (1, 0):
continue
if not tls_key and tls:
continue
reset()
objects(grmgr=grmgr, tls_key=tls_key, kmig=kmig, gpu_92d=gpu_92d, kmig_3eb0=kmig_3eb0,
kmig_3eb8=kmig_3eb8)
b(GPU + 0x52f3, gpu_52f3)
b(GPU + 0x52f2, gpu_52f2)
case.update(tls=tls)
before = bytes(cpu.mem_read(DATA, 0x50000))
result = call("_nv000333rm", GPU)
assert bytes(cpu.mem_read(DATA, 0x50000)) == before
index = "-" if result == 0 else f"{(result - GR) // 0x100000:x}"
assert result in (0, GR) or (result - GR) % 0x100000 == 0 and (result - GR) >> 20 < 8
emit("G", [grmgr, tls_key, tls & 0xffffffff, tls >> 32, kmig, gpu_92d, kmig_3eb0, kmig_3eb8,
gpu_52f3, gpu_52f2], index)
def parent_aperture(base, length, start, gpu=GPU):
cpu.mem_write(PARENT, bytes(0x88))
q(PARENT + 0x60, gpu)
d(PARENT + 0x68, 0x11)
d(PARENT + 0x6c, 0x22)
q(PARENT + 0x70, MAPPING)
d(PARENT + 0x78, start)
d(PARENT + 0x7c, base)
d(PARENT + 0x80, length)
q(GPU + 0x1d30, PARENT)
def aperture_fields(base):
return [word(base + 0x78), word(base + 0x7c), word(base + 0x80)]
# A: Graphics+a50 (_nv033225rm), _nv031724rm(gpu, graphics, graphics+1758) and
# one write through the +40 slot of the object at Graphics+17a8.
APERTURES = ((0, 0x1000000, 0), (0, 0x200000, 0), (0, 0x1fffff, 0), (0x1000, 0x1000000, 0),
(0x2000, 0x1000000, 0x1000), (0xfff00000, 0x400000, 0))
for (base, length, start), gpu_921, sanity, filter_, loop, (offset, value) in itertools.product(
APERTURES, (0, 1), (0, 0x55), (0, 2, 1), (0, 1),
((0x4041f0, 0xc646), (0x41bed4, 0xfffffff8), (0, 1))):
reset()
objects()
parent_aperture(base, length, start)
assert call(bound["Graphics+0xa50"], GPU, GR) & 0xffffffff == 0
register_base = [word(GR + 0x1858), word(GR + 0x185c)]
assert register_base == [0x400000, 0x200000]
status = call("_nv031724rm", GPU, GR, GR + 0x1758) & 0xffffffff
assert status == 0
created = list(trace)
target = pointer(GR + 0x17a8)
# The +50 pointer of the object built at Graphics+1758 is Graphics+17a8.
assert target == GR + 0x1790 and pointer(GR + 0x1758 + 0x58) == GR + 0x1758
assert (pointer(GR + 0x1758 + 0x60), word(GR + 0x1758 + 0x68), word(GR + 0x1758 + 0x6c),
pointer(GR + 0x1758 + 0x70)) == (GPU, 0x11, 0x22, MAPPING)
fields = aperture_fields(GR + 0x1758)
b(GPU + 0x921, gpu_921)
case.update(sanity=sanity, filter=filter_, loop=loop)
trace.clear()
write = pointer(pointer(target) + 0x40)
assert function_at(write) == "_nv003747rm"
call("_nv003747rm", target, offset, value)
# Creation events, the fields of the new object, then the write.
trace[:0] = created + [f"n:{fields[0]:x}:{fields[1]:x}:{fields[2]:x}"]
emit("A", [base, length, start, gpu_921, sanity, filter_, loop, offset, value],
f"{status:x}")
# P: Graphics PreInitLocked, _nv033667rm(gpu, graphics), for Graphics instance 0.
# Physical first-open sequence of the original driver on a V100 (BAR0 offsets),
# lines 37608 to 37712 of the per-GPU register transcript.
transcript = ROOT / "target/trace/b3-bar0.txt"
EMBEDDED = ROOT / "tools/check_gpu_clock_gating_binary.py"
physical_text = re.search(r'PHYSICAL = """(.*?)"""', EMBEDDED.read_text(), re.S)[1].split()
assert len(physical_text) == 104
if transcript.exists():
lines = transcript.read_text().splitlines()
assert [f"{kind.lower()}:{int(offset, 16):x}:{int(value, 16):x}" for kind, offset, value, _time
in (line.split() for line in lines[37608:37712])] == physical_text
# The five reads of the OBJBUS function at +300 (_nv018541rm) precede it.
assert [line.split()[:3] for line in lines[37598:37603]] == [
["R", "120070", "0x100001"], ["R", "120078", "0x6"], ["R", "022430", "0x6"],
["R", "022438", "0x8"], ["R", "022434", "0x7"]]
assert lines[37607].split()[:3] == ["R", "000200", "0x1fecdff1"]
def pre_init(enable=0x1fecdff1, registry=None, word_c=6, valid=1, info=1, done_mask=0,
base=0x400000, parent=(0, 0x1000000, 0), status_1723=0, gpu_921=0, gpu_6d41=0,
lpwr=1, child=1, byte_183=0, byte_184=0, word_160c=0, gr_1596=0):
reset()
objects(info=info, valid=valid, word_c=word_c)
case["registry"] = dict(registry or {})
for offset in WORDS:
d(GPU + offset, 0xdeadbeef)
assert call(bound["GPU+0x2d0"], GPU) & 0xffffffff == 0
words = [word(GPU + offset) for offset in WORDS] + [byte(GPU + 0x6d62)]
trace.clear()
b(GPU + 0x6d41, gpu_6d41)
b(GPU + 0x921, gpu_921)
d(INFO + 0x25c, done_mask)
q(GRMGR + 0x640, 0xffffffffffffffff)
q(GRMGR + 0x648, 0xffffffffffffffff)
q(GPU + 0x22c8, LPWR if lpwr else 0)
q(LPWR + 0x11d8, CHILD if child else 0)
q(LPWR + 0x11c0, HEAP + 0x800)
b(CHILD + 0x183, byte_183)
b(CHILD + 0x184, byte_184)
d(GR + 0x160c, word_160c)
b(GR + 0x1596, gr_1596)
parent_aperture(*parent)
if base:
# State the constructor leaves: Graphics+a50 has run.
assert call(bound["Graphics+0xa50"], GPU, GR) & 0xffffffff == 0
# Graphics+d10 reads PMC enable once for _nv033667rm and once for _nv033505rm.
case.update(reads=[enable, enable], status_1723=status_1723, sanity=0, filter=0, loop=0, tls=0)
status = call("_nv033667rm", GPU, GR) & 0xffffffff
outputs = [f"b640:{pointer(GRMGR + 0x640):x}", f"b650:{pointer(GRMGR + 0x650):x}",
f"gr1608:{word(GR + 0x1608):x}", f"gr160c:{word(GR + 0x160c):x}"]
outputs += [f"rec:{value:x}" for value in record_words()]
outputs += [f"seen:{offset:x}" for offset in range(8) if byte(GPU + 0x6dc4 + offset)]
emit("P", [enable] + words + [word_c, valid, info, done_mask, int(base != 0), *parent,
status_1723, gpu_921, gpu_6d41, lpwr, child, byte_183,
byte_184, word_160c, gr_1596], f"{status:x}", outputs)
return status, list(trace)
status, observed = pre_init()
# First open on the V100 with no registry override: both PMC reads, then every
# write of the transcript as a write of the register mapping at the same offset
# (Graphics tables) or a direct register write (table 0x13b000).
flat = []
for entry in observed:
kind, *fields = entry.split(":")
if kind == "r":
flat.append(entry)
elif kind in ("w", "o"):
flat.append("w:" + ":".join(fields))
assert status == 0
assert flat == ["r:200:1fecdff1"] + physical_text, flat
assert sum(entry.startswith("o:") for entry in observed) == 99
assert sum(entry.startswith("w:") for entry in observed) == 4
first_open_trace = list(observed)
for enable, word_c, valid in itertools.product((0x1fecdff1, 0x1feccff1), (6, 0, 1), (0, 1)):
pre_init(enable=enable, word_c=word_c, valid=valid)
for registry in ({"RMPowerFeature": 1 << 18}, {"RMPowerFeature2": 1 << 6},
{"RMPowerFeature": 2 << 18, "RMBlcg": 0xfffffff1},
{"RMPowerFeature2": 2 << 6, "RMSlcg": 0xfffffffe},
{"RMPowerFeature": 2 << 18, "RMPowerFeature2": 2 << 6},
{"RMPowerFeature": 3 << 18, "RMPowerFeature2": 3 << 6},
{"RMDisableFeatureDisablement": 1}, {"RmWar1760398": 1}):
pre_init(registry=registry)
pre_init(registry=registry, gpu_6d41=1)
for parent in ((0, 0x1000000, 0), (0x1000, 0x1000000, 0), (0x2000, 0x1000000, 0x1000),
(0, 0x100000, 0)):
for gpu_921 in (0, 1):
pre_init(parent=parent, gpu_921=gpu_921)
for done_mask in (1, 2, 0xffffffff):
pre_init(done_mask=done_mask)
# Without the +2b0 record, or without the register object, the original reads
# through a null pointer once Graphics is out of reset; those inputs are run
# with Graphics held in reset only.
pre_init(done_mask=1, info=0, enable=0x1feccff1)
pre_init(base=0, enable=0x1feccff1)
pre_init(status_1723=0x51)
pre_init(status_1723=0x51, base=0)
for byte_183, byte_184 in ((1, 0), (0, 1), (1, 1)):
pre_init(byte_183=byte_183, byte_184=byte_184)
pre_init(child=0)
pre_init(word_160c=0x01000001, enable=0x1feccff1)
pre_init(word_160c=0, enable=0x1feccff1)
out = ROOT / "target/gpu-stage"
out.mkdir(parents=True, exist_ok=True)
table_rows = [f"T;F;{row[0]:x} {row[1]:x} {row[2]:x} {row[3]:x}" for row in FEATURES]
table_rows += [f"T;E;{row[0]:x} {row[2]:x} {row[3]:x} {row[4]:x} {row[5]:x}" for row in ENGINES]
table_rows += ["T;K;" + key for key in KEYS]
oracle = "\n".join(table_rows + rows) + "\n"
(out / "original-clock-gating-providers.txt").write_text(oracle)
report = {
"original_sha256": DIGEST, "chip_hal": "0x23", "rm_hal": 2, "executed": sorted(executed),
"fixture_supplied": list(HOOKED), "bindings": bound, "gv100_properties": properties,
"registry_keys_read_by__nv030843rm": queried_all,
"tables": {"features": f".data+{FEATURES_AT:#x} x {FEATURES_COUNT}",
"engine_features": f".data+{ENGINES_AT:#x} x {ENGINES_COUNT}",
"bytes_sha256": TABLE_DIGEST,
"rust_constants": str(TABLES.relative_to(ROOT)),
"rust_constants_sha256": hashlib.sha256(TABLES.read_bytes()).hexdigest()},
"register_object": {
"class_data": f".rodata+{APERTURE_METADATA[0]:#x}",
"write32": ["_nv003747rm", "_nv037850rm", "_nv037851rm"],
"graphics_base_and_length": ["0x400000", "0x200000"]},
"cases": len(rows), "cases_by_entry": counts, "table_rows": len(table_rows),
"oracle": "target/gpu-stage/original-clock-gating-providers.txt",
"oracle_sha256": hashlib.sha256(oracle.encode()).hexdigest(),
"first_open_trace": first_open_trace,
"physical_sequence_reproduced_from": "tools/check_gpu_clock_gating_binary.py PHYSICAL"
+ (" and target/trace/b3-bar0.txt"
if transcript.exists() else ""),
"scope": "Original providers of the GV100 clock-gating table loads: feature query and "
"record, registry words, Graphics+c78, the Graphics lookup, the register object "
"at Graphics+1758 and its 32-bit write, and Graphics PreInitLocked for instance "
"0 with all of them connected. Register values, registry contents, the "
"thread-local value and the leaves listed are fixture-supplied; no hardware "
"executed."}
(ROOT / "reports/gpu-clock-gating-providers-original.json").write_text(
json.dumps(report, indent=1) + "\n")
print(f"{len(rows)} original clock-gating provider cases {counts}; {len(table_rows)} table rows; "
f"executed {len(executed)} functions")