# SPDX-License-Identifier: MIT """The GBA board: builds the CPU, the bus and the devices, and runs them on one clock. One clock domain (the charter's era 1 shape; docs/README.md "The machine in one page"). The CPU is arm7tdmi-python's ``ARM7TDMI(read, write, idle)``, used only through its public interface; the bus prices each of its callbacks (gba_python.bus, whose docstring holds the order of record within a cycle). Between instructions the board runs due events, updates the CPU's IRQ line, and handles HALT and STOP (gba_python.irq). Channels a later tier may thread (docs/plan.md "Module layout"): the sound unit takes register writes and time (``Sound.catch_up``, FIFO pushes); the picture processor takes register and video-memory writes and time. No device pokes another's state except through the bus or a named method. """ from __future__ import annotations from arm7tdmi_python import ARM7TDMI from gba_python.bios import load_bios from gba_python.bus import Bus from gba_python.cartridge.detect import detect_kind, detect_rtc, make_backup from gba_python.cartridge.rom import GamePakROM from gba_python.cartridge.rtc import GPIO, RTC from gba_python.dma import DMA from gba_python.io import IO from gba_python.irq import Interrupts from gba_python.keypad import Keypad from gba_python.ppu.timing import FRAME_CYCLES, PPU from gba_python.prefetch import Prefetch from gba_python.scheduler import NEVER, Scheduler from gba_python.serial import Serial from gba_python.sound import Sound from gba_python.timers import Timers class GBA: """A Game Boy Advance with a BIOS image and a Game Pak.""" def __init__( self, rom: bytes | GamePakROM | None = None, bios=None, save_type: str | None = None, save_data: bytes | None = None, rtc: bool | None = None, rtc_start=None, ) -> None: """``save_type`` overrides the detected save chip (cartridge/detect.py KINDS, with an optional Flash chip name); ``save_data`` is a battery file's content. ``rtc`` fits or removes the GPIO port and clock (default: detected); ``rtc_start`` is the clock's datetime at power-on (default: the host's time).""" if rom is None: rom = GamePakROM(b"") elif not isinstance(rom, GamePakROM): rom = GamePakROM(rom) self.rom = rom bios_image = bios if isinstance(bios, bytes | bytearray) else load_bios(bios) kind = save_type or detect_kind(rom.data) self.backup = make_backup(kind, save_data) self.dma_due = NEVER self.frames = 0 # V-blanks seen self.bus = Bus(self, bios_image, rom, self.backup) self.rtc = None if rtc if rtc is not None else detect_rtc(rom.data): self.rtc = RTC(rtc_start) self.bus.gpio = GPIO(self.rtc) self.scheduler = Scheduler(self.bus) self.irq = Interrupts(self) self.dma = DMA(self) self.timers = Timers(self) self.sound = Sound(self) self.serial = Serial(self) self.keypad = Keypad(self) self.ppu = PPU(self) self.bus.io = IO(self) self.bus.dma = self.dma self.bus.prefetch = Prefetch(self.bus) self.cpu = ARM7TDMI(self.bus.read, self.bus.write, self.bus.idle) self.cpu.reset() # ---------------------------------------------------------------------------------- def skip_bios(self) -> None: """Start the cartridge as Nintendo's BIOS leaves it, without running the boot (U-SYS-2). GBATEK §BIOS RAM Usage gives the stacks (SP_svc 03007FE0, SP_irq 03007FA0, SP_usr 03007F00; DOC). The rest is FITTED: taken from this board's own boot with Nintendo's BIOS, stopped at its first opcode fetch from 08000000 (2026-11-23, scratch capture; docs/validation.md "Rung 7"): System mode, ARM, IRQs and FIQs enabled, r0-r12 = 0, LR = 08000000, every RAM cleared, DISPCNT 0080 (forced blank), BG2PA, BG2PD, BG3PA and BG3PD 0100 (the affine BGs unscaled; write-only, so a game that never writes them draws its affine BG through them: Pinball Tycoon's logos, rung 7), SOUNDBIAS 0200, SOUNDCNT_H 880E (the FIFO reset bits as written; they read 0), RCNT 8000, POSTFLG 1, the BIOS latch E129F000 (the last BIOS opcode fetched). Not copied (HYPOTHESIS that no game depends on them): the boot's 76.0 million cycles of elapsed time and the line it leaves the picture on (VCOUNT 126), timer 0's counter (FFA3), the sequencer phase. """ state = self.cpu.capture_state() state.registers = [0] * 13 + [0x03007F00, 0x08000000, 0x08000000] state.cpsr = 0x1F # Banks (state.py order): user, fiq, svc, abt, irq, und; slot 5 is SP, 6 is LR. state.banks[0][5:7] = [0x03007F00, 0x08000000] state.banks[2][5:7] = [0x03007FE0, 0] state.banks[4][5:7] = [0x03007FA0, 0] self.cpu.restore_state(state) bus = self.bus io = bus.io now = bus.now io.write16(0x000, 0x0080, 0xFFFF, now) for offset in (0x020, 0x026, 0x030, 0x036): io.write16(offset, 0x0100, 0xFFFF, now) io.write16(0x082, 0x880E, 0xFFFF, now) io.write16(0x088, 0x0200, 0xFFFF, now) io.write16(0x134, 0x8000, 0xFFFF, now) io.write16(0x300, 0x0001, 0x00FF, now) bus.bios_latch = bus.open_bus = 0xE129F000 bus.fetch_in_bios = False self.cpu.start_at(0x08000000) def run_events(self) -> None: self.scheduler.run_due() def frame_done(self, time: int) -> None: self.frames += 1 @property def now(self) -> int: return self.bus.now def step(self) -> None: """One instruction, or one stretch of HALT up to the next event.""" bus = self.bus if bus.now >= bus.next_event: self.run_events() irq = self.irq if irq.halted or irq.stopped: self.wait_halted(NEVER) return if self.dma_due <= bus.now: self.dma.run() self.cpu.irq = irq.line(bus.now) self.cpu.step() def wait_halted(self, limit: int) -> None: """HALT: the CPU stops until (IE and IF) != 0 while everything else runs (GBATEK §BIOS Halt Functions; DOC). STOP: also until a keypad, Game Pak or serial IRQ condition with its IE bit set (DOC; HYPOTHESIS that IF is set as for halt, U-SYS-3). DMA runs during halt (hw-test haltcnt "CPUSET DMA"; TEST ROM).""" bus = self.bus irq = self.irq wake = irq.wake_time() if wake <= bus.now: irq.halted = irq.stopped = False return if self.dma_due <= bus.now: self.dma.run() return bus.now = max(bus.now, min(bus.next_event, self.dma_due, limit, wake)) if bus.now >= bus.next_event: self.run_events() if irq.wake_time() <= bus.now: irq.halted = irq.stopped = False def halt_during_access(self) -> None: """A DMA that stalled a CPU access wrote HALTCNT: the halt begins before that access, which waits for the wake-up (HYPOTHESIS; FITTED to hw-test haltcnt "HALTCNT CPUSET DMA" 4154, docs/timing.md "HALT and STOP").""" irq = self.irq while irq.halted or irq.stopped: self.wait_halted(NEVER) def run_until(self, time: int) -> None: bus = self.bus irq = self.irq cpu = self.cpu dma = self.dma while bus.now < time: if bus.now >= bus.next_event: self.run_events() if irq.halted or irq.stopped: self.wait_halted(time) continue if self.dma_due <= bus.now: dma.run() cpu.irq = irq.line(bus.now) cpu.step() def run_frames(self, count: int) -> None: """Run ``count`` frames of 280,896 cycles from where the board stands.""" self.run_until(self.bus.now + count * FRAME_CYCLES) def set_keys(self, pressed: int) -> None: self.keypad.set_keys(pressed, self.bus.now) def picture(self) -> list[list[int]]: """The last finished frame (rung 3's line renderer, gba_python.ppu.line).""" return self.ppu.picture()