#!/usr/bin/env python3 """Run the original functions of other objects that the GV100 Graphics InitLocked, StateLoad and StateUnload call, and write an oracle for core gpu::gr_level. Executed original code on the emulator of check_gpu_graphics_load_binary.py: E _nv027871rm, the FIFO engine status query of the idle wait, on the engine table the original KernelFifo constructor builds from the device-info words of the physical V100 (T row: that table); F OBJFUSE+118 _nv029006rm with id 0xff000034 and OBJFUSE+100 _nv029045rm, bound by the OBJFUSE binder _nv005974rm, with the Jtag function _nv039060rm; X the Falcon functions _nv027641rm, GPCCS+80, _nv027643rm and GPCCS+88 on the FECS and GPCCS objects the original Graphics constructor creates; Q the GV100 Pmu functions at +330 and +340, and P: the Lpwr control object _nv021616rm builds, its dwords +e0 and +130 and the answer of _nv042917rm(.., 0, 2); V _nv000194rm, the VBIOS table of Graphics register overrides, on synthetic images and (VP) on the physical V100 image when target/physical/prom-b3.bin exists; W _nv037435rm, the BIT token parser, for the word it stores at OBJVBIOS+438 (WP: the physical image); D _nv059989rm, the expansion offset OBJVBIOS+124c, on image lists; M _nv051499rm, the call StateLoad makes on the GPU+22e8 object (Pmgr). The load harness answers every dynamic cast (_nv005245rm) with its argument. The creators of the Falcon objects cast their parent to a HAL-owner class and read the selector at +10 of the result, so in that harness they bind the Falcon function tables with a word of the Graphics object as selector. Here a cast to either HAL-owner class returns that owner (chip HAL 0x23, RM HAL 2). """ import hashlib import json from pathlib import Path import struct import sys sys.path.insert(0, str(Path(__file__).resolve().parent)) ARGUMENTS = sys.argv[1:] sys.argv = sys.argv[:1] import check_gpu_graphics_load_binary as h # noqa: E402 from unicorn.x86_const import UC_X86_REG_RIP, UC_X86_REG_RSI # noqa: E402 ROOT = h.ROOT GPU, GR = h.GPU, h.GR PMU, PG, VBIOS, JTAG, PMGR = (h.OBJ + 0x10000 * index for index in (24, 27, 28, 29, 30)) CAST = h.by_name["_nv005245rm"] PROM = ROOT / "target/physical/prom-b3.bin" rows = [] original_in_objects, original_leave = h.in_objects, h.leave # Class ids of the two HAL-owner classes (generated/g_gpu_halspec_nvoc.h of the matching # public source; tools/gpu_engine_hal_bindings.py answers their casts the same way). OWNERS = {0x74bc71: h.CHIP, 0x34a6d6: h.RM} def owner_cast(): """The owner object a cast to a HAL-owner class must give, else None.""" if h.cpu.reg_read(UC_X86_REG_RIP) != CAST: return None return OWNERS.get(h.d(h.cpu.reg_read(UC_X86_REG_RSI) + 4)) def in_objects(address): return True if owner_cast() else original_in_objects(address) def leave(value=0): original_leave(owner_cast() or value) h.in_objects, h.leave = in_objects, leave h.hook("os_delay_us", lambda a: h.emit(f"du:{a[0] & 0xffffffff:x}") or 0) def events(kinds="rw"): """Register accesses, delays and assertions of the last call, in order.""" return " ".join(event for event in h.state["events"] if event.split(":")[0] in ("r", "w", "du", "A") and ( event[0] in kinds or event.startswith("du") or event.startswith("A"))) def fresh(reads=None): h.state["events"].clear() h.state["case"]["reads"] = {offset: [value] for offset, value in (reads or {}).items()} def engine_status(random): table, count = h.q(h.KFIFO + 0x348), h.d(h.KFIFO + 0x340) rows.append(f"T;{count:x};" + bytes(h.cpu.mem_read(table, 100 * count)).hex()) descriptors = [h.d(table + 100 * index) for index in range(count)] assert 0xd334df00 in descriptors busy = h.allocate(8) cases = [(0xd334df00, 0, 0, 0)] + [ (random.pick(descriptors + [0xd334df00] * 6 + [0xd334df01, 0, 0x12345600]), random.pick((0, 0x8000, 0x80000000, 0xffffffff, 0xffff7fff, random.word())), random.pick((0, random.word())), random.word() & 1) for unused in range(160)] for descriptor, engine, pbdma, initial in cases: fresh({0x3080 + 4 * index: pbdma ^ index for index in range(64)} | {0x2640 + 8 * index: engine for index in range(64)}) h.wb(busy, initial) status = h.call("_nv027871rm", GPU, h.OFIFO, descriptor, 0, busy, 0, stack=(0,)) rows.append(f"E;{descriptor:x};{initial:x};{status & 0xffffffff:x};{h.b(busy):x};" + events("r")) def fuse(random): h.call("_nv005974rm", h.FUSE, h.CHIP, h.RM) slots = tuple(h.function_at(h.q(h.FUSE + offset)) for offset in (0x100, 0x118, 0x168)) assert slots == ("_nv029045rm", "_nv029006rm", "_nv029047rm"), slots # The Jtag object as its creation _nv006537rm leaves it for chip HAL 0x23 # (reports/gpu-lsfm-mask-validation.json): function +100 and byte +108. h.cpu.mem_write(JTAG, bytes(0x1000)) h.wq(JTAG + 0x100, h.by_name["_nv039060rm"]) h.wq(GPU + 0x1e70, JTAG) assert h.q(h.FUSE + 0x2f0) == 0 and h.b(GPU + 0x4de4) == 0 out = h.allocate(8) offsets = [0xc38 + 4 * index for index in range(6)] + [0xc1c, 0x434, 0x1c38, 0xffc, 0] for number in range(96): guard = 0 if number % 8 == 7 else 1 jtag = random.pick((0xa, 0xa, 0x8, 0x2, 0, 0xffffffff, random.word())) value = random.pick((0, 1, 0x3f, 0xffffffff, random.word())) h.wb(JTAG + 0x108, guard) if number % 3 == 0: fresh({0x1373a0: jtag, 0x21c1c: value}) h.wd(out, 0xcccccccc) status = h.call("_nv029006rm", GPU, h.FUSE, 0xff000034, out) & 0xffffffff rows.append(f"F;q;ff000034;{guard:x};{status:x};{h.d(out):x};{events('r')}") else: offset = random.pick(offsets) fresh({0x1373a0: jtag, 0x21000 + (offset & 0xfff): value}) h.wd(out, 0xcccccccc) h.call("_nv029045rm", GPU, h.FUSE, offset, out, 0) rows.append(f"F;r;{offset:x};{guard:x};0;{h.d(out):x};{events('r')}") def falcons(random): fecs, gpccs = h.q(GR + 0x15e8), h.q(GR + 0x15f0) assert h.function_at(h.q(gpccs + 0x80)) == "_nv029884rm" assert h.function_at(h.q(gpccs + 0x88)) == "_nv029887rm" inner = {name: h.q(outer + 0x58) for name, outer in (("fecs", fecs), ("gpccs", gpccs))} falcon = {name: h.q(address + 0x18) for name, address in inner.items()} state = {} for name in ("fecs", "gpccs"): state[name] = {"F+10": h.b(inner[name] + 0x10), "F+11": h.b(inner[name] + 0x11), "Falcon+3a2": h.b(falcon[name] + 0x3a2), "Falcon+3a5": h.b(falcon[name] + 0x3a5), "Falcon+3a6": h.b(falcon[name] + 0x3a6), "Falcon+3b7": h.b(falcon[name] + 0x3b7), "Falcon+548 before the load": h.d(falcon[name] + 0x548), "Falcon+650": h.d(falcon[name] + 0x650), "Falcon+5ec": f"{h.d(falcon[name] + 0x5ec):#x}", "Falcon+90": h.function_at(h.q(falcon[name] + 0x90))} assert (state[name]["F+10"], state[name]["F+11"], state[name]["Falcon+3a2"], state[name]["Falcon+3b7"], state[name]["Falcon+548 before the load"], state[name]["Falcon+650"]) == (1, 1, 1, 0, 0, 1), state assert h.b(fecs + 0x1f8) == 0 calls = {("L", "fecs"): lambda flags: h.call("_nv027641rm", GPU, fecs), ("L", "gpccs"): lambda flags: h.call(h.q(gpccs + 0x80), GPU, gpccs), ("U", "fecs"): lambda flags: h.call("_nv027643rm", GPU, fecs, flags), ("U", "gpccs"): lambda flags: h.call(h.q(gpccs + 0x88), GPU, gpccs, flags)} words = (0, 1, 2, 3, 4, 7, 0xffffffff, 0xfffffffc) for name in ("fecs", "gpccs"): fresh() status = calls[("L", name)](0) & 0xffffffff rows.append(f"X;L;{name};0;{status:x};{h.d(falcon[name] + 0x548):x};{events()}") for number in range(64): name = ("fecs", "gpccs")[number & 1] base = h.d(falcon[name] + 0x548) word = words[number // 2] if number < 16 else random.word() flags = random.pick((0, 0, 0, 1, 0x20, 0x21, 0xffffffff)) fresh({base + 0x48: word}) status = calls[("U", name)](flags) & 0xffffffff rows.append(f"X;U;{name};{flags:x};{status:x};{base:x};{events()}") # The load functions again after an unload: the same result. for name in ("fecs", "gpccs"): fresh() status = calls[("L", name)](0) & 0xffffffff rows.append(f"X;L;{name};0;{status:x};{h.d(falcon[name] + 0x548):x};{events()}") return state PMU_BYTES = (0x5d6, 0x5de, 0x5e0, 0x5e1, 0x5e2, 0x5e3, 0x5e4, 0x5e5, 0x5e9, 0x5ea, 0x5eb) def build_pmu(slot): """The Pmu object as its binders leave it, then one of the two functions the constructor _nv051986rm calls on it.""" h.cpu.mem_write(PMU, bytes(0x20000)) h.call("_nv006035rm", PMU, h.CHIP, h.RM) h.call("_nv005852rm", PMU, h.RM, h.CHIP) status = h.call(h.q(PMU + slot), GPU, PMU) & 0xffffffff return h.function_at(h.q(PMU + slot)), status def lpwr(): for slot in (0x330, 0x340): name, status = build_pmu(slot) rows.append(f"Q;{slot:x};{name};{status:x};" + " ".join(f"{h.b(PMU + offset):x}" for offset in PMU_BYTES)) # The allocation inside the control object's creation _nv006583rm is the only fixture. h.hook("_nv006583rm", lambda a: h.wq(a[0], PG) or 0) for present, bytes_set, lpwr_228 in ( (1, (), 1), (0, (), 1), (1, (0x5de,), 1), (1, (0x5de, 0x5e4), 1), (1, (0x5de, 0x5e4, 0x5ea), 1), (1, (0x5de, 0x5e4), 0), (1, (0x5e4,), 1), (1, (0x5e4, 0x5ea, 0x5e0, 0x5e1), 1), (0, (0x5de, 0x5e4), 1)): h.prepare(h.default_load()) build_pmu(0x330) h.cpu.mem_write(PG, bytes(0x10000)) h.call("_nv005931rm", PG, h.CHIP, h.RM) h.call("_nv005804rm", PG, h.CHIP, h.RM) h.wq(GPU + 0x22c8, h.LPWR) h.wq(GPU + 0x2120, PMU if present else 0) for offset in (0x11b8, 0x11c0, 0x11c8, 0x11d0, 0x11d8, 0x11e0): h.wq(h.LPWR + offset, 0) for offset in bytes_set: h.wb(PMU + offset, 1) h.wb(h.LPWR + 0x228, lpwr_228) status = h.call("_nv021616rm", GPU, h.LPWR) & 0xffffffff control = h.q(h.LPWR + 0x11c0) assert status == 0 and control == PG, (status, control) # Past the entry instruction, where the load harness has its fixture hook. answer = h.call(h.by_name["_nv042917rm"] + 4, GPU, control, 0, 2) & 0xff rows.append(f"P;{present:x};{int(0x5de in bytes_set):x};" + "/".join(f"{offset:x}" for offset in bytes_set) + f";{lpwr_228:x};" f"{h.d(control + 0xe0):x};{h.d(control + 0x130):x};{answer:x}") return {"Lpwr+228..232": [h.b(h.LPWR + offset) for offset in range(0x228, 0x233)]} def entry_order(): conventions = json.loads((ROOT / "reports/gv100-engine-hal-bindings.json").read_text()) entry = [item for item in conventions["classes"] if item["class_label"] == "Pmgr"][0] assert entry["property_binders"] == ["_nv005851rm"], entry["property_binders"] return entry["argument_conventions"]["_nv005851rm"]["order"] def pmgr(): """_nv051499rm(gpu, GPU+22e8 object) on the object as its property initializer _nv005851rm(object, RM, chip) leaves it; a script call would reach _nv000303rm.""" order = entry_order() assert order == "RM, chip", order reached = [] h.hook("_nv000303rm", lambda a: reached.append(a[1] & 0xffffffff) or 0) for byte_21c0, byte_2c8 in ((0, None), (1, None), (0, 0), (1, 0), (0, 1), (1, 1)): h.cpu.mem_write(PMGR, bytes(0x10000)) h.call("_nv005851rm", PMGR, h.RM, h.CHIP) bound = h.b(PMGR + 0x2c8) if byte_2c8 is not None: h.wb(PMGR + 0x2c8, byte_2c8) h.wb(PMGR + 0x21c0, byte_21c0) h.wd(PMGR + 0x21d0, 0x1234) del reached[:] fresh() status = h.call("_nv051499rm", GPU, PMGR, GR) & 0xffffffff rows.append(f"M;{bound:x};{byte_21c0:x};{h.b(PMGR + 0x2c8):x};{status:x};" f"{len(reached):x};{events()}") IMAGE_CAPACITY = 0x80000 def vbios_object(image, word_438=0, word_124c=0, word_1250=0): """OBJVBIOS as far as _nv000194rm, _nv059988rm, _nv060179rm and _nv000068rm read it.""" h.cpu.mem_write(VBIOS, bytes(0x2000)) h.cpu.mem_write(vbios_object.buffer, bytes(image)) h.wq(VBIOS + 0x2e8, vbios_object.buffer) h.wd(VBIOS + 0x2f0, len(image)) h.wd(VBIOS + 0x438, word_438) h.wd(VBIOS + 0x124c, word_124c) h.wd(VBIOS + 0x1250, word_1250) h.wq(GPU + 0x20c8, VBIOS) def overrides(kind, image, word_438, word_124c, word_1250, text): vbios_object(image, word_438, word_124c, word_1250) out = h.allocate(0x400, 0xcc) h.state["events"].clear() # Past the entry instruction, where the load harness has its fixture hook. status = h.call(h.by_name["_nv000194rm"] + 4, GPU, out) & 0xffffffff version, count = (h.d(out), h.d(out + 4)) if status == 0 else (0, 0) rows.append(f"{kind};{word_438:x};{word_124c:x};{word_1250:x};{len(image):x};{status:x};" f"{version:x};{count:x};{text}") return status, version, count def override_images(random): for number in range(140): size = random.pick((0x100, 0x140, 0x180, 0x200)) image = bytearray(random.word() & 0xff for unused in range(size)) offset = random.pick((0x20, 0x41, 0x80, 0xc3)) version = random.pick((0x20, 0x20, 0x20, 0x21, 0xff, 0x10, 0x1f, 0, 5)) header_size = random.pick((4, 4, 4, 5, 0, 12)) entry_size = random.pick((9, 9, 9, 10, 0)) entries = random.pick((0, 1, 2, 5, 9, 0x10, 0x20, 0x20, 0x21, 0x28)) if version < 0x20: header_size = random.pick((4, 8, 0x30, 0xf0)) image[offset:offset + 4] = bytes((version, header_size, entry_size, entries)) for index in range(entries): at = offset + header_size + entry_size * index if at < size: image[at] = random.pick((0, 0, 1, 7, 0xff)) base = random.pick((0, offset - 1, offset, offset + 1, 0x1000)) delta = random.pick((0, 0x10, 0x40)) pointer = random.pick((offset, offset, offset, 0, offset - delta if base < offset - delta else offset)) if number % 7 == 6: image = image[:random.pick((offset, offset + 1, offset + 4, offset + 13, size - 3))] overrides("V", image, pointer, delta, base, bytes(image).hex()) def image_lists(random): """_nv059989rm(0, vbios): the list at OBJVBIOS+fd0 (offset +0, length +4, code type +c, next +10).""" for number in range(48): images = [(random.word() & 0xfffff, random.word() & 0xfffff, random.pick((0, 0, 3, 0xe0, 0xe0, 0x70, 0xff))) for unused in range(random.pick((0, 1, 2, 3, 4, 6)))] if number == 0: # The six images of the physical V100 (reports/physical-rom-validation.json). images = [(0, 58368, 0), (58368, 71680, 3), (130048, 69120, 0xe0), (199168, 56832, 0xe0), (256000, 4096, 0x70), (260096, 66048, 0x70)] h.cpu.mem_write(VBIOS, bytes(0x2000)) nodes = [h.allocate(0x18) for unused in images] for index, (node, (offset, length, code)) in enumerate(zip(nodes, images)): h.wd(node, offset) h.wd(node + 4, length) h.wb(node + 0xc, code) h.wq(node + 0x10, nodes[index + 1] if index + 1 < len(nodes) else 0) h.wq(VBIOS + 0xfd0, nodes[0] if nodes else 0) result = h.call("_nv059989rm", 0, VBIOS) & 0xffffffff rows.append(f"D;{result:x};" + ",".join(f"{offset:x}:{length:x}:{code:x}" for offset, length, code in images)) def bit_parser(image, bit): vbios_object(image) h.state["events"].clear() status = h.call("_nv037435rm", GPU, VBIOS, bit) & 0xffffffff return status, h.d(VBIOS + 0x438) def bit_images(random): for number in range(120): size = 0x800 image = bytearray(random.word() & 0xff for unused in range(size)) bit = random.pick((0x10, 0x33)) tokens = random.pick((1, 1, 2, 3)) token_size = random.pick((6, 6, 6, 7)) header_size = random.pick((12, 12, 13)) image[bit:bit + 12] = struct.pack(" base else word return {"sha256": digest, "bit_offset": f"{bit:#x}", "parser_status": f"{status:#x}", "OBJVBIOS+438": f"{word:#x}", "OBJVBIOS+124c": f"{delta:#x}", "OBJVBIOS+1250": f"{base:#x}", "table_offset": f"{table:#x}", "table_header": image[table:table + 4].hex(), "entries": [image[table + 4 + 9 * index:table + 13 + 9 * index].hex() for index in range(image[table + 3])], "_nv000194rm": {"status": f"{result[0]:#x}", "version": f"{result[1]:#x}", "count": result[2]}} def main(): random = h.Random(0x27871) h.prepare(h.default_load()) h.state["real"] = True engine_status(random) falcon_state = falcons(random) fuse(random) lpwr_state = lpwr() pmgr() h.prepare(h.default_load()) h.state["real"] = True vbios_object.buffer = h.allocate(IMAGE_CAPACITY) override_images(random) bit_images(random) image_lists(random) board = physical() out = ROOT / "target/gpu-stage" oracle = "\n".join(rows) + "\n" (out / "original-graphics-level.txt").write_text(oracle) kinds = {} for row in rows: kinds[row.split(";", 1)[0]] = kinds.get(row.split(";", 1)[0], 0) + 1 report = { "original_sha256": h.DIGEST, "chip_hal": "0x23", "rm_hal": 2, "kinds": {"T": "the engine table of the physical V100 (KernelFifo+348, 100-byte records)", "E": "_nv027871rm(gpu, OBJFIFO, descriptor, 0, &busy, 0) with stack word 0", "F": "_nv029006rm (q) with id 0xff000034 and _nv029045rm (r)", "X": "_nv027641rm / GPCCS+80 (L) and _nv027643rm / GPCCS+88 (U)", "Q": "the GV100 Pmu functions at +330 and +340 and the Pmu bytes after them", "P": "_nv021616rm and _nv042917rm(.., 0, 2)", "V": "_nv000194rm on synthetic images", "VP": "_nv000194rm on the V100 image", "W": "_nv037435rm on synthetic images", "WP": "_nv037435rm on the V100 image", "D": "_nv059989rm on image lists (the first is the V100's)", "M": "_nv051499rm on the GPU+22e8 object (byte +2c8 as bound, +21c0, +2c8 " "used, status, calls of _nv000303rm)"}, "falcon_objects_before_the_load": falcon_state, "lpwr": lpwr_state, "physical_v100_image": board, "fixture_supplied": ["register values", "os_delay_us", "the HAL-owner cast of " "_nv005245rm to the two HAL-owner classes", "the allocation of " "_nv006583rm", "OBJVBIOS fields +2e8, +2f0, +438, +124c, +1250 " "(V rows) and +2e8, +2f0 (W rows)", "the Jtag object's function " "+100 and byte +108", "everything the load harness supplies"], "cases": len(rows), "cases_by_kind": kinds, "oracle": "target/gpu-stage/original-graphics-level.txt", "oracle_sha256": hashlib.sha256(oracle.encode()).hexdigest(), "scope": "Original functions of other objects that Graphics InitLocked, StateLoad and " "StateUnload call on a GV100. No hardware executed."} (ROOT / "reports/gpu-graphics-level-original.json").write_text( json.dumps(report, indent=1) + "\n") print(f"{len(rows)} original rows {kinds}") print(report["oracle_sha256"]) if __name__ == "__main__": main()