mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
tools: harden dev_mode/dev_health/dev_reload and honor --check/atomic writes in extract_gv100_firmware.py
This commit is contained in:
111
tests/offline/test_dev_loop_and_fw_extractor.py
Normal file
111
tests/offline/test_dev_loop_and_fw_extractor.py
Normal file
@ -0,0 +1,111 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline tests for dev_mode.sh, dev_health.sh, dev_reload.sh, and extract_gv100_firmware.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
STOCK_OBJ = Path("/usr/src/nvidia-580.178.04/nvidia/nv-kernel.o_binary")
|
||||
|
||||
|
||||
class TestDevLoopScripts(unittest.TestCase):
|
||||
def test_shell_syntax_valid(self):
|
||||
for rel in ("tools/dev_mode.sh", "tools/dev_health.sh", "tools/dev_reload.sh"):
|
||||
proc = subprocess.run(["sh", "-n", str(REPO / rel)], capture_output=True, text=True)
|
||||
self.assertEqual(proc.returncode, 0, f"{rel} syntax error: {proc.stderr}")
|
||||
|
||||
def test_dev_mode_and_health_reject_bad_args(self):
|
||||
for cmd in (
|
||||
["sh", str(REPO / "tools/dev_mode.sh"), "bogus"],
|
||||
["sh", str(REPO / "tools/dev_mode.sh"), "status", "extra"],
|
||||
["sh", str(REPO / "tools/dev_health.sh"), "bogus"],
|
||||
["sh", str(REPO / "tools/dev_health.sh"), "pre", "extra"],
|
||||
):
|
||||
proc = subprocess.run(cmd, capture_output=True, text=True)
|
||||
self.assertEqual(proc.returncode, 2, f"expected exit 2 for {cmd}, got {proc.returncode}")
|
||||
|
||||
def test_dev_reload_rejects_malformed_and_missing_bdf(self):
|
||||
for bad_bdf in ("", "0000:01:00.0/../../x", "ZZZZ:01:00.0", "0000:ff:1f.7"):
|
||||
env = os.environ.copy()
|
||||
env["NV_RS_DEV_RELOAD_BDF"] = bad_bdf
|
||||
proc = subprocess.run(
|
||||
["sh", str(REPO / "tools/dev_reload.sh")],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
self.assertEqual(proc.returncode, 2, f"expected exit 2 for BDF={bad_bdf!r}")
|
||||
|
||||
|
||||
class TestExtractGv100Firmware(unittest.TestCase):
|
||||
def test_missing_rm_object_gives_clean_error(self):
|
||||
proc = subprocess.run(
|
||||
[sys.executable, str(REPO / "tools/extract_gv100_firmware.py"),
|
||||
"--rm-object", "/nonexistent/nv-kernel.o_binary"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
self.assertNotEqual(proc.returncode, 0)
|
||||
self.assertIn("kernel object not found", proc.stderr)
|
||||
self.assertNotIn("Traceback", proc.stderr)
|
||||
|
||||
def test_legacy_family_check_mode_does_not_write_and_detects_staleness(self):
|
||||
if not STOCK_OBJ.is_file():
|
||||
self.skipTest("580.178.04 nv-kernel.o_binary not present on host")
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
out_gv = Path(td) / "gv100.fw"
|
||||
out_gm = Path(td) / "gm20x.fw"
|
||||
manifest = Path(td) / "gv100.json"
|
||||
|
||||
# --check on missing gm20x.fw must fail and NOT create gm20x.fw
|
||||
proc = subprocess.run(
|
||||
[sys.executable, str(REPO / "tools/extract_gv100_firmware.py"),
|
||||
"--rm-object", str(STOCK_OBJ), "--family", "gm20x",
|
||||
"--out", str(out_gv), "--manifest", str(manifest), "--check"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
self.assertNotEqual(proc.returncode, 0)
|
||||
self.assertFalse(out_gm.exists(), "--check must never write gm20x.fw")
|
||||
|
||||
# Extract gm20x.fw, then --check must pass
|
||||
proc = subprocess.run(
|
||||
[sys.executable, str(REPO / "tools/extract_gv100_firmware.py"),
|
||||
"--rm-object", str(STOCK_OBJ), "--family", "gm20x",
|
||||
"--out", str(out_gv), "--manifest", str(manifest)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
self.assertEqual(proc.returncode, 0, proc.stderr)
|
||||
self.assertTrue(out_gm.is_file())
|
||||
|
||||
proc = subprocess.run(
|
||||
[sys.executable, str(REPO / "tools/extract_gv100_firmware.py"),
|
||||
"--rm-object", str(STOCK_OBJ), "--family", "gm20x",
|
||||
"--out", str(out_gv), "--manifest", str(manifest), "--check"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
self.assertEqual(proc.returncode, 0, proc.stderr)
|
||||
|
||||
# Corrupt one byte -> --check must fail
|
||||
data = bytearray(out_gm.read_bytes())
|
||||
data[-1] ^= 0xff
|
||||
out_gm.write_bytes(bytes(data))
|
||||
proc = subprocess.run(
|
||||
[sys.executable, str(REPO / "tools/extract_gv100_firmware.py"),
|
||||
"--rm-object", str(STOCK_OBJ), "--family", "gm20x",
|
||||
"--out", str(out_gv), "--manifest", str(manifest), "--check"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
self.assertNotEqual(proc.returncode, 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@ -7,15 +7,25 @@
|
||||
# post: the freshly loaded module answers (opens a node, so it runs under a timeout).
|
||||
# Exit 0 = healthy, 1 = stop all GPU work and report to the user, 2 = usage.
|
||||
set -u
|
||||
if [ "$#" -gt 1 ]; then
|
||||
echo "usage: $0 [pre|post]" >&2
|
||||
exit 2
|
||||
fi
|
||||
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
MODE=${1:-pre}
|
||||
case "$MODE" in pre|post) ;; *) echo "usage: $0 [pre|post]" >&2; exit 2 ;; esac
|
||||
BAD=0
|
||||
fail() { echo "FAIL: $*"; BAD=1; }
|
||||
warn() { echo "warn: $*"; }
|
||||
|
||||
TAINT=$(cat /proc/sys/kernel/tainted)
|
||||
[ $((TAINT & 128)) -eq 0 ] || fail "kernel has oopsed (taint $TAINT); reboot is the only clean recovery"
|
||||
[ $((TAINT & 32)) -eq 0 ] || warn "bad page taint (taint $TAINT)"
|
||||
TAINT=$(cat /proc/sys/kernel/tainted 2>/dev/null || true)
|
||||
case "$TAINT" in
|
||||
''|*[!0-9]*) fail "cannot read numeric /proc/sys/kernel/tainted (got '$TAINT')" ;;
|
||||
*)
|
||||
[ $((TAINT & 128)) -eq 0 ] || fail "kernel has oopsed (taint $TAINT); reboot is the only clean recovery"
|
||||
[ $((TAINT & 32)) -eq 0 ] || warn "bad page taint (taint $TAINT)"
|
||||
;;
|
||||
esac
|
||||
|
||||
# nvidia_rs_rt* parks in D state by design; any other D-state nvidia thread is a hang.
|
||||
STUCK=$(ps -eLo pid=,stat=,comm= | awk '$2 ~ /^D/ && $3 ~ /nv_open_q|nvidia|nv_queue|rmmod|insmod/ && $3 !~ /^nvidia_rs_rt/')
|
||||
@ -29,7 +39,7 @@ fi
|
||||
|
||||
sudo -n true 2>/dev/null || fail "passwordless sudo is not available"
|
||||
|
||||
if [ -x tools/dev_mode.sh ] && ! sh tools/dev_mode.sh status 2>/dev/null | grep -q ': on'; then
|
||||
if [ -f "$ROOT/tools/dev_mode.sh" ] && ! sh "$ROOT/tools/dev_mode.sh" status 2>/dev/null | grep -q ': on'; then
|
||||
warn "dev mode is off: desktop processes can pin the module (sh tools/dev_mode.sh on)"
|
||||
fi
|
||||
|
||||
@ -44,10 +54,12 @@ if [ "$MODE" = post ] && [ "$BAD" -eq 0 ]; then
|
||||
trap 'rm -f "$SMI"' EXIT
|
||||
if ! timeout -k 5 30 sudo -n nvidia-smi -L >"$SMI" 2>&1; then
|
||||
fail "nvidia-smi -L failed or timed out (30 s); GSP-RM may be wedged. Do not retry:"
|
||||
cat "$SMI"
|
||||
else
|
||||
cat "$SMI"
|
||||
grep -q '^GPU 0:' "$SMI" || fail "nvidia-smi lists no GPU; runtime init failed (journalctl -k; if -12/ENOMEM: sync; echo 3 > /proc/sys/vm/drop_caches; echo 1 > /proc/sys/vm/compact_memory, then reload)"
|
||||
sudo -n dmesg --level=err,crit,alert,emerg 2>/dev/null | tail -5 | grep -i nvidia_rs && warn "nvidia_rs logged errors above"
|
||||
fi
|
||||
cat "$SMI"
|
||||
grep -q '^GPU 0:' "$SMI" || fail "nvidia-smi lists no GPU; runtime init failed (journalctl -k; if -12/ENOMEM: sync; echo 3 > /proc/sys/vm/drop_caches; echo 1 > /proc/sys/vm/compact_memory, then reload)"
|
||||
sudo -n dmesg --level=err,crit,alert,emerg 2>/dev/null | tail -5 | grep -i nvidia_rs && warn "nvidia_rs logged errors above"
|
||||
fi
|
||||
|
||||
[ "$BAD" -eq 0 ] && echo "health ($MODE): ok"
|
||||
|
||||
@ -7,18 +7,28 @@
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
RULE=/etc/udev/rules.d/62-nvdriver-dev.rules
|
||||
NODES="/sys/class/misc/nvidia-rs-rmapi-ctl /sys/class/misc/nvidia-rs-rmapi-gpu[0-9]* /sys/class/misc/nvidia-rs-uvm"
|
||||
SRC_RULE=packaging/arch/62-nvdriver-dev.rules
|
||||
|
||||
if [ "$#" -gt 1 ]; then
|
||||
echo "usage: $0 on|off|status" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
case "${1:-status}" in
|
||||
on)
|
||||
sudo install -m 644 packaging/arch/62-nvdriver-dev.rules "$RULE"
|
||||
[ -f "$SRC_RULE" ] || { echo "missing udev rule: $SRC_RULE" >&2; exit 1; }
|
||||
sudo install -m 644 "$SRC_RULE" "$RULE"
|
||||
sudo udevadm control --reload
|
||||
echo "development mode on (nodes become root-only at the next module load or boot)"
|
||||
;;
|
||||
off)
|
||||
sudo rm -f "$RULE"
|
||||
sudo udevadm control --reload
|
||||
for n in $NODES; do [ -e "$n" ] && sudo udevadm trigger --action=add "$n"; done
|
||||
for n in /sys/class/misc/nvidia-rs-rmapi-ctl /sys/class/misc/nvidia-rs-rmapi-gpu[0-9]* /sys/class/misc/nvidia-rs-uvm; do
|
||||
if [ -e "$n" ]; then
|
||||
sudo udevadm trigger --action=add "$n"
|
||||
fi
|
||||
done
|
||||
sudo udevadm settle
|
||||
echo "development mode off"
|
||||
;;
|
||||
|
||||
@ -20,9 +20,10 @@ cd "$(dirname "$0")/.." || exit 2
|
||||
# On a multi-GPU or data-center host this script never runs unless that is set deliberately.
|
||||
NV_RS_DEV_RELOAD_BDF=${NV_RS_DEV_RELOAD_BDF:-}
|
||||
case "$NV_RS_DEV_RELOAD_BDF" in
|
||||
*:*:*.*) ;;
|
||||
*) echo "refusing: set NV_RS_DEV_RELOAD_BDF=<domain:bus:dev.fn> (the one GPU this reload may unbind)"; exit 2 ;;
|
||||
[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f]:[0-9a-f][0-9a-f].[0-7]) ;;
|
||||
*) echo "refusing: set NV_RS_DEV_RELOAD_BDF=<lowercase domain:bus:dev.fn> (the one GPU this reload may unbind)" >&2; exit 2 ;;
|
||||
esac
|
||||
[ -d "/sys/bus/pci/devices/$NV_RS_DEV_RELOAD_BDF" ] || { echo "refusing: PCI device $NV_RS_DEV_RELOAD_BDF does not exist" >&2; exit 2; }
|
||||
for d in /sys/bus/pci/drivers/nvidia_rs/*:*:*.*; do
|
||||
[ -e "$d" ] || continue
|
||||
[ "${d##*/}" = "$NV_RS_DEV_RELOAD_BDF" ] || { echo "refusing: nvidia_rs is also bound to ${d##*/}; only $NV_RS_DEV_RELOAD_BDF is allowed"; exit 2; }
|
||||
@ -38,7 +39,7 @@ sh tools/dev_health.sh pre || { echo "health check failed: no reload attempted";
|
||||
|
||||
holders() {
|
||||
for p in /proc/[0-9]*; do
|
||||
if sudo ls -l "$p/fd" 2>/dev/null | grep -q 'nvidia-rs'; then
|
||||
if sudo ls -l "$p/fd" 2>/dev/null | grep -Eq 'nvidia-rs|/dev/nvidia(ctl|[0-9]|-uvm|-modeset)'; then
|
||||
echo " ${p#/proc/} $(cat "$p/comm" 2>/dev/null)"
|
||||
fi
|
||||
done
|
||||
@ -59,7 +60,10 @@ if [ -e /sys/module/nvidia_rs ]; then
|
||||
fi
|
||||
# The standard-path aliases keep the old inodes across a reload; drop them now and rebind after insmod.
|
||||
mountpoint -q /dev/nvidiactl 2>/dev/null && REBIND=1
|
||||
sudo bash tools/bind_dev_nodes.sh --unbind
|
||||
if ! sudo bash tools/bind_dev_nodes.sh --unbind; then
|
||||
echo "failed to unbind /dev/nvidia* node aliases; aborting reload" >&2
|
||||
exit 1
|
||||
fi
|
||||
# Every PCI domain, not only 0000.
|
||||
for d in /sys/bus/pci/drivers/nvidia_rs/*:*:*.*; do
|
||||
[ -e "$d" ] || continue
|
||||
@ -72,6 +76,11 @@ if [ -e /sys/module/nvidia_rs ]; then
|
||||
sudo journalctl -k --no-pager --since "$STAMP" | tail -20
|
||||
exit 1
|
||||
fi
|
||||
if ! wait "$UNBIND" || [ -e "$d" ]; then
|
||||
echo "unbind of ${d##*/} failed; not attempting rmmod or insmod." >&2
|
||||
sudo journalctl -k --no-pager --since "$STAMP" | tail -20
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
sudo rmmod nvidia_rs &
|
||||
RMMOD=$!
|
||||
@ -82,12 +91,15 @@ if [ -e /sys/module/nvidia_rs ]; then
|
||||
sudo journalctl -k --no-pager --since "$STAMP" | tail -20
|
||||
exit 1
|
||||
fi
|
||||
wait "$RMMOD" || true
|
||||
[ -e /sys/module/nvidia_rs ] && { echo "nvidia_rs is still loaded"; exit 1; }
|
||||
fi
|
||||
|
||||
sudo insmod "$KO" "$@" || { echo "insmod failed"; sudo journalctl -k --no-pager --since "$STAMP" | tail -30; exit 1; }
|
||||
sudo udevadm settle
|
||||
[ "$REBIND" -eq 0 ] || sudo bash tools/bind_dev_nodes.sh --bind
|
||||
if [ "$REBIND" -ne 0 ]; then
|
||||
sudo bash tools/bind_dev_nodes.sh --bind || { echo "failed to rebind /dev/nvidia* node aliases" >&2; exit 1; }
|
||||
fi
|
||||
sudo journalctl -k --no-pager --since "$STAMP" -g 'nvidia_rs' | grep -v 'TRACE' | tail -40
|
||||
ls -l /dev/nvidiactl /dev/nvidia0 /dev/nvidia-uvm 2>&1
|
||||
sh tools/dev_health.sh post
|
||||
|
||||
@ -24,8 +24,10 @@ selected directly.
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import tempfile
|
||||
import zlib
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
@ -95,130 +97,59 @@ LEGACY_FAMILY_BUNDLES = {
|
||||
"gp10x": (0x1143150, 0x1143308, 0x1143768),
|
||||
}
|
||||
|
||||
parser = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawTextHelpFormatter)
|
||||
parser.add_argument("--rm-object", type=Path, default=DEFAULT_OBJECT)
|
||||
parser.add_argument("--family", choices=("gv100", "gm20x", "gp100", "gp10x", "all"),
|
||||
default="gv100",
|
||||
help="target firmware family to extract (default: gv100; 'all' extracts gv100+gm20x+gp100+gp10x)")
|
||||
parser.add_argument("--out", type=Path,
|
||||
default=ROOT / "target/firmware/nvidia-rs/580.178.04/gv100.fw")
|
||||
parser.add_argument("--manifest", type=Path,
|
||||
default=ROOT / "reports/gv100-firmware-pack.json")
|
||||
parser.add_argument("--check", action="store_true",
|
||||
help="fail if the existing container or manifest would change")
|
||||
arguments = parser.parse_args()
|
||||
|
||||
source = arguments.rm_object.read_bytes()
|
||||
if hashlib.sha256(source).hexdigest() != DIGEST:
|
||||
raise SystemExit("the kernel object is not the 580.178.04 build this list was recovered from")
|
||||
e_shoff, = struct.unpack_from("<Q", source, 40)
|
||||
e_shentsize, e_shnum, e_shstrndx = struct.unpack_from("<HHH", source, 58)
|
||||
def _sh(idx):
|
||||
return struct.unpack_from("<IIQQQQIIQQ", source, e_shoff + idx * e_shentsize)
|
||||
shstr_off = _sh(e_shstrndx)[4]
|
||||
secs = {}
|
||||
for idx in range(e_shnum):
|
||||
s = _sh(idx)
|
||||
end = source.index(b"\0", shstr_off + s[0])
|
||||
secs[source[shstr_off + s[0]:end].decode()] = (idx, s)
|
||||
_, symtab = secs[".symtab"]
|
||||
sym_off, sym_ent = symtab[4], symtab[9]
|
||||
regions = {}
|
||||
for name, base in ((".data", 0x00f7e890), (".rodata", 0x0111d660)):
|
||||
idx, s = secs[name]
|
||||
regions[idx] = (base, source[s[4]:s[4] + s[5]])
|
||||
pointers = {}
|
||||
for rname, tname in ((".rela.data", ".data"), (".rela.rodata", ".rodata")):
|
||||
_, rs = secs[rname]
|
||||
tidx, _ = secs[tname]
|
||||
tbase = regions[tidx][0]
|
||||
for off in range(rs[4], rs[4] + rs[5], rs[9]):
|
||||
r_off, r_info, r_add = struct.unpack_from("<QQq", source, off)
|
||||
if (r_info & 0xffffffff) == 1:
|
||||
r_sym = r_info >> 32
|
||||
_, _, _, st_shndx, st_val, _ = struct.unpack_from("<IBBHQQ", source, sym_off + r_sym * sym_ent)
|
||||
if st_shndx in regions:
|
||||
pointers[tbase + r_off] = regions[st_shndx][0] + st_val + r_add
|
||||
def _atomic_write_bytes(path: Path, data: bytes) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd, tmp = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as fh:
|
||||
fh.write(data)
|
||||
fh.flush()
|
||||
os.fsync(fh.fileno())
|
||||
os.replace(tmp, path)
|
||||
except BaseException:
|
||||
try:
|
||||
os.unlink(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
def read(address, length):
|
||||
for base, data in regions.values():
|
||||
if base <= address and address + length <= base + len(data):
|
||||
return bytes(data[address - base:address - base + length])
|
||||
raise SystemExit(f"{address:#x}+{length:#x} is outside the object's data sections")
|
||||
def _parse_elf_regions(source: bytes):
|
||||
e_shoff, = struct.unpack_from("<Q", source, 40)
|
||||
e_shentsize, e_shnum, e_shstrndx = struct.unpack_from("<HHH", source, 58)
|
||||
|
||||
def _sh(idx):
|
||||
return struct.unpack_from("<IIQQQQIIQQ", source, e_shoff + idx * e_shentsize)
|
||||
|
||||
def word(address):
|
||||
return struct.unpack("<I", read(address, 4))[0]
|
||||
shstr_off = _sh(e_shstrndx)[4]
|
||||
secs = {}
|
||||
for idx in range(e_shnum):
|
||||
s = _sh(idx)
|
||||
end = source.index(b"\0", shstr_off + s[0])
|
||||
secs[source[shstr_off + s[0]:end].decode()] = (idx, s)
|
||||
_, symtab = secs[".symtab"]
|
||||
sym_off, sym_ent = symtab[4], symtab[9]
|
||||
regions = {}
|
||||
for name, base in ((".data", 0x00f7e890), (".rodata", 0x0111d660)):
|
||||
idx, s = secs[name]
|
||||
regions[idx] = (base, source[s[4]:s[4] + s[5]])
|
||||
pointers = {}
|
||||
for rname, tname in ((".rela.data", ".data"), (".rela.rodata", ".rodata")):
|
||||
_, rs = secs[rname]
|
||||
tidx, _ = secs[tname]
|
||||
tbase = regions[tidx][0]
|
||||
for off in range(rs[4], rs[4] + rs[5], rs[9]):
|
||||
r_off, r_info, r_add = struct.unpack_from("<QQq", source, off)
|
||||
if (r_info & 0xffffffff) == 1:
|
||||
r_sym = r_info >> 32
|
||||
_, _, _, st_shndx, st_val, _ = struct.unpack_from(
|
||||
"<IBBHQQ", source, sym_off + r_sym * sym_ent
|
||||
)
|
||||
if st_shndx in regions:
|
||||
pointers[tbase + r_off] = regions[st_shndx][0] + st_val + r_add
|
||||
return regions, pointers
|
||||
|
||||
|
||||
def descriptor(offset, bundle=0, tag=0):
|
||||
decoded_size, stored_bytes = word(offset), word(offset + 4)
|
||||
flags = word(offset + 0x10)
|
||||
stored = read(pointers[offset + 8], stored_bytes)
|
||||
if flags & 1:
|
||||
inflater = zlib.decompressobj(-15)
|
||||
decoded = inflater.decompress(stored)
|
||||
consumed = stored_bytes - len(inflater.unused_data)
|
||||
else:
|
||||
decoded, consumed = stored, stored_bytes
|
||||
# The original pads primary outputs to 256 bytes; only the prefix is produced here.
|
||||
if len(decoded) > decoded_size:
|
||||
raise SystemExit(f"descriptor {offset:#x} decodes past its declared size")
|
||||
return {"descriptor": offset, "bundle": bundle, "tag": tag, "decoded_size": decoded_size,
|
||||
"stored_bytes": stored_bytes, "flags": flags, "stored": stored,
|
||||
"consumed": consumed, "produced": len(decoded),
|
||||
"decoded_sha256": hashlib.sha256(decoded).hexdigest()}
|
||||
|
||||
|
||||
records = []
|
||||
seen = {}
|
||||
for bundle in BUNDLES:
|
||||
for index in range(word(bundle)):
|
||||
entry = bundle + 8 + 16 * index
|
||||
record = descriptor(pointers[entry + 8], bundle, word(entry))
|
||||
records.append(record)
|
||||
seen[record["descriptor"]] = record
|
||||
for offset in DIRECT:
|
||||
if offset not in seen:
|
||||
records.append(descriptor(offset))
|
||||
seen[offset] = records[-1]
|
||||
for bundle in LATER_BUNDLES:
|
||||
for index in range(word(bundle)):
|
||||
entry = bundle + 8 + 16 * index
|
||||
if pointers[entry + 8] in seen:
|
||||
raise SystemExit(f"bundle {bundle:#x} repeats descriptor {pointers[entry + 8]:#x}")
|
||||
records.append(descriptor(pointers[entry + 8], bundle, word(entry)))
|
||||
seen[records[-1]["descriptor"]] = records[-1]
|
||||
for offset in LATER_DIRECT:
|
||||
if offset in seen:
|
||||
raise SystemExit(f"descriptor {offset:#x} is already selected")
|
||||
records.append(descriptor(offset))
|
||||
seen[offset] = records[-1]
|
||||
|
||||
for offset in UNLOAD_DIRECT:
|
||||
if offset in seen:
|
||||
raise SystemExit(f"descriptor {offset:#x} is already selected")
|
||||
records.append(descriptor(offset))
|
||||
seen[offset] = records[-1]
|
||||
for offset in MSENC_DIRECT:
|
||||
if offset in seen:
|
||||
raise SystemExit(f"descriptor {offset:#x} is already selected")
|
||||
records.append(descriptor(offset))
|
||||
seen[offset] = records[-1]
|
||||
for bundle in MINION_BUNDLES:
|
||||
for index in range(word(bundle)):
|
||||
entry = bundle + 8 + 16 * index
|
||||
if pointers[entry + 8] in seen:
|
||||
raise SystemExit(f"bundle {bundle:#x} repeats descriptor {pointers[entry + 8]:#x}")
|
||||
records.append(descriptor(pointers[entry + 8], bundle, word(entry)))
|
||||
seen[records[-1]["descriptor"]] = records[-1]
|
||||
if [pointers[0x11432e0 + 8 + 16 * index + 8] for index in range(word(0x11432e0))] != [
|
||||
0x114fb00, 0x114fb18] or [word(0x11432e0 + 8 + 16 * index) for index in range(2)] != [
|
||||
0x12, 0x23]:
|
||||
raise SystemExit("bundle 0x11432e0 is not the PMU boot loader pair")
|
||||
|
||||
def pack_container(recs):
|
||||
hdr = 48 + 64 * len(recs)
|
||||
pay = bytearray()
|
||||
@ -236,76 +167,186 @@ def pack_container(recs):
|
||||
+ bytes(tbl) + bytes(pay))
|
||||
|
||||
|
||||
container = pack_container(records)
|
||||
manifest = {
|
||||
"source_sha256": DIGEST,
|
||||
"container": "nvidia-rs/580.178.04/gv100.fw",
|
||||
"container_bytes": len(container),
|
||||
"container_sha256": hashlib.sha256(container).hexdigest(),
|
||||
"previous_container": {
|
||||
"records": 59, "bytes": 93476,
|
||||
"sha256": "d0cc11446bf4c2422a47845216535f001fa51b868f541d54d9fbd3fbf28cb4e6",
|
||||
"note": "Container before the NVDEC HS (both bundles), NVDEC LS, PMU LS and SEC2 LS records were "
|
||||
"appended. Its 59 records are the first 59 of this one with the same "
|
||||
"descriptor, bundle, tag, sizes, flags and stored hashes; only their payload "
|
||||
"offsets moved because the record table grew.",
|
||||
},
|
||||
"container_of_77_records": {
|
||||
"records": 77, "bytes": 407461,
|
||||
"sha256": "e4609de4e540648ac2c008d953229f952c9fdae984fb4dc11a76e0e5afa8d8f3",
|
||||
"note": "Container before the NVDEC LS descriptor, the NVDEC LS signature and the PMU LS "
|
||||
"signature were appended for the WPR image builder. Its 77 records are the "
|
||||
"first 77 of this one, unchanged except for their payload offsets.",
|
||||
},
|
||||
"container_of_80_records": {
|
||||
"records": 80, "bytes": 408216,
|
||||
"sha256": "949c532bc7579b7c1b2c57741f34019fea48967b4456f2a3a6aae0b6b5dd741a",
|
||||
"note": "Container before the header of the PMU HS boot loader (descriptor 0x114fb00) "
|
||||
"was appended for the ACR unload. Its 80 records are the first 80 of this one, "
|
||||
"unchanged except for their payload offsets.",
|
||||
},
|
||||
"scope": "Stored bytes of the selected packed firmware descriptors, copied unchanged from "
|
||||
"the original kernel object's read-only data. Payloads remain packed and their "
|
||||
"authenticity is established only by the GPU.",
|
||||
"records": [{key: (f"{value:#x}" if key in ("descriptor", "bundle", "tag", "flags") else value)
|
||||
for key, value in record.items() if key != "stored"}
|
||||
| {"stored_sha256": hashlib.sha256(record["stored"]).hexdigest()}
|
||||
for record in records],
|
||||
}
|
||||
manifest_text = json.dumps(manifest, indent=1) + "\n"
|
||||
def build_legacy_pack(family_name):
|
||||
fam_records = []
|
||||
fam_seen = {}
|
||||
for bundle in LEGACY_FAMILY_BUNDLES[family_name]:
|
||||
def parse_args(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawTextHelpFormatter)
|
||||
parser.add_argument("--rm-object", type=Path, default=DEFAULT_OBJECT)
|
||||
parser.add_argument("--family", choices=("gv100", "gm20x", "gp100", "gp10x", "all"),
|
||||
default="gv100",
|
||||
help="target firmware family to extract (default: gv100; 'all' extracts gv100+gm20x+gp100+gp10x)")
|
||||
parser.add_argument("--out", type=Path,
|
||||
default=ROOT / "target/firmware/nvidia-rs/580.178.04/gv100.fw")
|
||||
parser.add_argument("--manifest", type=Path,
|
||||
default=ROOT / "reports/gv100-firmware-pack.json")
|
||||
parser.add_argument("--check", action="store_true",
|
||||
help="fail if the existing container or manifest would change")
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
arguments = parse_args(argv)
|
||||
if not arguments.rm_object.is_file():
|
||||
raise SystemExit(
|
||||
f"kernel object not found: {arguments.rm_object}\n"
|
||||
"Pass --rm-object /path/to/580.178.04/nvidia/nv-kernel.o_binary"
|
||||
)
|
||||
source = arguments.rm_object.read_bytes()
|
||||
if hashlib.sha256(source).hexdigest() != DIGEST:
|
||||
raise SystemExit("the kernel object is not the 580.178.04 build this list was recovered from")
|
||||
regions, pointers = _parse_elf_regions(source)
|
||||
|
||||
def read(address, length):
|
||||
for base, data in regions.values():
|
||||
if base <= address and address + length <= base + len(data):
|
||||
return bytes(data[address - base:address - base + length])
|
||||
raise SystemExit(f"{address:#x}+{length:#x} is outside the object's data sections")
|
||||
|
||||
def word(address):
|
||||
return struct.unpack("<I", read(address, 4))[0]
|
||||
|
||||
def descriptor(offset, bundle=0, tag=0):
|
||||
decoded_size, stored_bytes = word(offset), word(offset + 4)
|
||||
flags = word(offset + 0x10)
|
||||
stored = read(pointers[offset + 8], stored_bytes)
|
||||
if flags & 1:
|
||||
inflater = zlib.decompressobj(-15)
|
||||
decoded = inflater.decompress(stored)
|
||||
consumed = stored_bytes - len(inflater.unused_data)
|
||||
else:
|
||||
decoded, consumed = stored, stored_bytes
|
||||
# The original pads primary outputs to 256 bytes; only the prefix is produced here.
|
||||
if len(decoded) > decoded_size:
|
||||
raise SystemExit(f"descriptor {offset:#x} decodes past its declared size")
|
||||
return {"descriptor": offset, "bundle": bundle, "tag": tag, "decoded_size": decoded_size,
|
||||
"stored_bytes": stored_bytes, "flags": flags, "stored": stored,
|
||||
"consumed": consumed, "produced": len(decoded),
|
||||
"decoded_sha256": hashlib.sha256(decoded).hexdigest()}
|
||||
|
||||
records = []
|
||||
seen = {}
|
||||
for bundle in BUNDLES:
|
||||
for index in range(word(bundle)):
|
||||
entry = bundle + 8 + 16 * index
|
||||
desc_addr = pointers[entry + 8]
|
||||
if desc_addr in fam_seen:
|
||||
continue
|
||||
rec = descriptor(desc_addr, bundle, word(entry))
|
||||
fam_records.append(rec)
|
||||
fam_seen[desc_addr] = rec
|
||||
blob = pack_container(fam_records)
|
||||
out_path = arguments.out.parent / f"{family_name}.fw"
|
||||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
out_path.write_bytes(blob)
|
||||
print(f"{family_name}.fw: {len(fam_records)} records, {len(blob)} bytes, "
|
||||
f"sha256 {hashlib.sha256(blob).hexdigest()}")
|
||||
record = descriptor(pointers[entry + 8], bundle, word(entry))
|
||||
records.append(record)
|
||||
seen[record["descriptor"]] = record
|
||||
for offset in DIRECT:
|
||||
if offset not in seen:
|
||||
records.append(descriptor(offset))
|
||||
seen[offset] = records[-1]
|
||||
for bundle in LATER_BUNDLES:
|
||||
for index in range(word(bundle)):
|
||||
entry = bundle + 8 + 16 * index
|
||||
if pointers[entry + 8] in seen:
|
||||
raise SystemExit(f"bundle {bundle:#x} repeats descriptor {pointers[entry + 8]:#x}")
|
||||
records.append(descriptor(pointers[entry + 8], bundle, word(entry)))
|
||||
seen[records[-1]["descriptor"]] = records[-1]
|
||||
for offset in LATER_DIRECT:
|
||||
if offset in seen:
|
||||
raise SystemExit(f"descriptor {offset:#x} is already selected")
|
||||
records.append(descriptor(offset))
|
||||
seen[offset] = records[-1]
|
||||
|
||||
for offset in UNLOAD_DIRECT:
|
||||
if offset in seen:
|
||||
raise SystemExit(f"descriptor {offset:#x} is already selected")
|
||||
records.append(descriptor(offset))
|
||||
seen[offset] = records[-1]
|
||||
for offset in MSENC_DIRECT:
|
||||
if offset in seen:
|
||||
raise SystemExit(f"descriptor {offset:#x} is already selected")
|
||||
records.append(descriptor(offset))
|
||||
seen[offset] = records[-1]
|
||||
for bundle in MINION_BUNDLES:
|
||||
for index in range(word(bundle)):
|
||||
entry = bundle + 8 + 16 * index
|
||||
if pointers[entry + 8] in seen:
|
||||
raise SystemExit(f"bundle {bundle:#x} repeats descriptor {pointers[entry + 8]:#x}")
|
||||
records.append(descriptor(pointers[entry + 8], bundle, word(entry)))
|
||||
seen[records[-1]["descriptor"]] = records[-1]
|
||||
if [pointers[0x11432e0 + 8 + 16 * index + 8] for index in range(word(0x11432e0))] != [
|
||||
0x114fb00, 0x114fb18] or [word(0x11432e0 + 8 + 16 * index) for index in range(2)] != [
|
||||
0x12, 0x23]:
|
||||
raise SystemExit("bundle 0x11432e0 is not the PMU boot loader pair")
|
||||
|
||||
container = pack_container(records)
|
||||
manifest = {
|
||||
"source_sha256": DIGEST,
|
||||
"container": "nvidia-rs/580.178.04/gv100.fw",
|
||||
"container_bytes": len(container),
|
||||
"container_sha256": hashlib.sha256(container).hexdigest(),
|
||||
"previous_container": {
|
||||
"records": 59, "bytes": 93476,
|
||||
"sha256": "d0cc11446bf4c2422a47845216535f001fa51b868f541d54d9fbd3fbf28cb4e6",
|
||||
"note": "Container before the NVDEC HS (both bundles), NVDEC LS, PMU LS and SEC2 LS records were "
|
||||
"appended. Its 59 records are the first 59 of this one with the same "
|
||||
"descriptor, bundle, tag, sizes, flags and stored hashes; only their payload "
|
||||
"offsets moved because the record table grew.",
|
||||
},
|
||||
"container_of_77_records": {
|
||||
"records": 77, "bytes": 407461,
|
||||
"sha256": "e4609de4e540648ac2c008d953229f952c9fdae984fb4dc11a76e0e5afa8d8f3",
|
||||
"note": "Container before the NVDEC LS descriptor, the NVDEC LS signature and the PMU LS "
|
||||
"signature were appended for the WPR image builder. Its 77 records are the "
|
||||
"first 77 of this one, unchanged except for their payload offsets.",
|
||||
},
|
||||
"container_of_80_records": {
|
||||
"records": 80, "bytes": 408216,
|
||||
"sha256": "949c532bc7579b7c1b2c57741f34019fea48967b4456f2a3a6aae0b6b5dd741a",
|
||||
"note": "Container before the header of the PMU HS boot loader (descriptor 0x114fb00) "
|
||||
"was appended for the ACR unload. Its 80 records are the first 80 of this one, "
|
||||
"unchanged except for their payload offsets.",
|
||||
},
|
||||
"scope": "Stored bytes of the selected packed firmware descriptors, copied unchanged from "
|
||||
"the original kernel object's read-only data. Payloads remain packed and their "
|
||||
"authenticity is established only by the GPU.",
|
||||
"records": [{key: (f"{value:#x}" if key in ("descriptor", "bundle", "tag", "flags") else value)
|
||||
for key, value in record.items() if key != "stored"}
|
||||
| {"stored_sha256": hashlib.sha256(record["stored"]).hexdigest()}
|
||||
for record in records],
|
||||
}
|
||||
manifest_text = json.dumps(manifest, indent=1) + "\n"
|
||||
|
||||
def build_legacy_pack(family_name):
|
||||
fam_records = []
|
||||
fam_seen = {}
|
||||
for bundle in LEGACY_FAMILY_BUNDLES[family_name]:
|
||||
for index in range(word(bundle)):
|
||||
entry = bundle + 8 + 16 * index
|
||||
desc_addr = pointers[entry + 8]
|
||||
if desc_addr in fam_seen:
|
||||
continue
|
||||
rec = descriptor(desc_addr, bundle, word(entry))
|
||||
fam_records.append(rec)
|
||||
fam_seen[desc_addr] = rec
|
||||
blob = pack_container(fam_records)
|
||||
out_path = arguments.out.parent / f"{family_name}.fw"
|
||||
if arguments.check:
|
||||
if not out_path.exists() or out_path.read_bytes() != blob:
|
||||
raise SystemExit(f"the {family_name}.fw firmware container is missing or stale: {out_path}")
|
||||
else:
|
||||
_atomic_write_bytes(out_path, blob)
|
||||
print(f"{family_name}.fw: {len(fam_records)} records, {len(blob)} bytes, "
|
||||
f"sha256 {hashlib.sha256(blob).hexdigest()}")
|
||||
|
||||
if arguments.family in ("gv100", "all"):
|
||||
if arguments.check:
|
||||
if (not arguments.out.exists() or arguments.out.read_bytes() != container
|
||||
or not arguments.manifest.exists()
|
||||
or arguments.manifest.read_text() != manifest_text):
|
||||
raise SystemExit("the firmware container or manifest is stale")
|
||||
else:
|
||||
_atomic_write_bytes(arguments.out, container)
|
||||
_atomic_write_bytes(arguments.manifest, manifest_text.encode("utf-8"))
|
||||
print(f"{len(records)} records, {len(container)} bytes, sha256 {manifest['container_sha256']}")
|
||||
|
||||
if arguments.family == "all":
|
||||
for fam in ("gm20x", "gp100", "gp10x"):
|
||||
build_legacy_pack(fam)
|
||||
elif arguments.family in LEGACY_FAMILY_BUNDLES:
|
||||
build_legacy_pack(arguments.family)
|
||||
return 0
|
||||
|
||||
|
||||
if arguments.family in ("gv100", "all"):
|
||||
if arguments.check:
|
||||
if (not arguments.out.exists() or arguments.out.read_bytes() != container
|
||||
or arguments.manifest.read_text() != manifest_text):
|
||||
raise SystemExit("the firmware container or manifest is stale")
|
||||
else:
|
||||
arguments.out.parent.mkdir(parents=True, exist_ok=True)
|
||||
arguments.out.write_bytes(container)
|
||||
arguments.manifest.write_text(manifest_text)
|
||||
print(f"{len(records)} records, {len(container)} bytes, sha256 {manifest['container_sha256']}")
|
||||
|
||||
if arguments.family == "all":
|
||||
for fam in ("gm20x", "gp100", "gp10x"):
|
||||
build_legacy_pack(fam)
|
||||
elif arguments.family in LEGACY_FAMILY_BUNDLES:
|
||||
build_legacy_pack(arguments.family)
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
|
||||
Reference in New Issue
Block a user