Files
nvdriver/tools/oracle_gsp_rm.py

809 lines
33 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""Standalone x86_64 Unicorn Binary Oracle for Pillar 1: Turing–Blackwell GSP-RM
Full Runtime & RPC Protocol (TU102, GA100, GA102, AD102, GH100, GB100, GB202, GB20B).
Executes the REAL NVIDIA 580.178.04 `nv-kernel.o_binary` x86_64 functions in Unicorn
and compares exact RPC payload bytes, `GSP_MSG_QUEUE_ELEMENT` checksums & fragmentation
(`CONTINUATION_RECORD`), queue pointer transitions, RISC-V/BCR/WPR2/FRTS MMIO bootstrap
traces, WPR2 metadata, and `LIBOS_LOG` ring decoding against our Rust implementation
with 0 diffs.
Exports `run_checks()` returning a list of `{"name": ..., "passed": bool, "diffs": [...]}` dicts.
"""
from __future__ import annotations
import json
import struct
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tools"))
from rmapi_binary_emulator import Emulator # noqa: E402
def _xor_checksum(data: bytes) -> int:
"""Exact 64-bit folded XOR checksum matching `gsp_rpc::message_checksum` and `_nv000343rm`."""
pad = (8 - (len(data) & 7)) & 7
padded = data + b"\x00" * pad
acc = 0
for i in range(0, len(padded), 8):
acc ^= struct.unpack_from("<Q", padded, i)[0]
return ((acc & 0xFFFFFFFF) ^ ((acc >> 32) & 0xFFFFFFFF)) & 0xFFFFFFFF
def _rust_rpc_header(func: int, payload_len: int, seq: int = 0, gfid: int = 0,
res: int = 0xFFFFFFFF, res_priv: int = 0xFFFFFFFF) -> bytes:
return struct.pack("<8I", 0x03000000, 0x43505256, payload_len + 0x20, func, res, res_priv, seq, gfid)
def _rust_pack_message(seq_num: int, rpc_hdr: bytes, payload: bytes) -> tuple[bytes, int]:
total = 0x30 + len(rpc_hdr) + len(payload)
elem_count = (total + 0xFFF) // 0x1000
buf = bytearray(max(total, elem_count * 0x1000))
struct.pack_into("<II", buf, 0x24, seq_num, elem_count)
buf[0x30:0x30 + len(rpc_hdr)] = rpc_hdr
buf[0x30 + len(rpc_hdr):total] = payload
csum = _xor_checksum(bytes(buf[:total]))
struct.pack_into("<I", buf, 0x20, csum)
return bytes(buf[:total]), elem_count
def _make_callback(emu: Emulator, handler) -> int:
"""Allocate a synthetic executable callback address in Unicorn and bind `handler`."""
addr = emu.allocate(16, fill=0x90)
emu.wb(addr, 0xC3) # ret
emu.install(addr, handler)
return addr
def _install_common_stubs(emu: Emulator) -> None:
"""Install minimal OS/logging/memory/lock stubs for `nv-kernel.o_binary` execution."""
emu.install("_nv047869rm", lambda _a: 0)
emu.install("_nv047868rm", lambda _a: 0)
emu.install("_nv047867rm", lambda _a: 0)
emu.install("_nv046745rm", lambda _a: 0)
emu.install("_nv046747rm", lambda _a: 0)
emu.install("_nv046751rm", lambda _a: 0)
emu.install("_nv046752rm", lambda _a: 0)
emu.install("_nv054098rm", lambda _a: 1)
emu.install("_nv054105rm", lambda _a: 1)
emu.install("_nv054248rm", lambda _a: 1)
emu.install("_nv030875rm", lambda _a: 0) # CC disabled
emu.install("_nv031390rm", lambda _a: 0) # GPU not lost
emu.install("_nv049819rm", lambda _a: 0) # osSpinLoop
emu.install("_nv059509rm", lambda _a: 0) # gpuSetTimeout
emu.install("_nv059505rm", lambda _a: 0) # gpuCheckTimeout
emu.install("_nv059492rm", lambda _a: 0) # gpuResetTimeout
emu.install("_nv052705rm", lambda a: (emu.write(a[0], bytes([a[1] & 0xFF]) * a[2]), a[0])[1])
emu.install("_nv052695rm", lambda a: (emu.write(a[0], emu.read(a[2], a[3])), a[0])[1])
emu.install("_nv052687rm", lambda a: emu.allocate(max(a[0], 16)))
emu.install("_nv052701rm", lambda _a: 0)
emu.install("_nv052715rm", lambda a: len(emu.text(a[0], 4096)))
def check_gsp_msgq_send_recv_checksum_ring_unicorn() -> dict:
"""Execute real 580.178.04 `_nv000343rm` (GspMsgQueueSendCommand), `_nv000342rm`
(GspMsgQueueReceiveStatusMessage), and real `_nv046462rm/_nv046463rm/_nv046464rm` +
`_nv046457rm/_nv046458rm/_nv046460rm` ring buffer helpers in Unicorn across single-page
and multi-page wrap-around frames."""
emu = Emulator()
_install_common_stubs(emu)
diffs = []
RING_PAGES = 8
PAGE = 0x1000
tx_ring = emu.allocate(RING_PAGES * PAGE)
rx_ring = emu.allocate(RING_PAGES * PAGE)
tx_head_mem = emu.allocate(8) # writePtr shared slot
tx_tail_mem = emu.allocate(8) # readPtr shared slot
rx_head_mem = emu.allocate(8) # writePtr shared slot
rx_tail_mem = emu.allocate(8) # readPtr shared slot
msgq = emu.allocate(0x100)
# Initialize msgq struct matching _nv046462rm / _nv046463rm / _nv046464rm / _nv046457rm / _nv046458rm / _nv046460rm
emu.wq(msgq + 0x20, tx_ring)
emu.wq(msgq + 0x28, rx_ring)
emu.wq(msgq + 0x30, tx_tail_mem) # TX readPtr*
emu.wq(msgq + 0x38, rx_head_mem) # RX writePtr*
emu.wq(msgq + 0x40, rx_tail_mem) # RX readPtr*
emu.wq(msgq + 0x48, tx_head_mem) # TX writePtr*
emu.wd(msgq + 0x58, PAGE) # TX elem size
emu.wd(msgq + 0x5c, RING_PAGES) # TX queue size
emu.wd(msgq + 0x60, 0) # TX writePtr
emu.wd(msgq + 0x70, 0) # TX readPtr
emu.wd(msgq + 0x74, RING_PAGES - 1)
emu.wb(msgq + 0x78, 1) # TX initialized
emu.wd(msgq + 0x84, PAGE) # RX elem size
emu.wd(msgq + 0x88, RING_PAGES) # RX queue size
emu.wd(msgq + 0x8c, 0) # RX writePtr
emu.wd(msgq + 0x9c, 0) # RX readPtr
emu.wd(msgq + 0xa0, 0) # RX ready count
emu.wb(msgq + 0xa4, 1) # RX initialized
work_buf = emu.allocate(0x10000)
cmdq = emu.allocate(0x80)
emu.wq(cmdq + 0x30, work_buf)
emu.wq(cmdq + 0x40, msgq)
emu.wd(cmdq + 0x48, 0) # txSeqNum
emu.wd(cmdq + 0x4c, 0) # rxSeqNum
gpu = emu.allocate(0x2800)
# Test 1: Single-page (128B payload) + Multi-page (3-page, 9000B payload) + wrap-around (5+3 -> wraps mod 8)
for seq_idx, (func_id, payload_len) in enumerate([(0x48, 0x80), (0x49, 9000), (0x4c, 0x1200)]):
payload = bytes(((i * 29 + seq_idx * 7) & 0xFF) for i in range(payload_len))
rpc_hdr = _rust_rpc_header(func_id, payload_len, seq=seq_idx)
emu.write(work_buf, b"\x00" * 0x30 + rpc_hdr + payload)
# Advance tx_tail so ring has space before wrap test
if seq_idx == 2:
emu.wd(tx_tail_mem, 4)
rc = emu.call("_nv000343rm", cmdq, gpu) & 0xFFFFFFFF
exp_frame, exp_elems = _rust_pack_message(seq_idx, rpc_hdr, payload)
orig_frame = emu.read(work_buf, len(exp_frame))
if rc != 0 or orig_frame != exp_frame:
diffs.append({
"case": f"send_seq_{seq_idx}_len_{payload_len}",
"rc": hex(rc),
"orig_hdr": orig_frame[:0x50].hex(),
"rust_hdr": exp_frame[:0x50].hex(),
})
# Verify TX writePtr wrapped cleanly: 1 + 3 + 2 = 6 mod 8
got_tx_head = emu.d(tx_head_mem)
if got_tx_head != 6:
diffs.append({"case": "tx_writePtr_after_3_msgs", "orig": got_tx_head, "rust": 6})
# Test 2: Oversized RPC (> 0xffd0) rejected with 0x3a
emu.write(work_buf, b"\x00" * 0x30 + _rust_rpc_header(0x4c, 0xFFD0))
rc_big = emu.call("_nv000343rm", cmdq, gpu) & 0xFFFFFFFF
if rc_big != 0x3A:
diffs.append({"case": "send_oversized_rpc", "orig_rc": hex(rc_big), "rust_rc": "0x3a"})
# Test 3: RX multi-page receive via real _nv000342rm across wrap-around (pages 6, 7, 0)
emu.wd(msgq + 0x9c, 6) # rx readPtr = 6
emu.wd(rx_tail_mem, 6)
emu.wd(rx_head_mem, 1) # rx writePtr = 1 => 3 pages pending (6, 7, 0)
emu.wd(msgq + 0xa0, 0)
rx_payload = bytes(((i * 17 + 3) & 0xFF) for i in range(8500))
rx_rpc = _rust_rpc_header(0x1002, len(rx_payload), seq=0, res=0, res_priv=0)
rx_frame, rx_elems = _rust_pack_message(0, rx_rpc, rx_payload)
if rx_elems != 3:
raise AssertionError(f"expected 3 RX message elements, got {rx_elems}")
padded_rx = rx_frame + b"\x00" * (rx_elems * PAGE - len(rx_frame))
for p_i in range(rx_elems):
ring_p = (6 + p_i) % RING_PAGES
emu.write(rx_ring + ring_p * PAGE, padded_rx[p_i * PAGE:(p_i + 1) * PAGE])
emu.write(work_buf, b"\x00" * (rx_elems * PAGE))
rc_rx = emu.call("_nv000342rm", cmdq, gpu, 0) & 0xFFFFFFFF
got_rx = emu.read(work_buf, len(rx_frame))
got_rx_tail = emu.d(rx_tail_mem)
if rc_rx != 0 or got_rx != rx_frame or got_rx_tail != 1:
diffs.append({
"case": "rx_multipage_wrap",
"rc": hex(rc_rx),
"tail": got_rx_tail,
"expected_tail": 1,
"bytes_match": got_rx == rx_frame,
})
# Test 4: RX corrupted checksum rejected with 0x25 (NV_ERR_INVALID_DATA)
emu.wd(msgq + 0x9c, 1)
emu.wd(rx_tail_mem, 1)
emu.wd(rx_head_mem, 2)
emu.wd(msgq + 0xa0, 0)
bad_rpc = _rust_rpc_header(0x1001, 0, seq=1, res=0, res_priv=0)
bad_frame, _ = _rust_pack_message(1, bad_rpc, b"")
bad_arr = bytearray(bad_frame + b"\x00" * (PAGE - len(bad_frame)))
bad_arr[0x00] ^= 0x01 # corrupt byte 0 (+0x00 authTagBuffer)
emu.write(rx_ring + 1 * PAGE, bytes(bad_arr))
rc_bad = emu.call("_nv000342rm", cmdq, gpu, 0) & 0xFFFFFFFF
if rc_bad != 0x25:
diffs.append({"case": "rx_bad_checksum", "orig_rc": hex(rc_bad), "rust_rc": "0x25"})
return {
"name": "gsp_msgq_send_recv_checksum_ring_unicorn",
"passed": len(diffs) == 0,
"cases": 6,
"diffs": diffs,
}
def check_gsp_continuation_record_split_reassemble_unicorn() -> dict:
"""Execute real 580.178.04 `_nv013893rm` (rpcSendMessageSplit) in Unicorn and verify
multi-page `CONTINUATION_RECORD` (0x47) fragmentation and reply reassembly byte-for-byte."""
emu = Emulator()
_install_common_stubs(emu)
diffs = []
MAX_RPC = 0x100 # 256B per RPC packet => 0xE0 payload bytes per packet
TOTAL_RPC = 0x280 # 0x20 header + 0x260 payload => 3 packets (0xE0 + 0xE0 + 0xA0)
payload = bytes(((i * 31 + 5) & 0xFF) for i in range(TOTAL_RPC - 0x20))
orig_msg = _rust_rpc_header(0x49, len(payload), seq=0) + payload
gpu = emu.allocate(0x2000)
rpc = emu.allocate(0x3000)
msg_buf = emu.allocate(MAX_RPC)
full_buf = emu.allocate(TOTAL_RPC)
emu.write(msg_buf, orig_msg[:0x20])
emu.write(full_buf, orig_msg)
emu.wq(rpc + 0x6a8, msg_buf)
emu.wd(rpc + 0x6c0, MAX_RPC)
emu.wd(rpc + 0x2ef4, 10) # starting sequence = 10
sent_packets: list[tuple[int, int, int, bytes]] = []
def fake_send(args):
# (pGpu, pRpc, *out_seq)
seq = emu.d(rpc + 0x2ef4)
emu.wd(rpc + 0x2ef4, seq + 1)
if args[2]:
emu.wd(args[2], seq)
hdr = emu.read(msg_buf, 0x20)
length, func_id = struct.unpack_from("<II", hdr, 8)
body = emu.read(msg_buf + 0x20, length - 0x20)
sent_packets.append((func_id, seq, length, body))
return 0
reply_payload = bytes(((b ^ 0xA5) & 0xFF) for b in payload)
# Build reply chunks matching ContinuationSplitter: 0xE0, 0xE0, 0xA0
reply_chunks = [
(0x49, 10, reply_payload[0:0xE0]),
(0x47, 11, reply_payload[0xE0:0x1C0]),
(0x47, 12, reply_payload[0x1C0:0x260]),
]
recv_calls: list[tuple[int, int]] = []
def fake_recv(args):
# (pGpu, pRpc, expected_func, expected_seq)
exp_func, exp_seq = args[2] & 0xFFFFFFFF, args[3] & 0xFFFFFFFF
recv_calls.append((exp_func, exp_seq))
idx = len(recv_calls) - 1
f, s, chunk = reply_chunks[idx]
if f != exp_func or s != exp_seq:
raise AssertionError(f"recv mismatch {(f, s)} vs {(exp_func, exp_seq)}")
hdr = _rust_rpc_header(f, len(chunk), seq=s, res=0, res_priv=0)
emu.write(msg_buf, hdr + chunk)
return 0
send_stub = _make_callback(emu, fake_send)
recv_stub = _make_callback(emu, fake_recv)
emu.wq(rpc + 0x18, send_stub)
emu.wq(rpc + 0x20, recv_stub)
# Call _nv013893rm(pGpu, pRpc, total_len, full_buf, flags=1 [copy reply], wait_reply=1)
rc = emu.call("_nv013893rm", gpu, rpc, TOTAL_RPC, full_buf, 1, 1) & 0xFFFFFFFF
if rc != 0:
diffs.append({"case": "rpcSendMessageSplit_rc", "orig": hex(rc), "rust": "0x0"})
# Compare sent packets against Rust ContinuationSplitter model
exp_sent = [
(0x49, 10, 0x100, payload[0:0xE0]),
(0x47, 11, 0x100, payload[0xE0:0x1C0]),
(0x47, 12, 0xC0, payload[0x1C0:0x260]),
]
if sent_packets != exp_sent:
diffs.append({
"case": "continuation_sent_packets",
"orig": [(f, s, l, len(b)) for f, s, l, b in sent_packets],
"rust": [(f, s, l, len(b)) for f, s, l, b in exp_sent],
})
# Verify reassembled reply payload in full_buf[0x20..TOTAL_RPC]
got_reply = emu.read(full_buf + 0x20, len(reply_payload))
if got_reply != reply_payload:
diffs.append({"case": "continuation_reassembled_reply", "mismatch": True})
return {
"name": "gsp_continuation_record_split_reassemble_unicorn",
"passed": len(diffs) == 0,
"packets": len(sent_packets),
"diffs": diffs,
}
def check_gsp_rpc_payload_codecs_unicorn() -> dict:
"""Execute real 580.178.04 RPC marshalers in Unicorn:
- `_nv054434rm` (`ALLOC_ROOT` 0x02)
- `_nv054409rm` + `_nv013889rm` (`ALLOC_MEMORY` 0x04 + PTE desc)
- `_nv054844rm` (`MAP_MEMORY_DMA` 0x0e)
- `_nv054923rm` & `_nv054924rm` (`UNLOADING_GUEST_DRIVER` 0x2f v0 & v1)
- `_nv054780rm` (`GSP_SET_SYSTEM_INFO` 0x48)
- `_nv000813rm` + `_nv053902rm` (`SET_REGISTRY` 0x49 `PACKED_REGISTRY_TABLE`)
and verify exact payload wire bytes with 0 diffs."""
emu = Emulator()
_install_common_stubs(emu)
diffs = []
gpu = emu.allocate(0x6000)
rpc = emu.allocate(0x3000)
msg_buf = emu.allocate(0x2000)
emu.wq(rpc + 0x6a8, msg_buf)
emu.wd(rpc + 0x6c0, 0x2000)
emu.wb(gpu + 0xe01, 1) # IS_GSP_CLIENT = true
emu.wq(gpu + 0x1e60, emu.allocate(0x100))
captured: dict[int, bytes] = {}
def capture_rpc(_args):
hdr = emu.read(msg_buf, 0x20)
length, fid = struct.unpack_from("<II", hdr, 8)
captured[fid] = emu.read(msg_buf + 0x20, length - 0x20)
return 0
emu.install("_nv013890rm", capture_rpc)
emu.install("_nv013892rm", capture_rpc)
# 1. ALLOC_ROOT (0x02, _nv054434rm): 0x6c bytes
client_obj = emu.allocate(0x200)
emu.wd(client_obj + 0x118, 4242) # processID
tls_obj = emu.allocate(0x100)
emu.wd(tls_obj + 0x28, 1) # user-mode thread (< 2)
emu.install("_nv056384rm", lambda _a: client_obj)
emu.install("_nv054073rm", lambda _a: tls_obj)
emu.install("_nv049644rm", lambda _a: 4242)
emu.install("_nv049646rm", lambda a: (emu.write(a[0], b"cuda-test\x00"), 0)[1])
rc = emu.call("_nv054434rm", gpu, rpc, 0xC1D00001) & 0xFFFFFFFF
exp_root = struct.pack("<II", 0xC1D00001, 4242) + b"cuda-test" + b"\x00" * (100 - 9)
if rc != 0 or captured.get(0x02) != exp_root:
diffs.append({"func": "ALLOC_ROOT", "rc": hex(rc), "match": captured.get(0x02) == exp_root})
# 2. ALLOC_MEMORY (0x04, _nv054409rm + _nv013889rm): 0x38 + 2*8 PFNs
memdesc = emu.allocate(0x100)
emu.wq(memdesc + 0x00, gpu)
emu.wq(memdesc + 0x18, 2) # pageCount
emu.wq(memdesc + 0x30, 0x2000) # length
emu.wd(memdesc + 0x68, 0) # pteAdjust
pte_arr = emu.allocate(16)
emu.wq(pte_arr + 0, 0x0000000123456000)
emu.wq(pte_arr + 8, 0x0000000123457000)
emu.install("_nv043728rm", lambda _a: 0) # format
emu.install("_nv043726rm", lambda _a: 2) # page_count
emu.install("_nv043725rm", lambda _a: pte_arr) # page_addrs
captured_split: list[bytes] = []
emu.install("_nv013893rm", lambda a: (captured_split.append(emu.read(a[3], a[2])), 0)[1])
rc = emu.call("_nv054409rm", gpu, rpc, 0xC1D00001, 0x00010001, 0x00020001, 0x003E,
stack=(0x100, memdesc)) & 0xFFFFFFFF
exp_amem = (
struct.pack("<IIIIIII", 0xC1D00001, 0x00010001, 0x00020001, 0x003E, 0x100, 0, 0)
+ struct.pack("<I", 0)
+ struct.pack("<Q", 0x2000)
+ struct.pack("<II", 2, 0)
+ struct.pack("<BBHI", 0, 0, 2, 0)
+ struct.pack("<QQ", 0x123456, 0x123457)
)
got_amem = captured_split[0][0x20:] if captured_split else b""
if rc != 0 or got_amem != exp_amem:
diffs.append({"func": "ALLOC_MEMORY", "rc": hex(rc), "orig": got_amem.hex(), "rust": exp_amem.hex()})
# 3. MAP_MEMORY_DMA (0x0e, _nv054844rm): 0x38 bytes
dma_off_ptr = emu.allocate(8)
emu.wq(dma_off_ptr, 0x00007F0000000000)
emu.call("_nv054844rm", gpu, rpc, 0xC1D00001, 0x00010001, 0x00030001, 0x00020001,
stack=(0x1000, 0x20000, 0x3, dma_off_ptr))
exp_mdma = struct.pack("<IIIIQQIIQQ", 0xC1D00001, 0x00010001, 0x00030001, 0x00020001,
0x1000, 0x20000, 0x3, 0, 0x00007F0000000000, 0)
if captured.get(0x0E) != exp_mdma:
diffs.append({"func": "MAP_MEMORY_DMA", "orig": captured.get(0x0E, b"").hex(), "rust": exp_mdma.hex()})
# 4. UNLOADING_GUEST_DRIVER (0x2f): v0 (_nv054923rm, 0B) and v1 (_nv054924rm, 8B)
emu.call("_nv054923rm", gpu, rpc)
if captured.get(0x2F) != b"":
diffs.append({"func": "UNLOADING_GUEST_DRIVER_v0", "orig": captured.get(0x2F, b"").hex()})
rc_u1 = emu.call("_nv054924rm", gpu, rpc, 1, 0, 3) & 0xFFFFFFFF
exp_u1 = struct.pack("<BBHI", 1, 0, 0, 3)
if rc_u1 != 0 or captured.get(0x2F) != exp_u1:
diffs.append({"func": "UNLOADING_GUEST_DRIVER_v1", "rc": hex(rc_u1), "orig": captured.get(0x2F, b"").hex(), "rust": exp_u1.hex()})
# 5. GSP_SET_SYSTEM_INFO (0x48, _nv054780rm): 0x3a8 bytes
sys_obj = emu.allocate(0x300)
emu.wq(emu.by_name["_nv029075rm"], sys_obj)
kgsp_obj = emu.allocate(0x60000)
bif_obj = emu.allocate(0x2500)
os_obj = emu.allocate(0x1000)
tmr_obj = emu.allocate(0x2600)
chip_obj = emu.allocate(0x300)
emu.wq(gpu + 0x1fa0, kgsp_obj)
emu.wq(gpu + 0x1e90, bif_obj)
emu.wq(gpu + 0x1ed0, os_obj)
emu.wq(gpu + 0x1f60, tmr_obj)
emu.wq(gpu + 0x1ec8, chip_obj)
emu.wq(gpu + 0xd40, 0xFB000000) # gpu_phys_addr
emu.wq(gpu + 0xd48, 0x10000000000) # gpu_phys_fb_addr
emu.wd(gpu + 0xcec, 0x268410DE) # pci_vendor_device_id
emu.wd(gpu + 0xd7c, 1) # is_passthru
emu.write(gpu + 0xce2, struct.pack("<H", 1)) # pci_domain
emu.wq(tmr_obj + 0x2528, 1000000000) # gsp_log_timestamp_freq
max_va_cb = _make_callback(emu, lambda a: (emu.wd(a[2], 0xFFFF0000), emu.wd(a[3], 0x00007FFF), 0)[2])
emu.wq(bif_obj + 0x228, max_va_cb)
emu.install("_nv049661rm", lambda _a: 1000)
emu.install("_nv049672rm", lambda _a: 999999)
emu.install("_nv036616rm", lambda _a: 0x42)
emu.install("_nv049658rm", lambda _a: 0)
emu.install("os_is_grid_supported", lambda _a: 0)
rc_si = emu.call("_nv054780rm", gpu, rpc) & 0xFFFFFFFF
got_si = captured.get(0x48, b"")
if rc_si != 0 or len(got_si) != 0x3A8:
diffs.append({"func": "GSP_SET_SYSTEM_INFO_len", "rc": hex(rc_si), "len": len(got_si)})
else:
checks = [
(0x00, 8, 0xFB000000),
(0x08, 8, 0x10000000000),
(0x50, 4, 0xFFFF0000),
(0x54, 4, 0x00007FFF),
(0x58, 4, 0x268410DE),
(0x68, 1, 1),
(0x344, 4, 0x42),
(0x348, 2, 1),
(0x350, 8, 1000000000),
(0x398, 8, 999999),
]
for off, sz, exp in checks:
fmt = {1: "<B", 2: "<H", 4: "<I", 8: "<Q"}[sz]
got = struct.unpack_from(fmt, got_si, off)[0]
if got != exp:
diffs.append({"func": "GSP_SET_SYSTEM_INFO", "off": hex(off), "orig": hex(got), "rust": hex(exp)})
# 6. SET_REGISTRY (0x49, _nv000813rm + _nv053902rm): PACKED_REGISTRY_TABLE
# Build 2 linked registry nodes: EnableGpuFirmware=DWORD(1), RmMsg=STRING("all\0")
name1 = emu.allocate(32)
emu.write(name1, b"EnableGpuFirmware\x00")
name2 = emu.allocate(16)
emu.write(name2, b"RmMsg\x00")
val2 = emu.allocate(16)
emu.write(val2, b"all\x00")
node2 = emu.allocate(0x30)
emu.wq(node2 + 0x00, name2)
emu.wd(node2 + 0x08, 3) # STRING
emu.wq(node2 + 0x10, val2)
emu.wq(node2 + 0x18, 4) # len=4
emu.wq(node2 + 0x20, 0) # next=NULL
node1 = emu.allocate(0x30)
emu.wq(node1 + 0x00, name1)
emu.wd(node1 + 0x08, 1) # DWORD
emu.wd(node1 + 0x0c, 1) # val=1
emu.wq(node1 + 0x18, 0) # extra data len=0 for DWORD
emu.wq(node1 + 0x20, node2)
reg_wrap = emu.allocate(0x200)
reg_root = emu.allocate(0x10)
emu.wq(reg_wrap + 0x1e8, node1)
emu.wq(reg_root, reg_wrap)
out_reg = emu.allocate(0x200)
out_sz = emu.allocate(8)
emu.wd(out_sz, 0x200)
rc_reg = emu.call("_nv000813rm", reg_root, out_reg, out_sz) & 0xFFFFFFFF
packed_sz = emu.d(out_sz)
got_reg = emu.read(out_reg, packed_sz)
# Build exact Rust `encode_packed_registry` bytes:
# header (8B) + 2*16B entries (32B) = 40B; name1 @ 40 (18B), name2 @ 58 (6B), val2 @ 64 (4B) => total 68B
exp_reg = (
struct.pack("<II", 68, 2)
+ struct.pack("<IB3xII", 40, 1, 1, 4)
+ struct.pack("<IB3xII", 58, 3, 64, 4)
+ b"EnableGpuFirmware\x00"
+ b"RmMsg\x00"
+ b"all\x00"
)
if rc_reg != 0 or got_reg != exp_reg:
diffs.append({"func": "SET_REGISTRY", "rc": hex(rc_reg), "orig": got_reg.hex(), "rust": exp_reg.hex()})
return {
"name": "gsp_rpc_payload_codecs_unicorn",
"passed": len(diffs) == 0,
"codecs": 7,
"diffs": diffs,
}
def check_gsp_riscv_bootstrap_mmio_unicorn() -> dict:
"""Execute real 580.178.04 RISC-V/BCR/WPR2/FRTS bootstrap & init-wait functions in Unicorn:
- `_nv041407rm` (TU102/GA100/GA102/AD102 MAILBOX0/1)
- `_nv041420rm` (GSP Falcon reset `0x1103c0`)
- `_nv041253rm` (FRTS/WPR2 register verification `0x1438/0x1fa824/0x1fa828`)
- `_nv041222rm` (GH100/GB100/GB202 BCR `0x111670..0x111684`, `0x11166c`, `0x111388`)
- `_nv013979rm` (GH100/GB100/GB202 BCR boot poll `MAILBOX0/1/HWCFG2`)
- `_nv041450rm` (`kgspWaitForRmInitDone` waiting for `0x1001` `GSP_INIT_DONE`)
and verify exact MMIO register traces with 0 diffs."""
emu = Emulator()
_install_common_stubs(emu)
diffs = []
mmio_regs: dict[int, int] = {}
mmio_writes: list[tuple[int, int]] = []
def reg_rd(args):
return mmio_regs.get(args[3] & 0xFFFFFFFF, 0)
def reg_wr(args):
off, val = args[3] & 0xFFFFFFFF, args[4] & 0xFFFFFFFF
mmio_regs[off] = val
mmio_writes.append((off, val))
return 0
emu.install("_nv053907rm", reg_rd)
emu.install("_nv053912rm", reg_wr)
gpu = emu.allocate(0x6000)
kgsp = emu.allocate(0x60000)
# 1. _nv041407rm (TU102/GA100/GA102/AD102 MAILBOX0/1)
emu.wq(kgsp + 0xa48, 0x1000)
phys_addr_map = {0x1000: 0x0000000123456000, 0xA30: 0x0000000123456000, 0xA80: 0x0000000200000000}
emu.install("_nv043721rm", lambda a: phys_addr_map.get(a[0], 0x0000000200000000))
mmio_writes.clear()
emu.call("_nv041407rm", gpu, kgsp)
if mmio_writes != [(0x110040, 0x23456000), (0x110044, 0x00000001)]:
diffs.append({"func": "_nv041407rm", "orig": mmio_writes})
# 2. _nv041420rm (GSP Falcon engine reset 0x1103c0 bit 0)
mmio_writes.clear()
mmio_regs[0x1103C0] = 0x10
emu.call("_nv041420rm", gpu)
if mmio_writes != [(0x1103C0, 0x11), (0x1103C0, 0x10)]:
diffs.append({"func": "_nv041420rm", "orig": mmio_writes})
# 3. _nv041253rm (FRTS / WPR2 verification on TU10x/GA10x/AD10x)
emu.wb(gpu + 0xe01, 1)
kflcn = emu.allocate(0x700)
emu.wq(kgsp + 0x770, kflcn)
exec_stub = _make_callback(emu, lambda _a: 0)
emu.wq(kgsp + 0x8c8, exec_stub)
fwsec_desc = emu.allocate(0x30)
emu.wd(fwsec_desc + 0x08, 0x15) # FRTS cmd
emu.wq(fwsec_desc + 0x10, 0x00000003F0000000) # frtsOffset
mmio_regs[0x1438] = 0x00000000
mmio_regs[0x1FA828] = 0x0003FF00 << 4
mmio_regs[0x1FA824] = (0x00000003F0000000 >> 12) << 4
rc_frts = emu.call("_nv041253rm", gpu, kgsp, fwsec_desc) & 0xFFFFFFFF
if rc_frts != 0:
diffs.append({"func": "_nv041253rm_frts", "rc": hex(rc_frts)})
# 4. _nv041222rm (GH100 / GB100 / GB202 RISC-V BCR bootstrap sequence)
flcn_writes: list[tuple[int, int]] = []
riscv_writes: list[tuple[int, int]] = []
bcr_ctrl_calls: list[int] = []
emu.wq(kgsp + 0xa30, 0xA30) # wprMeta memdesc
emu.wq(kgsp + 0xa80, 0xA80) # bootloader memdesc
ucode_desc = emu.allocate(0x40)
emu.wd(ucode_desc + 0x1c, 0x580) # os_version
emu.wd(ucode_desc + 0x20, 0x3000) # manifest_offset
emu.wd(ucode_desc + 0x28, 0x1000) # code_offset
emu.wd(ucode_desc + 0x30, 0x2000) # data_offset
emu.wq(kgsp + 0xaa0, ucode_desc)
cc_obj = emu.allocate(0x300)
emu.wd(cc_obj + 0x23c, 0xDEADBEEF)
emu.wq(gpu + 0x23c0, cc_obj)
rpc_obj = emu.allocate(0x800)
rpc_msg = emu.allocate(0x40)
emu.wd(rpc_msg + 0x10, 0) # rpc_result = OK
emu.wq(rpc_obj + 0x6a8, rpc_msg)
wait_calls: list[tuple[int, int]] = []
emu.wq(rpc_obj + 0x20, _make_callback(emu, lambda a: (wait_calls.append((a[2], a[3])), 0)[1]))
emu.wq(kgsp + 0x9c0, rpc_obj)
emu.install("_nv059506rm", lambda _a: 0) # poll succeeds
emu.install("_nv000346rm", lambda _a: 0) # msgq init succeeds
emu.install("_nv036619rm", lambda _a: 0)
emu.wq(kgsp + 0x830, _make_callback(emu, lambda _a: 0))
emu.wq(kflcn + 0x4c0, _make_callback(emu, lambda _a: 0))
emu.wq(kflcn + 0x4c8, _make_callback(emu, lambda a: (flcn_writes.append((a[2], a[3] & 0xFFFFFFFF)), 0)[1]))
emu.wq(kflcn + 0x4d8, _make_callback(emu, lambda a: (riscv_writes.append((a[2], a[3] & 0xFFFFFFFF)), 0)[1]))
emu.wq(kflcn + 0x4e8, _make_callback(emu, lambda _a: 1))
emu.wq(kflcn + 0x4f8, _make_callback(emu, lambda a: (bcr_ctrl_calls.append(a[2]), 0)[1]))
mmio_writes.clear()
rc_gh100 = emu.call("_nv041222rm", gpu, kgsp, 0) & 0xFFFFFFFF
exp_flcn = [(0x40, 0x23456000), (0x44, 0x00000001), (0x80, 0x580)]
exp_riscv = [
(0x678, 0x02000020), (0x67C, 0x00000000), # FMCDATA >> 8, >> 40
(0x680, 0x02000010), (0x684, 0x00000000), # FMCCODE >> 8, >> 40
(0x670, 0x02000030), (0x674, 0x00000000), # PKCPARAM >> 8, >> 40
(0x66C, 0x80000001), # BCR_DMACFG
(0x388, 0x00000001), # RISCV_CPUCTL STARTCPU=1
]
if (rc_gh100 != 0 or flcn_writes != exp_flcn or riscv_writes != exp_riscv
or bcr_ctrl_calls != [1] or mmio_writes != [(0x110804, 0xDEADBEEF)]
or wait_calls != [(0x1001, 0)] or emu.b(gpu + 0xcd9) != 1):
diffs.append({
"func": "_nv041222rm_gh100_blackwell",
"rc": hex(rc_gh100),
"flcn_writes": flcn_writes,
"riscv_writes": riscv_writes,
"bcr_ctrl": bcr_ctrl_calls,
"mmio_writes": mmio_writes,
"wait_calls": wait_calls,
"init_done_flag": emu.b(gpu + 0xcd9),
})
# 5. _nv013979rm (GH100/Blackwell BCR boot poll callback)
mb_state = {0x40: 0x23456000, 0x44: 0x00000001, 0xF4: 0}
emu.wq(kflcn + 0x4c0, _make_callback(emu, lambda a: mb_state.get(a[2], 0)))
r_busy = emu.call("_nv013979rm", gpu, kgsp) & 0xFFFFFFFF
mb_state[0x40] = 0
mb_state[0xF4] = 0 # HWCFG2 bit 13 clear -> done!
r_done = emu.call("_nv013979rm", gpu, kgsp) & 0xFFFFFFFF
if r_busy != 0 or r_done != 1:
diffs.append({"func": "_nv013979rm", "busy": r_busy, "done": r_done})
return {
"name": "gsp_riscv_bootstrap_mmio_unicorn",
"passed": len(diffs) == 0,
"sequences": 5,
"diffs": diffs,
}
def check_gsp_wpr_meta_all_archs_unicorn() -> dict:
"""Execute real 580.178.04 `_nv041391rm` (GH100/GB100/GB202) and `_nv041390rm`
(GB10B/GB20B) in Unicorn and verify exact 256-byte `GspFwWprMeta`."""
diffs = []
for sym, exp_vga, exp_pmu, exp_nonwpr in [
("_nv041391rm", 0x20000, 0x400000, 0x100000),
("_nv041390rm", 0, 0, 0),
]:
emu = Emulator()
_install_common_stubs(emu)
gpu = emu.allocate(0x6000)
kgsp = emu.allocate(0xc00)
img = emu.allocate(0x100)
bl_desc = emu.allocate(0x100)
wpr = emu.allocate(0x100)
sig_md = emu.allocate(0x100)
crash_md = emu.allocate(0x100)
addr_map = {
0x1001: 0x150000000,
0x1002: 0x123450000,
sig_md: 0x160000000,
crash_md: 0x170000000,
}
emu.install("_nv042132rm", lambda _a: 0x400000)
emu.install("_nv043721rm", lambda a: addr_map[a[0]])
emu.install("_nv041332rm", lambda _a: 0x8000000)
emu.install("_nv040033rm", lambda _a: crash_md)
emu.install("_nv030877rm", lambda _a: 1)
emu.wb(gpu + 0xe01, 1)
emu.wb(gpu + 0x543e, 1)
emu.wq(kgsp + 0xa00, wpr)
emu.wq(kgsp + 0xa98, 1)
emu.wd(kgsp + 0xa90, 0x20000)
emu.wq(kgsp + 0xaa0, bl_desc)
emu.wq(kgsp + 0xa80, 0x1001)
emu.wq(kgsp + 0xaa8, 0x1002)
emu.wq(kgsp + 0xab0, sig_md)
emu.wq(kgsp + 0x768, 0x1004)
emu.wq(kgsp + 0x818, _make_callback(emu, lambda _a: 0x100000))
emu.wq(kgsp + 0x878, _make_callback(emu, lambda _a: 0x100000))
emu.wq(kgsp + 0x950, _make_callback(emu, lambda _a: 8))
emu.wd(bl_desc + 0x30, 0)
emu.wd(bl_desc + 0x28, 0x10000)
emu.wd(bl_desc + 0x20, 0x1f000)
emu.wq(img + 0x18, 0x3000000)
emu.wq(sig_md + 0x30, 0x1000)
emu.wq(crash_md + 0x30, 0x8000)
rc = emu.call(sym, gpu, kgsp, img) & 0xFFFFFFFF
magic = emu.q(wpr + 0x00)
rev = emu.q(wpr + 0x08)
vga = emu.q(wpr + 0xC0)
pmu = emu.d(wpr + 0xF4)
nonwpr = emu.q(wpr + 0x68)
if rc != 0 or magic != 0xDC3AAE21371A60B3 or rev != 1 or vga != exp_vga or pmu != exp_pmu or nonwpr != exp_nonwpr:
diffs.append({
"func": sym, "rc": hex(rc), "magic": hex(magic),
"vga": hex(vga), "pmu": hex(pmu), "nonwpr": hex(nonwpr),
})
return {
"name": "gsp_wpr_meta_all_archs_unicorn",
"passed": len(diffs) == 0,
"archs": 2,
"diffs": diffs,
}
def check_gsp_libos_log_decode_unicorn() -> dict:
"""Execute real 580.178.04 `_nv042398rm` (libosLogExtractRecord) in Unicorn on a
`LIBOS_LOG` ring buffer with `put` pointer, `timestamp`, `meta_word`, and arguments,
verifying bit-for-bit parity with `gsp_boot::LibosLogCursor`."""
emu = Emulator()
_install_common_stubs(emu)
diffs = []
# 8-qword ring buffer: +0x00 put=5, +0x08..+0x3f 7 data qwords
ring_buf = emu.allocate(64)
emu.wq(ring_buf + 0x00, 5)
# Record 0: 1 arg (0x1234), meta=(task=3, entry_qwords=3, off=0x100), ts=1000
emu.wq(ring_buf + 0x08, 0x1234)
emu.wq(ring_buf + 0x10, (3 << 56) | (3 << 48) | 0x100)
emu.wq(ring_buf + 0x18, 1000)
# Record 1: 0 args, meta=(task=5, entry_qwords=2, off=0x200), ts=2000
emu.wq(ring_buf + 0x20, (5 << 56) | (2 << 48) | 0x200)
emu.wq(ring_buf + 0x28, 2000)
meta_rec0 = emu.allocate(0x20)
emu.wb(meta_rec0 + 0x14, 1) # arg_count = 1
meta_rec1 = emu.allocate(0x20)
emu.wb(meta_rec1 + 0x14, 0) # arg_count = 0
str_ptr = emu.allocate(16)
emu.write(str_ptr, b"test.c\x00")
emu.wq(meta_rec0, str_ptr)
emu.wq(meta_rec1, str_ptr)
emu.install("_nv000426rm", lambda a: meta_rec0 if a[1] == 0x100 else (meta_rec1 if a[1] == 0x200 else 0))
emu.install("_nv000427rm", lambda a: str_ptr if a[1] == str_ptr else 0)
log_ctx = emu.allocate(0x1000)
rec_ctx = emu.allocate(0x200)
emu.wq(rec_ctx + 0x00, ring_buf) # physicLogBuffer
emu.wq(rec_ctx + 0x08, 64) # bufferSize
emu.wq(rec_ctx + 0x10, 0) # previousPut
emu.wq(rec_ctx + 0x18, 5) # putCopy
emu.wq(rec_ctx + 0x20, 5) # putIter (walks backwards from 5)
emu.wd(rec_ctx + 0x60, 2) # version = 2
emu.wb(rec_ctx + 0x64, 1) # flags bit 0 = 1
emu.wq(rec_ctx + 0x80, 1) # elfImage != NULL
# First call extracts Record 1 (ts=2000, task=5, 0 args, cursor 5 -> 3)
emu.call("_nv042398rm", log_ctx, rec_ctx)
ts1 = emu.q(rec_ctx + 0x118)
task1 = emu.q(rec_ctx + 0x120)
cur1 = emu.q(rec_ctx + 0x20)
if (ts1, task1, cur1) != (2000, 5, 3):
diffs.append({"case": "libos_rec1", "orig": (ts1, task1, cur1), "rust": (2000, 5, 3)})
# Second call extracts Record 0 (ts=1000, task=3, arg0=0x1234, cursor 3 -> 0)
emu.call("_nv042398rm", log_ctx, rec_ctx)
ts0 = emu.q(rec_ctx + 0x118)
task0 = emu.q(rec_ctx + 0x120)
arg0 = emu.q(rec_ctx + 0x128)
cur0 = emu.q(rec_ctx + 0x20)
if (ts0, task0, arg0, cur0) != (1000, 3, 0x1234, 0):
diffs.append({"case": "libos_rec0", "orig": (ts0, task0, arg0, cur0), "rust": (1000, 3, 0x1234, 0)})
return {
"name": "gsp_libos_log_decode_unicorn",
"passed": len(diffs) == 0,
"records": 2,
"diffs": diffs,
}
def run_checks() -> list[dict]:
return [
check_gsp_msgq_send_recv_checksum_ring_unicorn(),
check_gsp_continuation_record_split_reassemble_unicorn(),
check_gsp_rpc_payload_codecs_unicorn(),
check_gsp_riscv_bootstrap_mmio_unicorn(),
check_gsp_wpr_meta_all_archs_unicorn(),
check_gsp_libos_log_decode_unicorn(),
]
def main() -> int:
results = run_checks()
all_ok = all(r["passed"] for r in results)
for r in results:
status = "PASS" if r["passed"] else "FAIL"
print(f"[{status}] {r['name']} (diffs={len(r['diffs'])})")
if not r["passed"]:
print(json.dumps(r["diffs"], indent=2))
print(f"\nSummary: {sum(r['passed'] for r in results)}/{len(results)} PASS")
return 0 if all_ok else 1
if __name__ == "__main__":
raise SystemExit(main())