Files
nvdriver/tests/offline/test_extract_gsp_boot_ucode.py
Fardid021 76ca4abcc5 GB20x (RTX 50): GSP boot through the FSP, MMU v3 and CUDA on a GB205 (#416)
* GB20x (RTX 50): GSP boot through the FSP, MMU v3 and CUDA on a GB205

A GB205 (RTX 5070) stopped at "boot failed" (EIO): its GSP is started by the
FSP, not by booter_load on SEC2, and its page tables are format version 3.

- gpu/fsp.rs: the FSP command channel (EMEM queue, MCTP/NVDM headers), the
  chain-of-trust message with the FMC image and its signature, and the checks
  of the reply. extract_gsp_boot_ucode.py also takes the GB20x FMC out of the
  580.178.04 module.
- MMU format version 3 for the kernel-side tables and the UVM node: PDE4 root
  with 2 entries, PCF field, 16-byte PDE0.
- Context buffers placed by their own sizes: a GB205's attribute CB is 50 MiB.
- Work submit token with RUNLIST_DOORBELL (bit 30).
- BLACKWELL_USERMODE_A with bBar1Mapping: the doorbell is mapped through BAR1
  (PTE kind SMSKED_MESSAGE). Rung through BAR0, about one CUDA start in four
  waited forever for its first work.
- Classes 0xcec0, 0xce97 and 0xc761; copy engines from the class database.

Tested on an RTX 5070 (10de:2f04, VFIO guest, 580.178.04 userspace).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* uvm: a PTE kind that does not fit MMU format 3 gives an invalid entry

V3 has four bits for the kind. A kind like 0x1f became 0xf, a reflected SKED
entry without an address, and 0xdb became 0xb. Such an entry is now invalid, so
that an access faults instead of using another kind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* GB20x: review fixes

- ga10x_mem: a BAR1 of 2 MiB or less has no room for the doorbell slot and is
  refused before anything is allocated. The check word stays out of that slot.
  If the window is taken back and the invalidate does not complete, its tables
  stay allocated.
- ga10x_gsp: a boot that fails before the message to the FSP (for example
  because the FMC file is missing) gave no falcon an address, so its memory is
  freed and the next open can try again without a GPU reset.
- uvm_node: VA bit 56 picks the PDE3 page in MMU format 3.
- mmu_v3: a system address above bit 51 gives an invalid entry.
- fsp: use the HWCFG2 and NVDM helpers that exist.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 17:38:13 +01:00

338 lines
14 KiB
Python

#!/usr/bin/env python3
"""Offline unit tests for tools/extract_gsp_boot_ucode.py."""
from __future__ import annotations
import gzip
import io
import struct
import sys
import tempfile
import unittest
from unittest import mock
import zlib
from contextlib import redirect_stderr, redirect_stdout
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "tools"))
import extract_gsp_boot_ucode as extractor # noqa: E402
def _raw_deflate(payload: bytes) -> bytes:
comp = zlib.compressobj(wbits=-zlib.MAX_WBITS)
return comp.compress(payload) + comp.flush()
def _make_elf64(
rodata_entries: dict[str, bytes],
*,
use_xindex: bool = False,
corrupt_sym_size: tuple[str, int] | None = None,
) -> bytes:
"""Build a minimal little-endian ELF64 relocatable object with .rodata/.symtab/.strtab/.shstrtab."""
rodata = bytearray()
sym_specs: list[tuple[str, int, int]] = []
for name, payload in rodata_entries.items():
off = len(rodata)
rodata.extend(payload)
size = corrupt_sym_size[1] if corrupt_sym_size and corrupt_sym_size[0] == name else len(payload)
sym_specs.append((name, off, size))
strtab = bytearray(b"\x00")
symtab = bytearray(24) # STN_UNDEF
shndx_entries = [0]
rodata_shndx = 1
for name, off, size in sym_specs:
name_off = len(strtab)
strtab.extend(name.encode("ascii") + b"\x00")
st_shndx = extractor.SHN_XINDEX if use_xindex else rodata_shndx
symtab.extend(struct.pack("<IBBHQQ", name_off, 0, 0, st_shndx, off, size))
shndx_entries.append(rodata_shndx)
shstrtab = bytearray(b"\x00")
def add_shname(s: str) -> int:
pos = len(shstrtab)
shstrtab.extend(s.encode("ascii") + b"\x00")
return pos
sh_rodata_name = add_shname(".rodata")
sh_symtab_name = add_shname(".symtab")
sh_strtab_name = add_shname(".strtab")
sh_shstrtab_name = add_shname(".shstrtab")
sh_shndx_name = add_shname(".symtab_shndx") if use_xindex else 0
shndx_bytes = b"".join(struct.pack("<I", idx) for idx in shndx_entries) if use_xindex else b""
body = bytearray(b"\x00" * 64) # ELF header placeholder
rodata_off = len(body)
body.extend(rodata)
symtab_off = len(body)
body.extend(symtab)
strtab_off = len(body)
body.extend(strtab)
shstrtab_off = len(body)
body.extend(shstrtab)
shndx_off = len(body)
if use_xindex:
body.extend(shndx_bytes)
shoff = len(body)
shnum = 6 if use_xindex else 5
shstrndx = 4
def pack_shdr(name: int, stype: int, off: int, size: int, link: int = 0) -> bytes:
return struct.pack("<IIQQQQIIQQ", name, stype, 0, 0, off, size, link, 0, 1, 0)
shdr0_size = shnum if use_xindex else 0
shdr0_link = shstrndx if use_xindex else 0
shdrs = [
pack_shdr(0, 0, 0, shdr0_size, shdr0_link),
pack_shdr(sh_rodata_name, 1, rodata_off, len(rodata)),
pack_shdr(sh_symtab_name, extractor.SHT_SYMTAB, symtab_off, len(symtab), link=3),
pack_shdr(sh_strtab_name, 3, strtab_off, len(strtab)),
pack_shdr(sh_shstrtab_name, 3, shstrtab_off, len(shstrtab)),
]
if use_xindex:
shdrs.append(
pack_shdr(sh_shndx_name, extractor.SHT_SYMTAB_SHNDX, shndx_off, len(shndx_bytes), link=2)
)
for shdr in shdrs:
body.extend(shdr)
e_shnum = 0 if use_xindex else shnum
e_shstrndx = extractor.SHN_XINDEX if use_xindex else shstrndx
ehdr = struct.pack(
"<16sHHIQQQIHHHHHH",
b"\x7fELF\x02\x01\x01" + b"\x00" * 9,
1, # ET_REL
62, # EM_X86_64
1,
0,
0,
shoff,
0,
64,
0,
0,
64,
e_shnum,
e_shstrndx,
)
body[:64] = ehdr
return bytes(body)
def _add_hs_entries(entries: dict[str, bytes], prefix: str, num_sigs: int = 1) -> None:
entries[f"{prefix}_BINDATA_LABEL_NUM_SIGS_data"] = struct.pack("<I", num_sigs)
entries[f"{prefix}_BINDATA_LABEL_SIG_PROD_data"] = b"\xaa" * (num_sigs * 384)
entries[f"{prefix}_BINDATA_LABEL_PATCH_LOC_data"] = struct.pack("<I", 0x10)
entries[f"{prefix}_BINDATA_LABEL_PATCH_SIG_data"] = struct.pack("<I", 0x20)
entries[f"{prefix}_BINDATA_LABEL_PATCH_META_data"] = b"\x11" * 12
entries[f"{prefix}_BINDATA_LABEL_HEADER_PROD_data"] = gzip.compress(b"\x22" * 36)
entries[f"{prefix}_BINDATA_LABEL_IMAGE_PROD_data"] = _raw_deflate(b"\x33" * 256)
def _make_full_chip_entries(chips: list[str]) -> dict[str, bytes]:
entries: dict[str, bytes] = {}
for chip in chips:
spec = extractor.CHIPS[chip]
bl = spec["bootloader"]
entries[f"{bl}_BINDATA_LABEL_UCODE_DESC_PROD_data"] = gzip.compress(b"\x04" * 44)
image = b"\x55" * 512
if not spec.get("bootloader_image_stored"):
image = _raw_deflate(image)
entries[f"{bl}_BINDATA_LABEL_UCODE_IMAGE_PROD_data"] = image
if "booter_load" in spec:
_add_hs_entries(entries, spec["booter_load"], num_sigs=2)
_add_hs_entries(entries, spec["booter_unload"], num_sigs=1)
if "scrubber" in spec:
_add_hs_entries(entries, spec["scrubber"], num_sigs=1)
if "fmc" in spec:
fmc = f"{spec['fmc']}_BINDATA_LABEL"
entries[f"{fmc}_UCODE_HASH_data"] = b"f" * 48
entries[f"{fmc}_UCODE_SIG_data"] = b"w" * 96
entries[f"{fmc}_UCODE_PKEY_data"] = b"\x88" * 97
entries[f"{fmc}_UCODE_IMAGE_data"] = b"\x99" * 1024
return entries
class ExtractGspBootUcodeTests(unittest.TestCase):
def test_extract_ad102_and_ga102_all(self) -> None:
with tempfile.TemporaryDirectory() as td:
root = Path(td)
obj = root / "nv-kernel.o_binary"
obj.write_bytes(_make_elf64(_make_full_chip_entries(["ga102", "ad102", "gb202"])))
out_dir = root / "fw"
buf = io.StringIO()
with redirect_stdout(buf):
rc = extractor.main(["--rm-object", str(obj), "--chip", "all", "--out-dir", str(out_dir)])
self.assertEqual(rc, 0)
ad_dir = out_dir / "ad102" / "gsp"
ga_dir = out_dir / "ga102" / "gsp"
for name in ("bootloader-580.bin", "booter_load-580.bin", "booter_unload-580.bin", "scrubber-580.bin"):
self.assertTrue((ad_dir / name).is_file(), f"missing {name}")
for name in ("bootloader-580.bin", "booter_load-580.bin", "booter_unload-580.bin"):
self.assertTrue((ga_dir / name).is_file(), f"missing {name}")
self.assertFalse((ga_dir / "scrubber-580.bin").exists())
bl = (ad_dir / "bootloader-580.bin").read_bytes()
magic, ver, total_size, hdr_off, data_off, data_size = struct.unpack_from("<6I", bl, 0)
self.assertEqual((magic, ver, hdr_off, data_off, data_size), (0x10DE, 1, 0x18, 0x18 + 44, 512))
self.assertEqual(total_size, extractor.align_up(0x18 + 44 + 512, 0x100))
load = (ad_dir / "booter_load-580.bin").read_bytes()
hs = struct.unpack_from("<9I", load, 0x18)
self.assertEqual(hs[0], 0x3C)
self.assertEqual(hs[1], 2 * 384)
self.assertEqual(hs[8], 36)
def test_gb202_writes_bootloader_and_fmc_container(self) -> None:
with tempfile.TemporaryDirectory() as td:
obj = Path(td) / "nv-kernel.o_binary"
obj.write_bytes(_make_elf64(_make_full_chip_entries(["gb202"])))
with redirect_stdout(io.StringIO()):
rc = extractor.main(["--rm-object", str(obj), "--chip", "gb202", "--out-dir", td])
self.assertEqual(rc, 0)
gsp = Path(td) / "gb202" / "gsp"
self.assertEqual(sorted(f.name for f in gsp.iterdir()), ["bootloader-580.bin", "fmc-580.bin"])
elf = (gsp / "fmc-580.bin").read_bytes()
self.assertEqual(elf[:7], b"\x7fELF\x01\x01\x01")
shoff = struct.unpack_from("<I", elf, 32)[0]
shentsize, shnum, shstrndx = struct.unpack_from("<3H", elf, 46)
hdrs = [struct.unpack_from("<10I", elf, shoff + i * shentsize) for i in range(shnum)]
names = elf[hdrs[shstrndx][4] :]
got = {names[h[0] : names.index(b"\0", h[0])].decode(): elf[h[4] : h[4] + h[5]] for h in hdrs[2:]}
self.assertEqual(
got,
{
"hash": b"f" * 48,
"signature": b"w" * 96,
"publickey": b"\x88" * 97,
"image": b"\x99" * 1024,
},
)
def test_extended_section_numbering_xindex(self) -> None:
with tempfile.TemporaryDirectory() as td:
root = Path(td)
obj = root / "nv-kernel-xindex.o_binary"
obj.write_bytes(_make_elf64(_make_full_chip_entries(["ad102"]), use_xindex=True))
out_dir = root / "fw"
buf = io.StringIO()
with redirect_stdout(buf):
rc = extractor.main(["--rm-object", str(obj), "--chip", "ad102", "--out-dir", str(out_dir)])
self.assertEqual(rc, 0)
self.assertTrue((out_dir / "ad102" / "gsp" / "scrubber-580.bin").is_file())
def test_proprietary_object_without_kgsp_symbols_reports_clear_hint(self) -> None:
with tempfile.TemporaryDirectory() as td:
root = Path(td)
obj = root / "proprietary.o_binary"
obj.write_bytes(_make_elf64({"some_other_rodata_symbol": b"hello"}))
out_dir = root / "fw"
err = io.StringIO()
with redirect_stderr(err):
rc = extractor.main(["--rm-object", str(obj), "--chip", "ad102", "--out-dir", str(out_dir)])
self.assertEqual(rc, 1)
msg = err.getvalue()
self.assertIn("kernel-open/nvidia/nv-kernel.o_binary", msg)
self.assertIn("kgspBinArchive", msg)
self.assertFalse((out_dir / "ad102").exists())
def test_rejects_symbol_exceeding_rodata_bounds(self) -> None:
with tempfile.TemporaryDirectory() as td:
root = Path(td)
entries = _make_full_chip_entries(["ad102"])
bad_sym = "kgspBinArchiveGspRmBoot_AD102_BINDATA_LABEL_UCODE_DESC_PROD_data"
obj = root / "oob.o_binary"
obj.write_bytes(_make_elf64(entries, corrupt_sym_size=(bad_sym, 10_000_000)))
out_dir = root / "fw"
err = io.StringIO()
with redirect_stderr(err):
rc = extractor.main(["--rm-object", str(obj), "--chip", "ad102", "--out-dir", str(out_dir)])
self.assertEqual(rc, 1)
self.assertIn("exceeds .rodata size", err.getvalue())
def test_rejects_zero_hs_sig_count(self) -> None:
with tempfile.TemporaryDirectory() as td:
root = Path(td)
entries = _make_full_chip_entries(["ad102"])
entries["kgspBinArchiveBooterLoadUcode_AD102_BINDATA_LABEL_NUM_SIGS_data"] = struct.pack("<I", 0)
obj = root / "zero-sig.o_binary"
obj.write_bytes(_make_elf64(entries))
out_dir = root / "fw"
err = io.StringIO()
with redirect_stderr(err):
rc = extractor.main(["--rm-object", str(obj), "--chip", "ad102", "--out-dir", str(out_dir)])
self.assertEqual(rc, 1)
self.assertIn("invalid HS signature count", err.getvalue())
def test_failed_write_and_replace_preserve_existing_firmware_and_clean_tempfiles(self) -> None:
with tempfile.TemporaryDirectory() as td:
root = Path(td)
obj = root / "nv-kernel.o_binary"
obj.write_bytes(_make_elf64(_make_full_chip_entries(["ad102"])))
out_dir = root / "fw"
gsp_dir = out_dir / "ad102" / "gsp"
gsp_dir.mkdir(parents=True)
existing = gsp_dir / "bootloader-580.bin"
existing.write_bytes(b"ORIGINAL_INSTALLED_FIRMWARE")
# 1. os.replace failure preserves existing file, removes tempfiles, returns 1.
err1 = io.StringIO()
with (
mock.patch.object(extractor.os, "replace", side_effect=OSError("simulated replace failure")),
redirect_stderr(err1),
):
rc1 = extractor.main(["--rm-object", str(obj), "--chip", "ad102", "--out-dir", str(out_dir)])
self.assertEqual(rc1, 1)
self.assertIn("simulated replace failure", err1.getvalue())
self.assertEqual(existing.read_bytes(), b"ORIGINAL_INSTALLED_FIRMWARE")
self.assertEqual(list(gsp_dir.glob("*.tmp")), [])
# 2. Write failure inside os.fdopen preserves existing file, removes tempfiles, returns 1.
real_fdopen = extractor.os.fdopen
class FailingWriter:
def __init__(self, fh):
self._fh = fh
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
self._fh.close()
return False
def write(self, _data: bytes) -> int:
raise OSError("simulated disk full")
def flush(self) -> None:
pass
err2 = io.StringIO()
with (
mock.patch.object(extractor.os, "fdopen", side_effect=lambda fd, mode: FailingWriter(real_fdopen(fd, mode))),
redirect_stderr(err2),
):
rc2 = extractor.main(["--rm-object", str(obj), "--chip", "ad102", "--out-dir", str(out_dir)])
self.assertEqual(rc2, 1)
self.assertIn("simulated disk full", err2.getvalue())
self.assertEqual(existing.read_bytes(), b"ORIGINAL_INSTALLED_FIRMWARE")
self.assertEqual(list(gsp_dir.glob("*.tmp")), [])
if __name__ == "__main__":
unittest.main()