#!/usr/bin/env python3 """GA100 CMP 170HX FF calculator. Reads the fuse bank (read-only), decodes the current floorsweep / SM-speed / devid state, and computes the FF records needed to reach a known-good target. Emits a plan table and a Glitch_Journal-style reg-command burn sequence. READ-ONLY. This tool issues only CMD_READ (0x1) against the fuse controller to read rows, and plain MMIO reads for option registers. It never writes FUSEWDATA and never issues CMD_WRITE (0x2). It does not burn. It writes a per-card text file ff_calc_.txt that the burn tool ingests (keying off the FF-TABLE-BEGIN/END markers). Recipes (known-good target sets): smspeed SM-speed dividers -> FULL (chain 2, words 0x04E/0x04F) memory FBP/FBPA/FBIO/ROP_L2 -> _DEFECTIVE (recover swept-but-good FB) shaders GPC/TPC/PES -> _DEFECTIVE + RECONFIG clear pcie clear Gen3/Gen4/boot gen locks -> unlock PCIe speed (chain 2) nvlink clear OPT_NVLINK_DISABLE -> _DEFECTIVE (inert without U11 bridge mod) devid DEVIDA -> value given by --devid all memory + shaders + smspeed + pcie (+ devid if --devid given) Target for every floorsweep field is that field's own live _DEFECTIVE mask, so genuinely-defective units stay disabled and only swept-good ones come back. Usage: sudo python3 ff_calc.py --recipe all --devid 0x20B5 sudo python3 ff_calc.py --recipe smspeed --emit-journal python3 ff_calc.py --recipe memory --rows ffrows.txt # offline chain """ import argparse import mmap import os import struct import sys # ---- fuse controller registers ------------------------------------------- FUSECTRL, FUSEADDR, FUSERDATA, FUSEWDATA = 0x820000, 0x820004, 0x820008, 0x82000C FUSEDEBUG = 0x820060 CMD_READ, STATE_IDLE = 0x1, 4 BAR0_SPAN = 0x00830000 # ---- FF pool / IFF geometry ---------------------------------------------- FF_FIRST_RECORD_ROW = 0x0DE # records begin here IFF_WINDOW_LO = 0x1E8 # stock IFF stream — never allocate at/after this ROW_SCAN_LAST = 0x1E7 # ---- verified field map --------------------------------------------------- # name -> (chain, bit, width, defective_reg_or_None) # positions verified against live registers on card 6227ae53421c4e47 and the # 10g die; see FF/ff_map_chain_vs_register.md. FIELDS = { "fbio_disable": (1, 83, 24, 0x8205D4), "fbpa_disable": (1, 107, 24, 0x8205D0), "gpc_disable": (1, 131, 8, 0x8205C4), "pes_disable": (1, 251, 24, 0x820698), "fbp_disable": (1, 307, 12, 0x8205CC), "rop_l2_disable": (1, 319, 24, 0x8205E8), "nvlink_disable": (1, 368, 3, 0x82068C), "sys_pipe_disable": (1, 372, 8, 0x8203AC), # SM-speed: one 24-bit field = word 0x04E (all) + word 0x04F low byte. # target 0 => FULL on all 8 pipes; 0x04F high byte preserved by the overlay. "sm_speed": (2, 1248, 24, None), "devida": (2, 593, 16, None), # PCIe gen locks (target 0 = unlock). 1-bit fields; overlay preserves the # rest of each shared block (other MAGIC/boot/trim bits). "disable_gen3_speed": (2, 633, 1, None), # word 0x027 bit 9 (user-confirmed) "pcie_magic_gen4_dis": (2, 755, 1, None), # MAGIC_BITS_D[25], word 0x02F bit 3 "pcie_boot_gen23_dis": (2, 790, 1, None), # word 0x031 bit 6 "pcie_boot_gen3_dis": (2, 791, 1, None), # word 0x031 bit 7 } PCIE_FIELDS = ["disable_gen3_speed", "pcie_magic_gen4_dis", "pcie_boot_gen23_dis", "pcie_boot_gen3_dis"] for _i in range(8): FIELDS["tpc_gpc%d_disable" % _i] = (1, 187 + 8 * _i, 8, [0x8205C8, 0x820508, 0x82050C, 0x820514, 0x820564, 0x8205AC, 0x820B84, 0x820B80][_i]) FIELDS["tpc_gpc%d_reconfig" % _i] = (1, 392 + 8 * _i, 8, None) FLOORSWEEP_MEM = ["fbp_disable", "fbpa_disable", "fbio_disable", "rop_l2_disable"] FLOORSWEEP_SHADER = (["gpc_disable", "pes_disable"] + ["tpc_gpc%d_disable" % i for i in range(8)] + ["tpc_gpc%d_reconfig" % i for i in range(8)]) DISPLAY_DEF = { # live option-word status regs for the state summary "GPC_DISABLE": 0x820C1C, "FBP_DISABLE": 0x820D38, "FBPA_DISABLE": 0x820C18, "FBIO_DISABLE": 0x820C14, } # ---- bank access ---------------------------------------------------------- class Bank: """Read-only fuse bank. CMD_READ rows + MMIO option regs. Never burns.""" def __init__(self, bdf): self.path = "/sys/bus/pci/devices/%s/resource0" % bdf self.fd = os.open(self.path, os.O_RDWR | os.O_SYNC) self.mm = mmap.mmap(self.fd, min(os.stat(self.path).st_size, BAR0_SPAN), mmap.MAP_SHARED, mmap.PROT_READ | mmap.PROT_WRITE) b0 = self.rd(0) if b0 in (0, 0xFFFFFFFF) or (b0 & 0xFFFF0000) == 0xBADF0000: raise SystemExit("PMC_BOOT_0=0x%08x: BAR0 not accessible / asleep" % b0) def rd(self, off): return struct.unpack_from("> 16) & 0x1F) == STATE_IDLE and (self.rd(FUSECTRL) & 3) == 0 def read_rows(self, first=0, last=ROW_SCAN_LAST): if self.rd(FUSEDEBUG) != 0 or not self._idle(): raise SystemExit("fuse controller not idle (FUSECTRL=0x%08x FUSEDEBUG=0x%08x); " "run on an idle card" % (self.rd(FUSECTRL), self.rd(FUSEDEBUG))) orig = self.rd(FUSEADDR) rows = {} try: for r in range(first, last + 1): self._wr_cmd(FUSEADDR, r) self._wr_cmd(FUSECTRL, CMD_READ) for _ in range(100000): if self._idle(): break else: raise SystemExit("CMD_READ timeout at row 0x%x" % r) rows[r] = self.rd(FUSERDATA) finally: self._wr_cmd(FUSEADDR, orig) return rows def close(self): self.mm.close(); os.close(self.fd) def rows_from_file(path): """Parse ffrows.txt (' ') or a hexdump .md ('0xRRR | w w ...').""" import re rows = {} for ln in open(path, encoding="utf-8", errors="replace"): s = ln.strip() m = re.match(r"^0x([0-9A-Fa-f]{3})\s*\|\s*(.*)$", s) if m: base = int(m.group(1), 16) for i, w in enumerate(m.group(2).split()): if re.match(r"^[0-9A-Fa-f]{8}$", w): rows[base + i] = int(w, 16) continue if s.startswith("#") or not s: continue p = s.split() if len(p) >= 2: try: rows[int(p[0], 0)] = int(p[1], 0) except ValueError: pass return rows # ---- chain math ----------------------------------------------------------- def replay(rows): """{row: word} -> {chain: {offset: data16}} last-write-wins over ascending rows.""" blocks = {} for r in sorted(rows): w = rows[r] if w == 0 or (w >> 5) & 1: # blank or IFF-bit set continue blocks.setdefault(w & 0x1F, {})[(w >> 6) & 0x3FF] = (w >> 16) & 0xFFFF return blocks def owner_rows(rows): """highest row that currently writes each (chain, offset).""" own = {} for r in sorted(rows): w = rows[r] if w == 0 or (w >> 5) & 1: continue own[(w & 0x1F, (w >> 6) & 0x3FF)] = r return own def get_field(blocks, chain, bit, width): v = 0 cb = blocks.get(chain, {}) for i in range(width): b = bit + i v |= ((cb.get(b // 16, 0) >> (b % 16)) & 1) << i return v def first_free_row(rows): used = [r for r in range(FF_FIRST_RECORD_ROW, IFF_WINDOW_LO) if rows.get(r, 0) != 0] row = (max(used) + 1) if used else FF_FIRST_RECORD_ROW if row >= IFF_WINDOW_LO: raise SystemExit("no free FF rows below the IFF window (0x%X)" % IFF_WINDOW_LO) return row # ---- planner -------------------------------------------------------------- def encode(chain, offset, data): return ((data & 0xFFFF) << 16) | ((offset & 0x3FF) << 6) | (chain & 0x1F) def build_plan(rows, defmasks, targets): """targets: {field: value}. Returns list of record dicts + per-field notes.""" blocks = replay(rows) own = owner_rows(rows) pending = {c: dict(b) for c, b in blocks.items()} # mutated copy touched_by = {} # (chain, offset) -> set(fields) for field, tgt in targets.items(): chain, bit, width, _ = FIELDS[field] for i in range(width): b = bit + i off = b // 16 cur = pending.setdefault(chain, {}).get(off, 0) bitval = (tgt >> i) & 1 pending[chain][off] = (cur & ~(1 << (b % 16))) | (bitval << (b % 16)) touched_by.setdefault((chain, off), set()).add(field) records = [] for chain in sorted(pending): for off in sorted(pending[chain]): new = pending[chain][off] old = blocks.get(chain, {}).get(off, 0) if new == old: continue fields = sorted(touched_by.get((chain, off), set())) # target_mask = every bit in this block owned by a TARGETED field. target_mask = 0 for field in fields: fc, fb, fw, _ = FIELDS[field] for i in range(fw): b = fb + i if b // 16 == off: target_mask |= 1 << (b % 16) foreign_mask = ~target_mask & 0xFFFF # HARD GUARD: a record may only flip bits that belong to a targeted # field. Any other change would corrupt a trim or an untargeted # neighbour (e.g. the 0x04F SM-speed high-byte trim, or DEVIDB in # the DEVIDA block). This is computed from the live block, so the # preserved value is this die's own data. if (old ^ new) & foreign_mask: raise SystemExit( "INTERNAL ERROR: record for %s at chain %d/0x%03X would change " "non-target bits (old=0x%04X new=0x%04X foreign_mask=0x%04X)" % (fields, chain, off, old, new, foreign_mask)) records.append({ "chain": chain, "offset": off, "old": old, "new": new, "record": encode(chain, off, new), "supersedes": own.get((chain, off)), "fields": fields, "preserved": old & foreign_mask, # this die's non-target data carried through "foreign_mask": foreign_mask, }) # assign rows ascending from the first free slot row = first_free_row(rows) for rec in records: rec["row"] = row row += 1 return records def resolve_targets(recipe, defmasks, devid): tgt = {} def deff(field): a = FIELDS[field][3] return defmasks[field] want_mem = recipe in ("memory", "all") want_shader = recipe in ("shaders", "all") want_speed = recipe in ("smspeed", "all") want_pcie = recipe in ("pcie", "all") want_nvlink = recipe == "nvlink" # not in 'all': inert without the U11 bridge mod if want_mem: for f in FLOORSWEEP_MEM: tgt[f] = defmasks[f] if want_shader: for f in ["gpc_disable", "pes_disable"] + ["tpc_gpc%d_disable" % i for i in range(8)]: tgt[f] = defmasks[f] for i in range(8): tgt["tpc_gpc%d_reconfig" % i] = 0 if want_speed: tgt["sm_speed"] = 0 if want_pcie: for f in PCIE_FIELDS: tgt[f] = 0 # clear each gen lock to unlock PCIe Gen3/Gen4 if want_nvlink: tgt["nvlink_disable"] = defmasks["nvlink_disable"] # keep any defective lane off if recipe == "devid" or (recipe == "all" and devid is not None): if devid is None: raise SystemExit("recipe 'devid' needs --devid ") tgt["devida"] = devid return tgt # ---- state summary -------------------------------------------------------- def popcount(v): return bin(v).count("1") GIB_PER_FBP = 8 # 8 GiB/FBP for the 8GB-HBM-stack SKU (this card: 64 GiB @ 8 FBP) DEVID_NAMES = {0x20B5: "A100 80GB PCIe", 0x20B0: "A100-SXM4-40GB", 0x20B2: "A100-SXM4-80GB", 0x20F1: "A100 40GB PCIe", 0x20C2: "CMP 170HX", 0x2082: "CMP 170HX 10GB"} def _sm_tpc(gpc_mask, tpc_masks): """(TPC, SM) active given a GPC-disable mask and per-GPC TPC masks.""" tpc = sum(8 - popcount(tpc_masks[i] & 0xff) for i in range(8) if not (gpc_mask >> i) & 1) return tpc, tpc * 2 def summarize(rows, bank, defmasks): blocks = replay(rows) gpc = get_field(blocks, 1, 131, 8) fbp = get_field(blocks, 1, 307, 12) sm = [get_field(blocks, 2, 1248 + 3 * i, 3) for i in range(8)] tpc = [get_field(blocks, 1, 187 + 8 * i, 8) for i in range(8)] devida = get_field(blocks, 2, 593, 16) gpc_def = defmasks["gpc_disable"] fbp_def = defmasks["fbp_disable"] tpc_def = [defmasks["tpc_gpc%d_disable" % i] for i in range(8)] fbp_now, fbp_max = 12 - popcount(fbp & 0xfff), 12 - popcount(fbp_def & 0xfff) gpc_now, gpc_max = 8 - popcount(gpc & 0xff), 8 - popcount(gpc_def & 0xff) tpc_now, sm_now = _sm_tpc(gpc, tpc) tpc_max, sm_max = _sm_tpc(gpc_def, tpc_def) speed_full = all(s == 0 for s in sm) dn = DEVID_NAMES.get(devida, "unknown") print("current state -> full-unlock potential (DEFECTIVE floor):") print(" Memory %3d GiB (%2d/12 FBP) -> %3d GiB (%2d/12 FBP)" % (fbp_now * GIB_PER_FBP, fbp_now, fbp_max * GIB_PER_FBP, fbp_max)) print(" GPCs %d/8 active -> %d/8 active" % (gpc_now, gpc_max)) print(" SMs %3d SM (%2d TPC) -> %3d SM (%2d TPC)" % (sm_now, tpc_now, sm_max, tpc_max)) if speed_full: print(" SM-speed FULL (all 8 pipes) -> FULL (already unlocked)") else: print(" SM-speed %s -> FULL (all pipes)" % sm) print(" DEVIDA 0x%04X (%s)" % (devida, dn)) print(" first free FF row: 0x%03X" % first_free_row(rows)) print() # ---- rendering ------------------------------------------------------------ DEF_CHECK_ORDER = (["gpc_disable", "fbp_disable", "fbpa_disable", "fbio_disable", "rop_l2_disable", "pes_disable"] + ["tpc_gpc%d_disable" % i for i in range(8)] + ["nvlink_disable", "sys_pipe_disable"]) def print_defective_check(rows, defmasks, targets): """Show, per targeted floorsweep field, that TARGET keeps every DEFECTIVE bit disabled and only re-enables swept-but-good units. Returns False if any target would enable a defective unit.""" blocks = replay(rows) shown = [f for f in DEF_CHECK_ORDER if f in targets and FIELDS[f][3]] print("Disabled vs Defective Check") if not shown: print(" (no floorsweep fields in this recipe — nothing to re-enable)\n") return True print(" %-18s %-9s %-10s %-9s %-10s %-9s %s" % ("field", "DISABLE", "DEFECTIVE", "TARGET", "re-enable", "keep-OFF", "check")) all_ok = True for f in shown: c, b, w, da = FIELDS[f] dis = get_field(blocks, c, b, w) dfc = defmasks[f] tgt = targets[f] reen = dis & ~dfc # disabled-but-not-defective -> comes back ok = (tgt & dfc) == dfc # target must still contain every defective bit all_ok = all_ok and ok print(" %-18s 0x%06X 0x%06X 0x%06X 0x%06X 0x%06X %s" % (f, dis, dfc, tgt, reen, dfc, "OK" if ok else "!! WOULD ENABLE A DEFECTIVE")) print(" (TARGET = DEFECTIVE ; re-enable = DISABLE & ~DEFECTIVE ; keep-OFF = DEFECTIVE)\n") return all_ok def print_plan(records): if not records: print("No records needed — target already satisfied.") return print("%-5s %-12s %-7s %-7s %-7s %-10s %s" % ("row", "record", "chain", "offset", "data", "supersedes", "fields")) print("-" * 92) for r in records: pres = (" preserves 0x%04X" % r["preserved"]) if r["foreign_mask"] else "" print("0x%03X 0x%08X %-7d 0x%03X 0x%04X %-10s %s%s" % (r["row"], r["record"], r["chain"], r["offset"], r["new"], ("row 0x%03X" % r["supersedes"]) if r["supersedes"] is not None else "(new)", ",".join(r["fields"]), pres)) merged = sum(1 for r in records if r["foreign_mask"]) print("\n%d record(s), rows 0x%03X-0x%03X (%d carry preserved live data)" % (len(records), records[0]["row"], records[-1]["row"], merged)) def emit_journal(records): print("\n########## BURN SEQUENCE (review before executing) ##########") print("## Pre-flight — STOP if any is wrong") print("reg r 0x820060 # DEBUGCTRL MUST be 0x00000000") print("reg r 0x82007C # DIS_PROGRAM MUST be 0x00000000") print("reg r 0x820078 # EN_PROGRAM MUST be 0x00000001") print("reg r 0x8200F4 # FUSEWDATA_PLM MUST be 0xFFFFFFFF") for n, r in enumerate(records, 1): print("\n## ---- FF %d/%d : %s ----" % (n, len(records), ",".join(r["fields"]))) print("## chain %d / offset 0x%03X : 0x%04X -> 0x%04X%s" % (r["chain"], r["offset"], r["old"], r["new"], (" (supersedes row 0x%03X)" % r["supersedes"]) if r["supersedes"] is not None else "")) if r["foreign_mask"]: print("## merged block: preserves this die's 0x%04X (mask 0x%04X) — " "record is die-specific, computed from live data" % (r["preserved"], r["foreign_mask"])) print("reg w 0x820004 0x%X # FUSEADDR = row %d" % (r["row"], r["row"])) print("reg w 0x820000 0x1 # CMD_READ") print("reg r 0x820008 # MUST be 0x00000000 (blank)") print("reg w 0x82000C 0x%08X # FUSEWDATA (no readback)" % r["record"]) print("reg w 0x820000 0x2 # CMD_WRITE — IRREVERSIBLE OTP BURN") print("reg r 0x820000 # FUSECTRL should return to 0xe0040000") print("reg w 0x820000 0x1 # CMD_READ") print("reg r 0x820008 # FUSERDATA MUST read 0x%08X" % r["record"]) # ---- card serial (ECID — silicon-intrinsic, burn-invariant) -------------- ECID_REGS = {"vendor": 0x82025C, "fab": 0x820260, "lot0": 0x820264, "lot1": 0x820268, "wafer": 0x82026C, "x": 0x820270, "y": 0x820274} def get_serial(bank): v = {k: bank.rd(a) for k, a in ECID_REGS.items()} lot = (v["lot1"] << 32) | v["lot0"] return "L%X-W%d-X%d-Y%d" % (lot, v["wafer"], v["x"], v["y"]) def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--recipe", required=True, choices=["smspeed", "memory", "shaders", "pcie", "nvlink", "devid", "all"]) ap.add_argument("--devid", type=lambda s: int(s, 0), default=None, help="DEVIDA target, e.g. 0x20B5 (A100 80GB PCIe)") ap.add_argument("--bdf", default=None, help="PCI BDF; default auto-detect GA100") ap.add_argument("--rows", default=None, help="read chain from a dump file instead of the live card") ap.add_argument("--emit-journal", action="store_true", help="also append the reg-command burn sequence") ap.add_argument("--out", default=None, help="output text file (default ff_calc_.txt); '-' = console only") args = ap.parse_args() bank = None if args.rows: rows = rows_from_file(args.rows) # defective masks still need the live card (they are option regs, not FF rows) bdf = args.bdf or auto_bdf() bank = Bank(bdf) else: bdf = args.bdf or auto_bdf() bank = Bank(bdf) rows = bank.read_rows() # resolve defective masks live (pure MMIO reads) defmasks = {} for f, (c, b, w, da) in FIELDS.items(): if da: defmasks[f] = bank.rd(da) & ((1 << w) - 1) serial = get_serial(bank) targets = resolve_targets(args.recipe, defmasks, args.devid) # Capture the full console output so it can be teed to a serial-named file. import io import contextlib buf = io.StringIO() abort = None records = [] with contextlib.redirect_stdout(buf): print("CARD SERIAL (ECID): %s" % serial) print("BDF %s source: %s" % (bdf, "file %s" % args.rows if args.rows else "live CMD_READ")) print("recipe: %s%s\n" % (args.recipe, (" devid=0x%X" % args.devid) if args.devid is not None else "")) summarize(rows, bank, defmasks) if not print_defective_check(rows, defmasks, targets): print("!! ABORT: a target would re-enable a defective unit. No FF table emitted.") abort = 2 else: records = build_plan(rows, defmasks, targets) bad = [r for r in records if rows.get(r["row"], 0) != 0] # Explicit markers so a burn script keys off the table unambiguously: # each data row's first two columns are FUSEADDR and FUSEWDATA values. print("## FF-TABLE-BEGIN serial=%s recipe=%s " "(data rows: col1=FUSEADDR row, col2=FUSEWDATA record)" % (serial, args.recipe)) print("Final Calculated FF Table") print_plan(records) print("## FF-TABLE-END") if bad: print("\n!! ABORT: planned rows not blank: %s" % [hex(r["row"]) for r in bad]) abort = 2 if args.emit_journal and records and abort is None: emit_journal(records) text = buf.getvalue() sys.stdout.write(text) if args.out != "-": outfile = args.out or ("ff_calc_%s.txt" % serial) with open(outfile, "w") as f: f.write(text) print("\nwritten: %s" % outfile) if bank: bank.close() if abort: sys.exit(abort) def auto_bdf(): base = "/sys/bus/pci/devices" for d in sorted(os.listdir(base)): try: dev = open(os.path.join(base, d, "device")).read().strip() ven = open(os.path.join(base, d, "vendor")).read().strip() except OSError: continue if ven == "0x10de" and dev in ("0x20b5", "0x20c2", "0x2082"): return d raise SystemExit("no GA100 CMP/A100 device found; pass --bdf") if __name__ == "__main__": main()