#!/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("> 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")