Files
nvdriver/tools/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

437 lines
16 KiB
Python
Executable File

#!/usr/bin/env python3
"""Extract 580.x GSP-RM boot ucode from kernel-open nv-kernel.o_binary into linux-firmware nvfw_bin_hdr files.
Produces standard nouveau / linux-firmware layout files under <output-dir>/<chip>/gsp/:
- bootloader-580.bin (nvfw_bin_hdr + RM_RISCV_UCODE_DESC + RISC-V image)
- booter_load-580.bin (nvfw_bin_hdr + nvfw_hs_header_v2 + sigs/meta/load_hdr + image)
- booter_unload-580.bin (nvfw_bin_hdr + nvfw_hs_header_v2 + sigs/meta/load_hdr + image)
- scrubber-580.bin (AD10x only: ksec2BinArchiveSecurescrubUcode_AD10X)
- fmc-580.bin (GB20x only: ELF32 with hash/signature/publickey/image sections, the
GSP-FMC that FSP authenticates and starts; GB20x has no booters)
Note: The input must be the open-kernel-modules object
(`kernel-open/nvidia/nv-kernel.o_binary` from the 580.x `.run` installer or
`open-gpu-kernel-modules` build). The proprietary `kernel/nvidia/nv-kernel.o_binary`
strips the `kgspBinArchive*` bindata symbols and cannot be used here.
Currently supports Ampere (`ga102`), Ada (`ad102`) and the GeForce/RTX PRO Blackwell
chips GB202..GB207 (`gb202`); Hopper and GB10x are out of scope for this extractor.
Usage:
python3 tools/extract_gsp_boot_ucode.py \\
--rm-object /path/to/kernel-open/nvidia/nv-kernel.o_binary \\
--chip ad102 \\
--out-dir /lib/firmware/nvidia
"""
from __future__ import annotations
import argparse
import hashlib
import os
import struct
import sys
import tempfile
import zlib
from pathlib import Path
ELF_MAGIC = b"\x7fELF"
SHT_SYMTAB = 2
SHT_SYMTAB_SHNDX = 18
SHN_XINDEX = 0xFFFF
MAX_HS_SIG_COUNT = 64
def align_up(val: int, align: int) -> int:
return (val + align - 1) & ~(align - 1)
def _check_slice(data_len: int, offset: int, size: int, label: str) -> None:
if offset < 0 or size < 0 or offset + size > data_len:
raise ValueError(f"{label} out of bounds (offset={offset}, size={size}, file_len={data_len})")
def parse_elf64_rodata_and_syms(path: Path) -> tuple[bytes, int, int, dict[str, tuple[int, int]]]:
data = path.read_bytes()
data_len = len(data)
if data_len < 64 or data[:4] != ELF_MAGIC or data[4] != 2 or data[5] != 1:
raise ValueError(f"{path} is not a little-endian ELF64 object")
e_shoff = struct.unpack_from("<Q", data, 40)[0]
e_shentsize, e_shnum, e_shstrndx = struct.unpack_from("<HHH", data, 58)
if e_shoff == 0 or e_shentsize < 64:
raise ValueError(f"{path} has invalid section header table (shoff={e_shoff}, shentsize={e_shentsize})")
_check_slice(data_len, e_shoff, e_shentsize, "section header 0")
sh0_name, sh0_type, _sh0_flags, _sh0_addr, sh0_offset, sh0_size, sh0_link = struct.unpack_from(
"<IIQQQQI", data, e_shoff
)
shnum = sh0_size if e_shnum == 0 else e_shnum
shstrndx = sh0_link if e_shstrndx == SHN_XINDEX else e_shstrndx
if shnum == 0:
raise ValueError(f"{path} has no ELF sections")
_check_slice(data_len, e_shoff, shnum * e_shentsize, "section header table")
if shstrndx >= shnum:
raise ValueError(f"{path} has out-of-range shstrndx={shstrndx} (shnum={shnum})")
sections: list[tuple[int, int, int, int, int]] = []
for i in range(shnum):
off = e_shoff + i * e_shentsize
sh_name, sh_type, _flags, _addr, sh_offset, sh_size, sh_link = struct.unpack_from(
"<IIQQQQI", data, off
)
sections.append((sh_name, sh_type, sh_offset, sh_size, sh_link))
_, _, shstr_off, shstr_size, _ = sections[shstrndx]
_check_slice(data_len, shstr_off, shstr_size, "shstrtab")
def read_cstr(table_off: int, table_size: int, idx: int, label: str) -> str:
if idx >= table_size:
raise ValueError(f"{path}: {label} index {idx} out of bounds (size={table_size})")
start = table_off + idx
limit = table_off + table_size
end = data.find(b"\x00", start, limit)
if end < 0:
raise ValueError(f"{path}: unterminated string in {label} at offset {idx}")
return data[start:end].decode("ascii", errors="replace")
rodata_idx = None
rodata_off = None
rodata_size = None
symtab_sec = None
symtab_idx = None
shndx_by_link: dict[int, tuple[int, int]] = {}
for idx, (sh_name, sh_type, sh_offset, sh_size, sh_link) in enumerate(sections):
name = read_cstr(shstr_off, shstr_size, sh_name, "shstrtab")
if name == ".rodata":
_check_slice(data_len, sh_offset, sh_size, ".rodata")
rodata_idx = idx
rodata_off = sh_offset
rodata_size = sh_size
if sh_type == SHT_SYMTAB:
_check_slice(data_len, sh_offset, sh_size, ".symtab")
symtab_sec = (sh_offset, sh_size, sh_link)
symtab_idx = idx
elif sh_type == SHT_SYMTAB_SHNDX:
_check_slice(data_len, sh_offset, sh_size, ".symtab_shndx")
shndx_by_link[sh_link] = (sh_offset, sh_size)
if rodata_idx is None or rodata_off is None or rodata_size is None or symtab_sec is None:
raise ValueError(f"{path} missing .rodata or .symtab")
sym_off, sym_size, str_idx = symtab_sec
if sym_size % 24 != 0:
raise ValueError(f"{path}: .symtab size {sym_size} is not a multiple of 24")
if str_idx >= shnum:
raise ValueError(f"{path}: .symtab sh_link={str_idx} out of range (shnum={shnum})")
_, _, str_off, str_size, _ = sections[str_idx]
_check_slice(data_len, str_off, str_size, ".strtab")
ext_shndx = shndx_by_link.get(symtab_idx)
syms: dict[str, tuple[int, int]] = {}
for sym_i, pos in enumerate(range(sym_off, sym_off + sym_size, 24)):
st_name, _info, _other, st_shndx, st_value, st_size = struct.unpack_from(
"<IBBHQQ", data, pos
)
resolved_shndx = st_shndx
if st_shndx == SHN_XINDEX:
if ext_shndx is None:
raise ValueError(
f"{path}: symbol {sym_i} uses SHN_XINDEX without a matching "
f"SHT_SYMTAB_SHNDX section for .symtab (index {symtab_idx})"
)
if (sym_i + 1) * 4 > ext_shndx[1]:
raise ValueError(
f"{path}: truncated SHT_SYMTAB_SHNDX section (size {ext_shndx[1]}) "
f"for symbol index {sym_i}"
)
resolved_shndx = struct.unpack_from("<I", data, ext_shndx[0] + sym_i * 4)[0]
if resolved_shndx == rodata_idx and st_size > 0:
name = read_cstr(str_off, str_size, st_name, ".strtab")
syms[name] = (st_value, st_size)
return data, rodata_off, rodata_size, syms
def read_bindata(
data: bytes,
rodata_off: int,
rodata_size: int,
syms: dict[str, tuple[int, int]],
sym: str,
compressed: bool | None = None,
expected_len: int | None = None,
) -> bytes:
if sym not in syms:
has_gsp_bindata = any(name.startswith("kgspBinArchive") for name in syms)
if not has_gsp_bindata:
raise KeyError(
f"missing symbol {sym}: input ELF has no kgspBinArchive* symbols "
"(the proprietary kernel/nvidia/nv-kernel.o_binary strips them; "
"pass kernel-open/nvidia/nv-kernel.o_binary from the 580.x .run or open-gpu-kernel-modules)"
)
raise KeyError(f"missing symbol {sym}")
voff, size = syms[sym]
if voff + size > rodata_size:
raise ValueError(
f"{sym}: symbol range [{voff}, {voff + size}) exceeds .rodata size {rodata_size}"
)
raw = data[rodata_off + voff : rodata_off + voff + size]
if compressed is False and (expected_len is None or len(raw) == expected_len):
return raw
if compressed is True or (expected_len is not None and len(raw) != expected_len):
if len(raw) >= 2 and raw[0] == 0x1F and raw[1] == 0x8B:
out = zlib.decompress(raw, 16 + zlib.MAX_WBITS)
else:
out = zlib.decompress(raw, -zlib.MAX_WBITS)
if expected_len is not None and len(out) != expected_len:
raise ValueError(f"{sym}: decompressed len {len(out)} != expected {expected_len}")
return out
return raw
def pack_riscv_bootloader(desc: bytes, image: bytes) -> bytes:
header_off = 0x18
data_off = header_off + len(desc)
total_size = align_up(data_off + len(image), 0x100)
bin_hdr = struct.pack("<6I", 0x10DE, 1, total_size, header_off, data_off, len(image))
return bin_hdr + desc + image
def pack_hs_booter(
sig_prod: bytes,
patch_loc: bytes,
patch_sig: bytes,
patch_meta: bytes,
num_sigs: bytes,
header_prod: bytes,
image_prod: bytes,
) -> bytes:
header_off = 0x18
hs_hdr_size = 9 * 4 # 0x24
sig_prod_off = header_off + hs_hdr_size # 0x3c
patch_loc_off = sig_prod_off + len(sig_prod)
patch_sig_off = patch_loc_off + len(patch_loc)
meta_off = patch_sig_off + len(patch_sig)
num_sigs_off = meta_off + len(patch_meta)
load_hdr_off = num_sigs_off + len(num_sigs)
data_off = load_hdr_off + len(header_prod)
total_size = align_up(data_off + len(image_prod), 0x100)
bin_hdr = struct.pack("<6I", 0x10DE, 1, total_size, header_off, data_off, len(image_prod))
hs_hdr = struct.pack(
"<9I",
sig_prod_off,
len(sig_prod),
patch_loc_off,
patch_sig_off,
meta_off,
len(patch_meta),
num_sigs_off,
load_hdr_off,
len(header_prod),
)
return (
bin_hdr
+ hs_hdr
+ sig_prod
+ patch_loc
+ patch_sig
+ patch_meta
+ num_sigs
+ header_prod
+ image_prod
)
def extract_hs_archive(
data: bytes, rodata_off: int, rodata_size: int, syms: dict[str, tuple[int, int]], prefix: str
) -> bytes:
num_sigs = read_bindata(
data, rodata_off, rodata_size, syms, f"{prefix}_BINDATA_LABEL_NUM_SIGS_data", False, expected_len=4
)
count = struct.unpack_from("<I", num_sigs, 0)[0]
if count == 0 or count > MAX_HS_SIG_COUNT:
raise ValueError(f"{prefix}: invalid HS signature count {count}")
sig_prod = read_bindata(
data,
rodata_off,
rodata_size,
syms,
f"{prefix}_BINDATA_LABEL_SIG_PROD_data",
False,
expected_len=count * 384,
)
patch_loc = read_bindata(
data, rodata_off, rodata_size, syms, f"{prefix}_BINDATA_LABEL_PATCH_LOC_data", False, expected_len=4
)
patch_sig = read_bindata(
data, rodata_off, rodata_size, syms, f"{prefix}_BINDATA_LABEL_PATCH_SIG_data", False, expected_len=4
)
patch_meta = read_bindata(
data, rodata_off, rodata_size, syms, f"{prefix}_BINDATA_LABEL_PATCH_META_data", False, expected_len=12
)
header_prod = read_bindata(
data, rodata_off, rodata_size, syms, f"{prefix}_BINDATA_LABEL_HEADER_PROD_data", True, expected_len=36
)
image_prod = read_bindata(
data, rodata_off, rodata_size, syms, f"{prefix}_BINDATA_LABEL_IMAGE_PROD_data", True
)
return pack_hs_booter(sig_prod, patch_loc, patch_sig, patch_meta, num_sigs, header_prod, image_prod)
# FMC section name -> (bindata label, exact size in bytes; None = any)
FMC_SECTIONS = {
"hash": ("UCODE_HASH", 48),
"signature": ("UCODE_SIG", 96),
"publickey": ("UCODE_PKEY", 97),
"image": ("UCODE_IMAGE", None),
}
def pack_fmc(sections: dict[str, bytes]) -> bytes:
"""Pack the FMC parts as the ELF32 container linux-firmware uses for `fmc-*.bin`."""
names = b"\0" + b"".join(n.encode() + b"\0" for n in [".shstrtab", *sections])
shnum = len(sections) + 2 # NULL and .shstrtab
body = bytearray(52 + 40 * shnum)
def add(blob: bytes) -> int:
body.extend(bytes(-len(body) % 4))
off = len(body)
body.extend(blob)
return off
shdrs = [bytes(40), struct.pack("<10I", 1, 3, 0x20, 0, add(names), len(names), 0, 0, 1, 0)]
for name, blob in sections.items():
name_off = names.index(b"\0" + name.encode() + b"\0") + 1
shdrs.append(struct.pack("<10I", name_off, 1, 0, 0, add(blob), len(blob), 0, zlib.crc32(blob), 4, 0))
body[:52] = struct.pack(
"<16sHHIIIIIHHHHHH", b"\x7fELF\x01\x01\x01", 0, 0, 1, 0, 0, 52, 0, 52, 0, 0, 40, shnum, 1
)
body[52 : 52 + 40 * shnum] = b"".join(shdrs)
return bytes(body)
CHIPS = {
"ga102": {
"bootloader": "kgspBinArchiveGspRmBoot_GA102",
"booter_load": "kgspBinArchiveBooterLoadUcode_GA102",
"booter_unload": "kgspBinArchiveBooterUnloadUcode_GA102",
},
"ad102": {
"bootloader": "kgspBinArchiveGspRmBoot_AD102",
"booter_load": "kgspBinArchiveBooterLoadUcode_AD102",
"booter_unload": "kgspBinArchiveBooterUnloadUcode_AD102",
"scrubber": "ksec2BinArchiveSecurescrubUcode_AD10X",
},
"gb202": {
"bootloader": "kgspBinArchiveGspRmBoot_GB202",
"bootloader_image_stored": True, # not deflated, unlike the older chips'
"fmc": "kgspBinArchiveGspRmFmcGfwProdSigned_GB202",
},
}
def _write_file_atomic(dst: Path, blob: bytes) -> None:
fd, tmp_name = tempfile.mkstemp(prefix=f".{dst.name}.", suffix=".tmp", dir=dst.parent)
tmp_path = Path(tmp_name)
try:
with os.fdopen(fd, "wb") as fh:
fh.write(blob)
fh.flush()
os.chmod(tmp_path, 0o644)
os.replace(tmp_path, dst)
except BaseException:
try:
tmp_path.unlink(missing_ok=True)
except OSError:
pass
raise
def extract_chip_from_parsed(
data: bytes,
rodata_off: int,
rodata_size: int,
syms: dict[str, tuple[int, int]],
chip: str,
out_dir: Path,
suffix: str,
) -> None:
spec = CHIPS[chip]
bl_prefix = spec["bootloader"]
desc = read_bindata(
data, rodata_off, rodata_size, syms, f"{bl_prefix}_BINDATA_LABEL_UCODE_DESC_PROD_data", True
)
img = read_bindata(
data, rodata_off, rodata_size, syms, f"{bl_prefix}_BINDATA_LABEL_UCODE_IMAGE_PROD_data",
not spec.get("bootloader_image_stored", False),
)
outputs = {
f"bootloader-{suffix}.bin": pack_riscv_bootloader(desc, img),
}
for part in ("booter_load", "booter_unload", "scrubber"):
if part in spec:
outputs[f"{part}-{suffix}.bin"] = extract_hs_archive(
data, rodata_off, rodata_size, syms, spec[part]
)
if "fmc" in spec:
sections = {}
for name, (label, size) in FMC_SECTIONS.items():
sym = f"{spec['fmc']}_BINDATA_LABEL_{label}_data"
# all four are stored uncompressed (the image is what `hash` and `signature` cover)
sections[name] = read_bindata(data, rodata_off, rodata_size, syms, sym, False, expected_len=size)
outputs[f"fmc-{suffix}.bin"] = pack_fmc(sections)
gsp_dir = out_dir / chip / "gsp"
gsp_dir.mkdir(parents=True, exist_ok=True)
for fname, blob in outputs.items():
dst = gsp_dir / fname
_write_file_atomic(dst, blob)
digest = hashlib.sha256(blob).hexdigest()[:16]
print(f"{dst}: {len(blob)} bytes sha256={digest}...")
def extract_chip(rm_object: Path, chip: str, out_dir: Path, suffix: str) -> None:
data, rodata_off, rodata_size, syms = parse_elf64_rodata_and_syms(rm_object)
extract_chip_from_parsed(data, rodata_off, rodata_size, syms, chip, out_dir, suffix)
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument(
"--rm-object",
type=Path,
default=Path("/usr/src/nvidia-580.178.04/nvidia/nv-kernel.o_binary"),
help="Path to 580.x kernel-open/nvidia/nv-kernel.o_binary (not proprietary kernel/)",
)
ap.add_argument(
"--chip",
choices=[*CHIPS.keys(), "all"],
default="ad102",
help="Target chip family (default: ad102)",
)
ap.add_argument(
"--out-dir",
type=Path,
default=Path("/lib/firmware/nvidia"),
help="Firmware root directory (default: /lib/firmware/nvidia)",
)
ap.add_argument("--suffix", default="580", help="Filename version suffix (default: 580)")
args = ap.parse_args(argv)
chips = list(CHIPS.keys()) if args.chip == "all" else [args.chip]
try:
data, rodata_off, rodata_size, syms = parse_elf64_rodata_and_syms(args.rm_object)
for chip in chips:
extract_chip_from_parsed(data, rodata_off, rodata_size, syms, chip, args.out_dir, args.suffix)
except (OSError, ValueError, KeyError, zlib.error) as exc:
msg = exc.args[0] if isinstance(exc, KeyError) and exc.args else str(exc)
print(f"error: {msg}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())