"""The four timers: 16-bit up-counters on a free-running prescaler, or counting overflows. GBATEK "GBA Timers"; the cycle rules are NanoBoyAdvance's ``hw/timer/timer.cpp``, which passes ``hw-test/timer/*`` and the mGBA suite's count-up and timer IRQ groups (docs/timing.md "Timers"): - The prescaler (1, 64, 256 or 1024) is one divider that runs from power-on: a timer started at cycle t first ticks at the next multiple of its period, so the phase is observable (alyosha-tas ``timer/timer.gba``). The scheduler's clock is that divider. - A write to the reload (TMxCNT_L) lands one cycle after the write; a write to the control (TMxCNT_H) also lands one cycle later, and a 0->1 start loads the reload into the counter. - The counter is not stored while a timer runs: it is computed from the cycle it started (catch-up on access), and an overflow is an event on the scheduler. - On overflow: reload, raise the IRQ if enabled, clock the sound FIFOs (timers 0 and 1), and tick the next timer if it counts up. """ from __future__ import annotations from collections.abc import Callable from gba_python.irq import IRQ, TIMER0 from gba_python.scheduler import Event, Scheduler SHIFTS = (0, 6, 8, 10) class Channel: __slots__ = ( "cascade", "control", "counter", "enable", "event", "id", "interrupt", "pending_control", "pending_reload", "prescaler", "reload", "running", "shift", "started", ) def __init__(self, index: int) -> None: self.id = index self.reload = 0 self.counter = 0 self.pending_reload = 0 self.pending_control = 0 self.control = 0 # the readable bits of TMxCNT_H self.prescaler = 0 self.cascade = False self.interrupt = False self.enable = False self.running = False # counting on the prescaler (enabled and not cascading) self.shift = 0 self.started = 0 # the cycle the running count is measured from self.event: Event | None = None class Timers: def __init__( self, scheduler: Scheduler, irq: IRQ, on_overflow: Callable[[int], None] | None = None ) -> None: self.scheduler = scheduler self.irq = irq #: called with the timer number when timer 0 or 1 overflows (the sound FIFOs) self.on_overflow = on_overflow self.channels = [Channel(index) for index in range(4)] # ----- CPU access --------------------------------------------------------------------- def read_counter(self, index: int) -> int: channel = self.channels[index] counter = channel.counter if channel.running: counter += (self.scheduler.now - channel.started) >> channel.shift return counter & 0xFFFF def read_control(self, index: int) -> int: return self.channels[index].control def write_reload(self, index: int, value: int, mask: int) -> None: channel = self.channels[index] channel.pending_reload = channel.pending_reload & ~mask | value & mask self.scheduler.add(1, self._reload_written, index, priority=1) def write_control(self, index: int, value: int, mask: int) -> None: if not mask & 0xFF: return # the high byte of TMxCNT_H holds nothing self.channels[index].pending_control = value & 0xFF self.scheduler.add(1, self._control_written, index, priority=2) # ----- events ------------------------------------------------------------------------- def _reload_written(self, index: int) -> None: channel = self.channels[index] channel.reload = channel.pending_reload def _control_written(self, index: int) -> None: channel = self.channels[index] was_enabled = channel.enable value = channel.pending_control if channel.running: self._stop(channel) channel.prescaler = value & 3 channel.interrupt = bool(value & 0x40) channel.enable = bool(value & 0x80) if index != 0: channel.cascade = bool(value & 4) # timer 0 has no timer before it to count channel.control = ( channel.prescaler | (4 if channel.cascade else 0) | (0x40 if channel.interrupt else 0) | (0x80 if channel.enable else 0) ) channel.shift = SHIFTS[channel.prescaler] if not channel.enable: return # How far the free-running divider is past its last tick for this prescaler. offset = self.scheduler.now & ((1 << channel.shift) - 1) if was_enabled: if not channel.cascade: self._start(channel, offset) elif channel.cascade: channel.counter = channel.reload elif channel.counter == 0xFFFF and offset == 0: # Loading the reload takes a cycle, during which the counter can still tick and # overflow (NanoBoyAdvance issue 331; hw-test/timer/tick-before-reload). self._start(channel, 0) else: channel.counter = channel.reload self._start(channel, offset - 1) def _start(self, channel: Channel, offset: int) -> None: cycles = ((0x10000 - channel.counter) << channel.shift) - offset channel.running = True channel.started = self.scheduler.now - offset channel.event = self.scheduler.add(cycles, self._overflow, channel.id) def _stop(self, channel: Channel) -> None: channel.counter += (self.scheduler.now - channel.started) >> channel.shift if channel.counter >= 0x10000: # Stopped in the cycle it overflows: the overflow still happens (alyosha-tas # irq/readme.txt). self._reload_and_cascade(channel) self.scheduler.cancel(channel.event) channel.event = None channel.running = False def _reload_and_cascade(self, channel: Channel) -> None: channel.counter = channel.reload if channel.interrupt: self.irq.raise_(TIMER0 + channel.id) if channel.id <= 1 and self.on_overflow is not None: self.on_overflow(channel.id) if channel.id != 3: following = self.channels[channel.id + 1] if following.enable and following.cascade: following.counter += 1 if following.counter == 0x10000: self._reload_and_cascade(following) def _overflow(self, index: int) -> None: channel = self.channels[index] self._reload_and_cascade(channel) self._start(channel, 0)