"""The interrupt controller: IE, IF, IME, and the delay between a source and the CPU's line. GBATEK "GBA Interrupt Control"; the timing is NanoBoyAdvance's ``hw/irq/irq.cpp``, which passes ``hw-test/irq/irq-delay`` (docs/timing.md "Interrupt latency"): 1. A source, or a CPU write to IE/IF/IME, changes a *pending* copy; the registers the CPU reads take the pending values one cycle later. 2. ``IE & IF`` (which wakes a halted CPU) follows one cycle after that. 3. The CPU's IRQ input (``IE & IF`` and IME; ``level`` here) follows one cycle of the CPU's clock after step 1's update: the CPU's synchronizer, which stops while the CPU waits for a DMA to free the bus, but not through internal cycles a DMA overlaps and not in HALT (docs/undocumented-behavior.md quirk 10). 4. The CPU looks at its input when it begins a bus cycle, and the look at the last cycle of an instruction decides whether the next one runs: the board copies ``level`` to ``cpu.irq`` at the start of every CPU access (quirk 23). With no wait states that is the same three cycles from source to instruction boundary as NanoBoyAdvance's; an access with wait states looks before them. The core samples ``cpu.irq`` at the start of each ``step()`` and has no synchronizer of its own, so this delay is the whole of the GBA's latency (the core's contract). """ from __future__ import annotations from collections.abc import Callable from gba_python.scheduler import Scheduler VBLANK, HBLANK, VCOUNT = 0, 1, 2 TIMER0 = 3 # timers 0-3 are bits 3-6 SERIAL = 7 DMA0 = 8 # DMA 0-3 are bits 8-11 KEYPAD = 12 GAMEPAK = 13 IE_MASK = 0x3FFF SYNC_CYCLES = 1 # the CPU's IRQ synchronizer, in cycles of the CPU's clock class IRQ: def __init__(self, scheduler: Scheduler, cpu: object) -> None: self.scheduler = scheduler self.cpu = cpu self.ie = self.if_ = self.ime = 0 self.pending_ie = self.pending_if = self.pending_ime = 0 self.available = False # IE & IF, as the HALT logic sees it self.line = False # the line value last scheduled for the CPU self.level = False # the CPU's IRQ input, after the synchronizer self.available_at = 0 # when IE & IF last changed, for a wake-up during a DMA self.deferred: list[int] = [] # line changes held in the synchronizer while the CPU waits # Line changes made while a DMA overlapped the CPU's internal cycles: how far the # CPU's clock had run by then is known only when the CPU next asks for the bus. self.unsettled: list[tuple[int, bool]] = [] self.overlapping: Callable[[], bool] = lambda: False # Set by the board: cycles the CPU's clock has run, and whether it waits for a DMA. self.cpu_cycles: Callable[[], int] = lambda: scheduler.now self.cpu_waiting: Callable[[], bool] = lambda: False # ----- CPU access --------------------------------------------------------------------- def write_ie(self, value: int, mask: int) -> None: self.pending_ie = (self.pending_ie & ~mask | value & mask) & IE_MASK self.scheduler.add(1, self._apply, priority=1) def write_if(self, value: int, mask: int) -> None: # Writing 1 acknowledges (clears) that bit (GBATEK). self.pending_if &= ~(value & mask) self.scheduler.add(1, self._apply, priority=1) def write_ime(self, value: int, mask: int) -> None: if mask & 0xFF: self.pending_ime = value & 1 self.scheduler.add(1, self._apply, priority=1) def raise_(self, bit: int) -> None: """A source fires (``bit`` is its IE/IF bit number).""" self.pending_if |= 1 << bit self.scheduler.add(1, self._apply, priority=0) # ----- the pipeline ------------------------------------------------------------------- def _apply(self, _: int) -> None: self.ime = self.pending_ime self.ie = self.pending_ie self.if_ = self.pending_if available = bool(self.ie & self.if_) if available != self.available: self.scheduler.add(1, self._set_available, int(available)) line = bool(self.ime) and available if line != self.line: # The synchronizer is clocked by the CPU's own clock: it counts only cycles the # CPU runs, not those it spends waiting for a DMA to free the bus (quirk 10). if self.overlapping(): self.unsettled.append((self.scheduler.now, line)) else: target = self.cpu_cycles() + SYNC_CYCLES self.scheduler.add(SYNC_CYCLES, self._synchronized, target << 1 | line) self.line = line def _set_available(self, value: int) -> None: self.available = bool(value) self.available_at = self.scheduler.now def _synchronized(self, packed: int) -> None: """A line change has been through the synchronizer if the CPU ran long enough; otherwise (it waited for a DMA meanwhile) it waits for the rest of its CPU cycles.""" remaining = (packed >> 1) - self.cpu_cycles() if remaining <= 0: self.level = bool(packed & 1) elif self.cpu_waiting(): self.deferred.append(packed) else: self.scheduler.add(remaining, self._synchronized, packed) def resume(self) -> None: """The CPU's clock restarted: the synchronizer carries on with what it held.""" held, self.deferred = self.deferred, [] for packed in held: self._synchronized(packed) def overlap(self, start: int, cpu_start: int, used: int, final: bool) -> None: """A DMA that began at ``start`` (the CPU's clock at ``cpu_start``) overlapped the CPU's internal cycles, ``used`` of them so far; ``final``: the CPU now waits for the bus or the DMA is over, so the clock ran no further. Line changes whose place on the CPU's clock is now known go through the synchronizer.""" cpu_now = cpu_start + used keep = [] for wall, line in self.unsettled: if wall - start <= used or final: target = cpu_start + min(wall - start, used) + SYNC_CYCLES self.deferred.append(target << 1 | line) else: keep.append((wall, line)) self.unsettled = keep held = [] for packed in self.deferred: remaining = (packed >> 1) - cpu_now if remaining <= 0: self.level = bool(packed & 1) elif final: self.scheduler.add(remaining, self._synchronized, packed) else: held.append(packed) self.deferred = held