# SPDX-License-Identifier: MIT """The four 16-bit timers, their shared prescaler, count-up, and overflow events. Registers: GBATEK §GBA Timers (DOC): TMxCNT_L reads the counter and writes the reload; TMxCNT_H holds the prescaler (F/1, F/64, F/256, F/1024), count-up (not timer 0), IRQ enable and start. docs/timing.md "Timers" has the hardware results this module is judged by. The timer is computed from the time rather than stepped: a running timer holds ``counter``, its value at the start of cycle ``base``, and counts the prescaler's ticks since. An overflow is a scheduled event at the cycle of the tick that wraps the counter. Cycle-level rules (each tagged; U-TIM-4 is the prescaler's phase): - The prescaler is one free-running divider from power-on, not reset when a timer starts: a timer with prescaler p ticks in every cycle c with (c + PHASE) % p == 0 (HYPOTHESIS from alyosha-tas timer/readme.txt, "Tests state of the clock divider after power on"; U-TIM-4). - A start write in cycle w loads the reload into the counter one cycle later: the counter holds the reload from cycle w + 1 (hw-test timer/tick-before-reload README: "After enabling a timer, it takes one cycle to load the reload value into the counter"; TEST ROM), and its first tick is in cycle w + 2 (START_TICK; FITTED: with it, and a read in cycle t seeing the ticks of cycles before t, hw-test timer/start-stop (3, 8) and timer/reload (all seven lines) and the mGBA suite's "Timer IRQ" table come out as the hardware results; a first tick in w + 1 gives FFFA for reload's FFF9). - An overflow in cycle c puts the reload in the counter at once: the next tick is in c + 1 (same tests; FITTED together with START_TICK). - In the start cycle w the counter may still tick from its old value and overflow ("the timer can tick in the cycle before loading the counter and signal an overflow", same README; alyosha-tas timer/readme.txt test 2; TEST ROM). - A stop write in cycle w still lets the tick of cycle w happen ("timer runs one cycle after disabling, and interrupt should still occur", alyosha-tas irq/readme.txt; hw-test timer/start-stop; TEST ROM). - A reload write lands in the counter only at an overflow or a start (GBATEK; DOC; hw-test timer/reload; TEST ROM). """ from __future__ import annotations from gba_python.irq import TIMER0 from gba_python.scheduler import ORDER_TIMER PRESCALERS = (1, 64, 256, 1024) # The divider's phase at power-on, in cycles (U-TIM-4). FITTED: see docs/timing.md "Timers". PHASE = 0 # A reload written in cycle w is used by an overflow in cycle c only when w < c - RELOAD_LEAD # (hw-test timer/reload: "up to the next-to-last cycle before overflow takes effect at that # overflow, in the last cycle it does not"; TEST ROM). FITTED, docs/timing.md "Timers". RELOAD_LEAD = 0 # Cycles from an overflow's tick to its IF bit being set (see overflow_effects). FITTED. IRQ_LAG = 2 # Cycles from a start write to the counter's first tick (see the module rules). FITTED. START_TICK = 2 def ticks_between(start: int, end: int, period: int) -> int: """Prescaler ticks in the cycles start .. end - 1.""" if end <= start: return 0 if period == 1: return end - start return (end - 1 + PHASE) // period - (start - 1 + PHASE) // period def tick_at_or_after(time: int, period: int) -> int: """The first prescaler tick cycle at or after ``time``.""" if period == 1: return time return time + (-(time + PHASE)) % period class Timer: __slots__ = ( "base", "control", "count_up", "counter", "event", "event_tick", "index", "pending_reload", "pending_time", "period", "reload", "running", ) def __init__(self, index: int) -> None: self.index = index self.reload = 0 self.pending_reload = None self.pending_time = 0 self.control = 0 self.counter = 0 self.base = 0 self.running = False self.period = 1 self.count_up = False self.event = None self.event_tick = 0 class Timers: def __init__(self, board) -> None: self.board = board self.timers = [Timer(i) for i in range(4)] # ---------------------------------------------------------------------------------- def value(self, timer: Timer, time: int) -> int: """The counter as a read in cycle ``time`` sees it (ticks of earlier cycles).""" if not timer.running or timer.count_up: return timer.counter return timer.counter + ticks_between(timer.base, time, timer.period) def schedule_overflow(self, timer: Timer) -> None: if timer.event is not None: timer.event.cancel() timer.event = None if not timer.running or timer.count_up: return remaining = 0x10000 - timer.counter first = tick_at_or_after(timer.base, timer.period) when = first + (remaining - 1) * timer.period # The overflow's tick is in cycle ``when``; like any tick, a read sees it from the next # cycle on, so the event runs at ``when + 1`` with the tick's cycle as its time # (mGBA suite "Timer IRQ": reload FFFD read 4 cycles after the start reads FFFF; # TEST ROM). timer.event_tick = when timer.event = self.board.scheduler.schedule( when + 1, ORDER_TIMER, lambda t, timer=timer: self.overflow(timer, t - 1) ) def reload_value(self, timer: Timer, time: int) -> int: if timer.pending_reload is not None and timer.pending_time < time - RELOAD_LEAD: timer.reload = timer.pending_reload timer.pending_reload = None return timer.reload def overflow(self, timer: Timer, time: int) -> None: """The tick in cycle ``time`` wraps the counter: reload, IRQ, count-up, sound.""" timer.event = None timer.counter = self.reload_value(timer, time) timer.base = time + 1 self.overflow_effects(timer, time) self.schedule_overflow(timer) def overflow_effects(self, timer: Timer, time: int) -> None: if timer.control & 0x40: # IF is set two cycles after the overflow's tick (IRQ_LAG). FITTED with the IRQ # line's delays (gba_python.irq) to alyosha-tas irq/IF (a read in the cycle after # the reload first shows still sees IF clear) and the mGBA suite's Timer IRQ table. self.board.irq.request(TIMER0 << timer.index, time + IRQ_LAG) if timer.index < 2: self.board.sound.timer_overflow(timer.index, time) if timer.index < 3: following = self.timers[timer.index + 1] if following.running and following.count_up: self.count_up_tick(following, time) def count_up_tick(self, timer: Timer, time: int) -> None: """Count-up: the timer counts the previous timer's overflows, prescaler ignored (GBATEK §GBA Timers; DOC).""" if timer.counter == 0xFFFF: timer.counter = self.reload_value(timer, time) self.overflow_effects(timer, time) else: timer.counter += 1 # ---------------------------------------------------------------------------------- # Registers def read16(self, offset: int) -> int | None: index, high = (offset - 0x100) >> 2, offset & 2 timer = self.timers[index] if high: return timer.control & 0x00C7 if index else timer.control & 0x00C3 return self.value(timer, self.board.bus.now) & 0xFFFF def write16(self, offset: int, value: int, mask: int, time: int) -> None: index, high = (offset - 0x100) >> 2, offset & 2 timer = self.timers[index] if not high: new = ( (timer.pending_reload if timer.pending_reload is not None else timer.reload) & ~mask ) | (value & mask) if timer.running: timer.pending_reload = new timer.pending_time = time else: timer.reload = new timer.pending_reload = None return if not mask & 0x00FF: return # the high byte of TMxCNT_H is unused control = value & 0xC7 if index == 0: control &= ~0x04 # timer 0 has no count-up (DOC) was_running = timer.running starting = bool(control & 0x80) and not was_running stopping = was_running and not control & 0x80 if stopping and timer.event is not None and timer.event_tick <= time: # The tick of the stop cycle overflows: it still happens, IRQ included # (alyosha-tas irq/readme.txt; TEST ROM). timer.event.cancel() self.overflow(timer, timer.event_tick) if was_running: # Bring the counter up to and including this cycle's tick (the stop rule), or up # to this cycle for a setting change while running (HYPOTHESIS for the latter). end = time + 1 if stopping else time if not timer.count_up: timer.counter += ticks_between(timer.base, end, timer.period) timer.base = end timer.control = control timer.period = PRESCALERS[control & 3] timer.count_up = bool(control & 0x04) if starting: old = timer.counter if timer.pending_reload is not None: timer.reload = timer.pending_reload timer.pending_reload = None # The tick of the start cycle on the old counter (tick-before-reload; TEST ROM). if ( not timer.count_up and old == 0xFFFF and tick_at_or_after(time, timer.period) == time ): self.overflow_effects(timer, time) timer.counter = timer.reload # Loaded in cycle w + 1, first tick in w + 2 (START_TICK; see the module rules). timer.base = time + START_TICK timer.running = True elif stopping: timer.running = False self.schedule_overflow(timer)