# SPDX-License-Identifier: MIT """The Game Pak prefetch buffer (WAITCNT bit 14). What the documents say (GBATEK §GBA GamePak Prefetch; DOC): with bit 14 set, "the GBA attempts to read opcodes from Game Pak ROM during periods when the CPU is not using the bus (if any). Memory access is then performed with 0 Waits if the CPU requests data which is already stored in the buffer. The prefetch buffer stores up to eight 16bit values." Only opcode fetches from ROM use it. What the hardware tests' readme adds (alyosha-tas prefetcher/readme.txt; TEST ROM): - "When prefetcher is full ... the prefetch unit pauses until the buffer is empty and then starts up again with non-sequential timing." - "When the prefetch buffer is empty, and a branch is done to the next instruction that would be read by the prefetcher, the instruction fetch is done with non-sequential timing (even though the prefetcher starts at the same time with sequential timing.)" - "When the prefetcher encounters a 0x20000 boundary, it stops and behaves as though it is full." (Not followed as read: see BOUNDARY_STOP.) The rest of the state machine is undocumented (U-TIM-3). The model, with every choice named: - The unit reads the halfwords after the last opcode the CPU fetched from ROM, one at a time, each costing the window's S wait (N when it starts after a pause or after the cartridge was used for something else), whenever the cartridge bus is free: during the CPU's internal cycles and its accesses elsewhere (HYPOTHESIS from GBATEK's "when the CPU is not using the bus"; the readme's "loading a register from EWRAM should add one instruction"). - A sequential opcode fetch (the core's SEQ pin, the merged IS cycle included) whose halfwords are in the buffer takes 1 cycle (GBATEK's 0 waits). If its halfword is the one being fetched, the CPU waits for that fetch to finish. A non-sequential fetch (a branch) empties the buffer and is an ordinary access; the unit then starts on the next halfword (the readme's second fact). - A CPU data access or a DMA access to the cartridge stops the unit and empties the buffer; a fetch in flight is abandoned unless it is in its last cycle, when it finishes first (FLUSH_ON_DATA, FINISH_LAST; FITTED). The unit restarts at the next opcode fetch from ROM. The model is caught up lazily: the bus calls ``catch_up(now)`` before each use of the cartridge, and the unit advances over the cycles since it last looked. """ from __future__ import annotations CAPACITY = 8 # halfwords (DOC) # "When the prefetcher encounters a 0x20000 boundary, it stops and behaves as though it is # full" (alyosha-tas prefetcher/readme.txt; TEST ROM prose). Read as "the unit pauses at the # boundary until the buffer is empty", it fails that suite's own prefetcher_boundary_1 and _3 # (81, 83), which pass with the unit running on: the hardware-calibrated ROMs overrule this # reading (docs/undocumented-behavior.md U-TIM-3). Off (0); the switch stays so the rule's # effect stays measurable and seeded. BOUNDARY_STOP = 0 # Whether a data access to the cartridge empties the buffer (FLUSH_ON_DATA) instead of # leaving its halfwords for later opcode fetches. FITTED. FLUSH_ON_DATA = 1 # A fetch in flight with at most FINISH_LAST cycles left is finished before a data access # takes the cartridge, rather than abandoned. FITTED. FINISH_LAST = 1 MISS_FINISH_LAST = 1 class Prefetch: def __init__(self, bus) -> None: self.bus = bus self.enabled = False self.head = 0 # address of the first buffered halfword self.count = 0 # buffered halfwords self.fetching = False # a halfword fetch in flight at head + 2 * count self.remaining = 0 # its cycles left self.next_n = True # the next fetch the unit starts is N self.last = 0 # the cycle the unit was last brought up to self.streaming = False # following the CPU's opcode stream (head is meaningful) # ---------------------------------------------------------------------------------- def waitcnt_changed(self, time: int) -> None: enabled = bool(self.bus.waitcnt & 0x4000) if enabled != self.enabled: self.catch_up(time) self.enabled = enabled # Switching the unit off empties it; switching it on starts it at the next # opcode fetch (HYPOTHESIS; alyosha-tas timing/prefetch_enable* judge it). self.count = 0 self.fetching = False self.streaming = False self.next_n = True self.last = time self.waits_changed() def waits_changed(self) -> None: pass def fetch_cost(self, address: int, sequential: bool) -> int: region = address >> 24 return self.bus.s16[region] if sequential else self.bus.n16[region] def start_next(self) -> None: """Start fetching the halfword after the buffer, if the unit may.""" address = self.head + 2 * self.count if self.count >= CAPACITY: self.next_n = True # full: pause until empty, then restart N (readme) return if BOUNDARY_STOP and self.count and (address & 0x1FFFF) == 0: self.next_n = True # a 128 KB boundary: stop as though full (readme) return self.fetching = True self.remaining = self.fetch_cost(address, not self.next_n) self.next_n = False def catch_up(self, now: int) -> None: """Advance the unit over the free cartridge-bus cycles since it last looked.""" if now <= self.last: return free = now - self.last self.last = now while free > 0 and self.fetching: if self.remaining > free: self.remaining -= free return free -= self.remaining self.remaining = 0 self.fetching = False self.count += 1 self.bus.cart_latch = ((self.head >> 1) + self.count) & 0xFFFFFF self.start_next() if not self.fetching and self.count == 0 and self.paused_restart(): self.start_next() def paused_restart(self) -> bool: return False # ---------------------------------------------------------------------------------- # Uses of the cartridge def data_access(self, time: int) -> None: """The CPU or a DMA is about to use the cartridge for data at ``time``.""" self.catch_up(time) if self.fetching and self.remaining <= FINISH_LAST: self.bus.now += self.remaining self.catch_up(self.bus.now) if self.fetching: self.fetching = False # abandoned if FLUSH_ON_DATA: # Emptied: the unit idles until the next opcode fetch from ROM restarts it. self.count = 0 self.streaming = False self.next_n = True def after_cart(self, time: int) -> None: """The cartridge is free again from ``time``.""" self.last = time if self.streaming and not self.fetching and self.count < CAPACITY: self.start_next() def code_fetch(self, address: int, width: int, raw_seq: bool, seq) -> int: """An opcode fetch from Game Pak ROM with the unit on; advances the clock.""" bus = self.bus self.catch_up(bus.now) halves = 2 if width == 32 else 1 address &= ~1 if width == 16 else ~3 if self.streaming and address == self.head and (self.count or (self.fetching and raw_seq)): # The fetch completes when all its halfwords are in the buffer, and takes at least # one cycle ("0 Waits": DOC). A word whose second half arrives during that cycle # costs 1 (FITTED: the mGBA suite's timing table, ARM LDM and multiply rows with # prefetch on, docs/timing.md "The Game Pak prefetch buffer"). start = bus.now ready = start while self.count < halves and self.fetching: ready += self.remaining self.catch_up(ready) if self.count >= halves: bus.now = max(start + 1, ready) self.catch_up(bus.now) value = 0 for half in range(halves): value |= bus.rom.halfword((self.head & 0x1FFFFFF) >> 1) << (16 * half) self.head += 2 self.count -= 1 if not self.fetching and self.count == 0: # Drained after a pause (full, or a 128 KB boundary): restart, N (readme). self.next_n = True self.start_next() return value # A halfword buffered but nothing coming (stopped at a 128 KB boundary): take what # there is, then an ordinary access for the rest (HYPOTHESIS). bus.now = max(start + 1, ready) self.catch_up(bus.now) value = bus.rom.halfword((self.head & 0x1FFFFFF) >> 1) self.head += 2 self.count = 0 value |= bus.cart_access(self.head, 16, False) << 16 self.head += 2 self.last = bus.now self.next_n = False self.start_next() return value # A miss: the buffer empties and the fetch is an ordinary access. A fetch in its last # cycle finishes first, as for a data access (MISS_FINISH_LAST; FITTED to alyosha-tas # prefetcher/prefetcher_branch_thumb, the timing table unchanged; docs/timing.md # "The Game Pak prefetch buffer"). if self.fetching and self.remaining <= MISS_FINISH_LAST: bus.now += self.remaining self.count = 0 self.fetching = False self.streaming = True value = bus.cart_access(address, width, seq) self.head = address + (4 if width == 32 else 2) self.last = bus.now self.next_n = False # "the prefetcher starts ... with sequential timing" (readme) self.start_next() return value