# SPDX-License-Identifier: MIT """Have your own BIOS format the internal backup RAM, and save the result. A game such as Sonic CD refuses to start on an unformatted backup RAM ("Internal RAM is not initialized"). The format is the BIOS's own, written by its BRMFORMAT call, and no permitted document here describes the layout, so this board never writes one itself. Instead this tool boots your BIOS (no disc) until its sub-CPU program is up, then calls the BIOS's documented back-up RAM entry from the sub CPU, as a program on a disc would: BRMINIT (function 0), then BRMFORMAT (function 6). The bytes that come out are whatever your BIOS writes; they are saved to a file outside the repository, which ``python -m segacd_python --backup-ram FILE`` then loads. Sources: the call sequence, the registers (d0 function number, a0 scratch RAM, a1 a 12-byte string buffer) and "BRMINIT first" are Sega's *Mega-CD BIOS Manual* (Ver 2.00, 1992, chapter 7, p.38-41; DOC). The entry's address, ``_BURAM`` = $005F16, the two function numbers and the scratch RAM's size ($640 bytes) are megadev's ``lib/sub/bram.def.h`` and ``bram.h`` (MIT, Damian Rogers; DOC, a permissive SDK). python scripts/format_backup_ram.py --bios $SEGACD_BIOS runs/brm/formatted.brm The BIOS image is never copied into the repository; ``--bios`` defaults to the ``SEGACD_BIOS`` environment variable. """ from __future__ import annotations import argparse import os import sys from pathlib import Path from segacd_python.console import build from segacd_python.memory import formatted_backup_ram #: megadev ``bram.def.h``: the sub CPU's back-up RAM entry and two function numbers. BURAM = 0x005F16 BRMINIT = 0x0000 BRMFORMAT = 0x0006 #: Where the call's buffers and its return go: high PRG RAM, borrowed for the call #: only (the machine is thrown away afterwards). SCRATCH = 0x07E000 # $640 bytes (megadev bram.h) STRINGS = 0x07EF00 # 12 bytes RETURN = 0x07F000 # a BRA.S to itself: where the call comes back to STACK = 0x07FF00 def call(device: object, function: int, limit: int = 20_000_000) -> tuple[int, bool]: """Run ``jsr _buram`` with ``d0 = function`` on the sub CPU, interrupts masked; return d0 and the carry flag (set = error) when it returns.""" cpu = device.sub # type: ignore[attr-defined] prg = device.prg # type: ignore[attr-defined] prg[RETURN : RETURN + 2] = b"\x60\xfe" # BRA.S * cpu.set_sr(0x2700) # supervisor, every interrupt masked cpu.R[0] = function cpu.R[8] = SCRATCH cpu.R[9] = STRINGS sp = STACK - 4 prg[sp : sp + 4] = RETURN.to_bytes(4, "big") cpu.R[15] = sp cpu.set_pc(BURAM) clocks = 0 while clocks < limit: if cpu.PC == RETURN: return cpu.R[0] & 0xFFFF, bool(cpu.SR & 1) step = cpu.step() clocks += step device.gate.run(step) # type: ignore[attr-defined] raise SystemExit(f"_buram function {function} did not return") def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("out", type=Path, help="the formatted backup RAM file to write") parser.add_argument("--bios", type=Path, default=os.environ.get("SEGACD_BIOS")) parser.add_argument("--frames", type=int, default=600, help="frames to boot before the call (the BIOS's title screen)") # fmt: skip args = parser.parse_args(argv) if args.bios is None: parser.error("--bios or SEGACD_BIOS is needed") system, device = build("genesis", args.bios.read_bytes(), None, backup_ram=formatted_backup_ram()) # fmt: skip for _ in range(args.frames): system.run_frame() for source in device.audio_sources: source.take_samples(system.mclk) system.board.fm.take_samples() system.board.psg.take_samples() size, error = call(device, BRMINIT) print(f"BRMINIT: d0=${size:04X} {'cs (not formatted)' if error else 'cc'}") _, error = call(device, BRMFORMAT) if error: raise SystemExit("BRMFORMAT returned an error") size, error = call(device, BRMINIT) print(f"BRMINIT after BRMFORMAT: d0=${size:04X} {'cs' if error else 'cc (formatted)'}") if error: raise SystemExit("the backup RAM still reads as unformatted") args.out.parent.mkdir(parents=True, exist_ok=True) args.out.write_bytes(bytes(device.backup_ram.data)) print(f"wrote {args.out}") return 0 if __name__ == "__main__": sys.exit(main())