"""The Game Boy Advance: the bus that turns the core's cycles into clocks and serves them. arm7tdmi-python makes one callback per bus cycle, internal cycles included, and says what kind each is (address, width, N or S, opcode fetch, locked); it never counts clocks. This board decides how many clocks each cycle takes and advances every device by them **inside** the callback (docs/timing.md "From a callback to clocks"): - region decode with the access times of GBATEK "GBA Memory Map" and WAITCNT's wait states; - N or S on the Game Pak: the core's SEQ after the GBA's merged-IS rule (``arm7tdmi_python.gba_access``, never a copy of it here), a 128 KiB boundary, and the access after a DMA forced N; - the Game Pak prefetch buffer, which runs ahead while the CPU executes from ROM; - DMA, which takes the bus at the CPU's next access and overlaps its internal cycles; - open bus (the CPU's prefetched opcodes, or the DMA's latch) and the BIOS read latch; - HALT, during which the board stops calling ``step()`` and skips to the next event. Clocks are advanced *before* a read returns its value and before a write lands, as NanoBoyAdvance's bus does: an event due in the access's last cycle is seen by it. """ from __future__ import annotations import sys from collections.abc import Callable from datetime import datetime from arm7tdmi_python import ARM7TDMI, CPUState, gba_access from arm7tdmi_python.access import CODE, LOCK, SEQ from gba_python.apu import APU from gba_python.bios import BIOS from gba_python.cartridge import Cartridge from gba_python.dma import DMA, DMA_ACCESS from gba_python.io import IO from gba_python.irq import GAMEPAK, IRQ from gba_python.keypad import Keypad from gba_python.ppu import PPU from gba_python.scheduler import NEVER, Scheduler from gba_python.serial import Serial from gba_python.timer import Timers # The memory arrays are read through native-order memoryview casts for speed; the GBA is # little-endian, so the host must be too. assert sys.byteorder == "little", "gba-python needs a little-endian host" #: Game Pak first-access (N) and second-access (S) totals, 1 + wait states (GBATEK "WAITCNT") N_TOTAL = (5, 4, 3, 9) S_TOTAL = ((3, 2), (5, 2), (9, 2)) # WS0, WS1, WS2: [bit] -> total ON_IWRAM = 0x100 # bits the board adds to ``last_access``: the access was to IWRAM, ON_OAM = 0x200 # to OAM, ON_ROM = 0x400 # or a data read of the Game Pak ROM ON_BUS = ON_IWRAM | ON_OAM | ON_ROM SYS_MODE = 0x1F # (offset, value) the retail BIOS leaves in the I/O registers when it jumps to the cartridge: # DISPCNT forced blank, BG2/BG3 PA = PD = 100h, SOUNDCNT_H (with both FIFO resets), # SOUNDBIAS 200h, RCNT general-purpose mode. SKIP_BIOS_IO = ( (0x000, 0x0080), (0x020, 0x0100), (0x026, 0x0100), (0x030, 0x0100), (0x036, 0x0100), (0x082, 0x880E), (0x088, 0x0200), (0x134, 0x8000), ) SVC_BANK, IRQ_BANK = 2, 4 class GBA: """One console: a BIOS, a cartridge, the CPU core and every unit on the bus.""" def __init__( self, bios: BIOS, rom: bytes, save: bytes | None = None, save_type: str | None = None, *, skip_bios: bool = False, rtc_start: datetime | None = None, ) -> None: self.bios = bios self.bios_data = bios.data self.scheduler = Scheduler() self.cartridge = Cartridge(rom, self.scheduler, save, save_type, rtc_start) self.ewram = bytearray(0x40000) self.iwram = bytearray(0x8000) self.cpu = ARM7TDMI(self._cpu_read, self._cpu_write, self._cpu_idle) self.irq = IRQ(self.scheduler, self.cpu) self.irq.cpu_cycles = self.cpu_cycles self.irq.cpu_waiting = self.cpu_waiting self.irq.overlapping = self.dma_overlapping if self.cartridge.gpio is not None: self.cartridge.gpio.device.raise_irq = self._cartridge_irq self.dma = DMA(self.scheduler, self.irq, self) self.ppu = PPU(self.scheduler, self.irq, self.dma) self.apu = APU(self.dma, self.scheduler) self.timers = Timers(self.scheduler, self.irq, self.apu.timer_overflow) self.keypad = Keypad(self.irq) self.serial = Serial(self.scheduler, self.irq) self.io = IO(self) self._make_views() # Wait states (WAITCNT 4000204 and the internal memory control at 4000800). self.waitcnt = 0 self.memctl = 0x0D000020 self.ewram16 = 3 # cycles for an 8/16-bit EWRAM access self.ewram32 = 6 self.rom_n = [5, 5, 5] # 16-bit N totals for WS0-2 self.rom_s = [3, 5, 9] # 16-bit S totals self.sram_wait = 5 self.prefetch_enabled = False self.prefetch_was_disabled = False # The prefetch buffer (NanoBoyAdvance bus/timing.cpp; docs/timing.md). self.pf_active = False self.pf_head = 0 # the next opcode address the buffer can hand out self.pf_last = 0 # the opcode address being fetched self.pf_count = 0 # halfwords buffered (an ARM opcode is two) self.pf_capacity = 8 self.pf_width = 2 # the buffer fetches halfwords in either state self.pf_countdown = 0 # cycles until the one in flight lands self.pf_duty = 0 # cycles per halfword (the region's 16-bit S time) self.pf_paused = False # stopped full (or at a 128 KiB boundary) until emptied self.pf_paused_at = 0 # the cycle the buffer paused self.pf_lockstep = False # since it started, the buffer has never got ahead of the CPU self.last_access = 0 # the previous bus access's bits (for "N after a DMA") self.iwram_bus = 0 # what was last on IWRAM's 32-bit bus, lane by lane self.oam_bus = 0 # the OAM word last read or written self.rom_bus = 0 # the last data read from the Game Pak ROM self.dma_rom_next = 0 # the address after a DMA's last Game Pak access self._after_idle = False # the previous CPU callback was an internal cycle self._parallel = 0 # internal cycles still free because a DMA ran during them self.bios_latch = 0 # the last word the BIOS supplied (GBATEK BIOS protection) self.halted = False self.waited_cycles = 0 # cycles the CPU has waited for a DMA to free the bus self.bus_wait = -1 # the cycle the CPU began waiting for a DMA to free the bus, or -1 self._overlap = self._overlap_start = self._overlap_cpu = 0 # a DMA over I cycles self.postflg = 0 self.debug_log: list[str] = [] # lines sent through mGBA's debug port self.debug_enabled = False self.debug_buffer = bytearray(0x100) self.reset(skip_bios=skip_bios) def _make_views(self) -> None: """Halfword and word views of the memories (native order: little-endian hosts).""" for name, memory in ( ("_ewram", self.ewram), ("_iwram", self.iwram), ("_bios", self.bios_data), ("_palette", self.ppu.palette), ("_vram", self.ppu.vram), ("_oam", self.ppu.oam), ): setattr(self, name + "16", memoryview(memory).cast("H")) setattr(self, name + "32", memoryview(memory).cast("I")) # ----- state (gba_python.state) ------------------------------------------------------- def __getstate__(self) -> dict: state = self.__dict__.copy() for name in list(state): if isinstance(state[name], memoryview): del state[name] # rebuilt from the memories on load del state["io"] # a table of closures, rebuilt on load return state def __setstate__(self, state: dict) -> None: self.__dict__.update(state) self.io = IO(self) self._make_views() def _cartridge_irq(self) -> None: self.irq.raise_(GAMEPAK) # ----- power-on ----------------------------------------------------------------------- def reset(self, *, skip_bios: bool = False) -> None: cpu = self.cpu if skip_bios: # Where the BIOS leaves a cartridge: System mode, ARM, the three stacks it sets # (GBATEK "BIOS RAM Usage"), PC 8000000 (NanoBoyAdvance SkipBootScreen). For # development only: never for a timing judge (user decision 2). banks = [[0] * 7 for _ in range(6)] banks[SVC_BANK][5] = 0x03007FE0 banks[IRQ_BANK][5] = 0x03007FA0 registers = [0] * 16 registers[13] = 0x03007F00 registers[14] = 0x08000000 # the BIOS enters the cartridge with BX LR cpu.restore_state(CPUState(registers=registers, banks=banks, cpsr=SYS_MODE)) self.postflg = 1 # The registers the retail BIOS leaves set at the first fetch from 8000000, read # off this board booting it (docs/undocumented-behavior.md C19); mGBA's GBAIOInit # sets the same values. Left out: VCOUNT (126 there) and timer 0's stopped counter. for offset, value in SKIP_BIOS_IO: self.io.write(0x04000000 + offset, 16, value) cpu.start_at(0x08000000) else: cpu.reset() # ----- clocks ------------------------------------------------------------------------- def step(self, cycles: int) -> None: """Advance every device ``cycles`` clocks (NanoBoyAdvance ``Bus::Step``).""" scheduler = self.scheduler target = scheduler.now + cycles if target >= scheduler.next_time: scheduler.run_until(target) else: scheduler.now = target if self.pf_active and not self.pf_paused: self.pf_countdown -= cycles while self.pf_countdown <= 0: self.pf_count += 1 if ( self.pf_count < self.pf_capacity and self.prefetch_enabled and (self.pf_last + 2) & 0x1FFFF ): self.pf_last += self.pf_width self.pf_countdown += self.pf_duty else: # Full, or at a 128 KiB boundary (alyosha-tas prefetcher/readme.txt: "it # stops and behaves as though it is full"; bounday_test_1): the buffer # pauses, and stays paused while it holds opcodes # (alyosha-tas prefetcher/readme.txt: "the prefetch unit pauses until the # buffer is empty"; prefetcher_full_arm_2). NanoBoyAdvance keeps counting # here, handing out opcodes it never fetched. self.pf_paused = True self.pf_paused_at = target + self.pf_countdown # when the last one landed break def update_wait_states(self) -> None: value = self.waitcnt self.sram_wait = N_TOTAL[value & 3] self.rom_n = [N_TOTAL[value >> 2 & 3], N_TOTAL[value >> 5 & 3], N_TOTAL[value >> 8 & 3]] self.rom_s = [ S_TOTAL[0][value >> 4 & 1], S_TOTAL[1][value >> 7 & 1], S_TOTAL[2][value >> 10 & 1], ] enabled = bool(value & 0x4000) if self.prefetch_enabled and not enabled: self.prefetch_was_disabled = True self.prefetch_enabled = enabled wait = 15 - (self.memctl >> 24 & 0xF) self.ewram16 = 1 + wait self.ewram32 = 2 * (1 + wait) # ----- the prefetch buffer ------------------------------------------------------------ def _stop_prefetch(self) -> None: if self.pf_active: # A Game Pak data access in the cycle the buffer is landing a halfword costs one # more (NBA StopPrefetch; alyosha-tas prefetcher/*), while executing from ROM. if self.pf_countdown == 1 and 0x08000000 <= self.cpu.r[15] <= 0x0DFFFFFF: self.step(1) self.pf_active = False def _rom_access(self, address: int, code: bool, sequential: bool, cycles: int) -> None: """Clock one Game Pak ROM access of ``cycles`` and run the prefetch buffer around it (NanoBoyAdvance ``Bus::Prefetch``).""" if not code: self._stop_prefetch() self.step(cycles) return if self.pf_active and address == self.pf_head: # The buffer holds halfwords, whatever the CPU's state: an ARM opcode is two # (alyosha-tas prefetcher_branch_thumb_arm: Thumb code after a BX reads the # halfwords of words ARM code buffered). halves = 1 if self.cpu.thumb else 2 if self.pf_count >= halves: # The opcode is in the buffer: one cycle. self.pf_lockstep = False self.pf_count -= halves self.pf_head += halves << 1 self.step(1) return just_started = self.pf_countdown == self.pf_duty if ( not self.pf_paused and self.pf_last == address + (self.pf_count << 1) and (sequential or self.pf_count or not just_started or not self.pf_lockstep) ): # The rest of the opcode is being fetched: wait for it to land. A branch onto # a fetch that is only now starting, by an empty buffer that has never got # ahead of the CPU, is the CPU's own N access instead (below; alyosha-tas # prefetcher/readme.txt: "the instruction fetch is done with non-sequential # timing"; prefetcher_branch_thumb_2, _6). A branch past halfwords still in # the buffer flushes it, the fetch in flight too (prefetcher_branch_thumb_3). if not just_started: self.pf_lockstep = False self.step(self.pf_countdown + self.pf_duty * (halves - self.pf_count - 1)) self.pf_count -= halves self.pf_head += halves << 1 return if self.pf_active and self.pf_paused and not self.pf_count and sequential: # The buffer emptied after a pause: the fetch that restarts it is N (alyosha-tas # prefetcher/readme.txt). region = (address >> 25) - 4 n16, s16 = self.rom_n[region], self.rom_s[region] cycles = n16 if cycles == s16 else n16 + s16 # A buffer stopped at a 128 KiB boundary keeps its fetch rhythm: the CPU's fetch pays # the stop penalty when it comes one cycle before a fetch would have landed # (alyosha-tas bounday_test_1, prefetcher_boundary_1-4: a push of 1, 2, 3, 4 # registers before the fetch reads 52h, 52h, 54h, 54h). if ( self.pf_active and self.pf_paused and not (self.pf_last + 2) & 0x1FFFF and (self.scheduler.now - self.pf_paused_at) % self.pf_duty == self.pf_duty - 1 ): cycles += 1 self._stop_prefetch() if self.prefetch_was_disabled: # The first access after disabling the buffer is N (NBA # prefetch_buffer_was_disabled; alyosha-tas timing/prefetch_enable*). region = (address >> 25) - 4 n16, s16 = self.rom_n[0], self.rom_s[region] if cycles == s16: cycles = n16 elif cycles == 2 * s16: cycles = self.rom_n[0] + self.rom_s[0] self.prefetch_was_disabled = False self.step(cycles) if self.prefetch_enabled: region = (address >> 25) - 4 thumb = self.cpu.thumb self.pf_active = True self.pf_paused = False self.pf_count = 0 self.pf_duty = self.rom_s[region] self.pf_countdown = self.pf_duty self.pf_last = self.pf_head = address + (2 if thumb else 4) self.pf_lockstep = True # no fetch of its own yet: each lands as the CPU asks def _rom_sequential(self, address: int, width: int, access: int) -> bool: """Whether a Game Pak access is S. The cartridge's address counter has 16 bits, so a sequential run cannot carry across a 128 KiB boundary; besides the access's own SEQ: - a CPU access at a 128 KiB boundary is N (GBATEK; NanoBoyAdvance), and so is the CPU's first Game Pak access after a DMA (the DMA moved the counter); - a DMA access is N when its *previous* Game Pak access ended at a boundary, whichever way its addresses move: "the NEXT access will use non-sequential timing, even if in decrement or fixed mode" (alyosha-tas DMA/readme.txt). A decrementing DMA that reads the boundary address itself stays S (hw-test/bus/128kb-boundary). """ if access & DMA_ACCESS: sequential = access & SEQ and self.dma_rom_next & 0x1FFFF != 0 self.dma_rom_next = (address & -(width >> 3)) + (width >> 3) return bool(sequential) if not access & SEQ or address & 0x1FFFF == 0: return False return not self.last_access & DMA_ACCESS # ----- the CPU's callbacks ------------------------------------------------------------ def _run_dma(self) -> int: """Run the DMA that holds the bus; return its cycles. A DMA that writes HALTCNT stops the CPU's clock right where the CPU is waiting, mid-instruction, so the rest of that instruction runs after the wake-up (hw-test/haltcnt "HALTCNT CPUSET DMA").""" cycles = self.dma.run() while self.dma.runnable and not self.halted: # A channel that became ready as the last one's closing cycle ended goes next: # the CPU does not get an access in between (alyosha-tas DMA_pause_timing_end_4). cycles += self.dma.run() if self.halted: if self.bus_wait >= 0: self.bus_wait = -1 self.irq.overlap(self._overlap_start, self._overlap_cpu, 0, True) self._run_halted(NEVER) return 0 return cycles def _wait_for_dma(self) -> None: """The CPU wants the bus and a DMA has it: the CPU's clock stops until the DMA ends, and with it the IRQ synchronizer (alyosha-tas Interactions/ReadMe.txt; quirk 10).""" self._overlap = 0 self.bus_wait = self.scheduler.now self.waited_cycles += self._run_dma() self.bus_wait = -1 self.irq.resume() def _cpu_read(self, address: int, width: int, access: int) -> int: access = gba_access(access, self._after_idle) self._after_idle = False if self.bus_wait >= 0: self._settle_overlap(True) if self.dma.runnable and not access & LOCK: self._wait_for_dma() self.cpu.irq = self.irq.level return self.bus_read(address, width, access) def _cpu_write(self, address: int, width: int, value: int, access: int) -> None: access = gba_access(access, self._after_idle) self._after_idle = False if self.bus_wait >= 0: self._settle_overlap(True) if self.dma.runnable and not access & LOCK: self._wait_for_dma() self.cpu.irq = self.irq.level self.bus_write(address, width, value, access) def _cpu_idle(self, address: int) -> None: # The CPU runs internal cycles in parallel with a DMA: a DMA that starts now runs to # its end, and the following internal cycles are free until the CPU touches the bus # or they outlast it (NanoBoyAdvance Bus::Idle; alyosha-tas Interactions/*). self._after_idle = True self.cpu.irq = self.irq.level if self.dma.runnable: if self.bus_wait >= 0: self._settle_overlap(True) self._overlap_cpu = self.cpu_cycles() self.bus_wait = self._overlap_start = self.scheduler.now self._overlap = 1 # under way: line changes wait to be placed on the CPU's clock self._parallel = self._overlap = self._run_dma() if self._parallel == 0: self.step(1) else: self._parallel -= 1 if self.bus_wait >= 0: self._settle_overlap(self._parallel == 0) def _settle_overlap(self, final: bool) -> None: """The CPU's clock ran through the internal cycles a DMA overlapped and stopped when the CPU wanted the bus: the IRQ synchronizer counts only the first (quirk 10).""" used = self._overlap - self._parallel if final: self.waited_cycles += self._parallel self.bus_wait = -1 self._overlap = 0 self.irq.overlap(self._overlap_start, self._overlap_cpu, used, final) # ----- the bus ------------------------------------------------------------------------ def bus_read(self, address: int, width: int, access: int) -> int: """One access as the GBA's bus serves it, clocks included (CPU or DMA).""" self._parallel = 0 page = address >> 24 value: int if page == 0x03: self.step(1) offset = address & 0x7FFF value = ( self._iwram32[offset >> 2] if width == 32 else self._iwram16[offset >> 1] if width == 16 else self.iwram[offset] ) self._on_iwram_bus(address, width, value) access |= ON_IWRAM elif 0x08 <= page <= 0x0D: sequential = self._rom_sequential(address, width, access) region = (page >> 1) - 4 if width == 32: cycles = ( self.rom_s[region] * 2 if sequential else self.rom_n[region] + self.rom_s[region] ) self._rom_access(address & ~3, bool(access & CODE), sequential, cycles) value = self.cartridge.read32(address, bool(sequential)) if not access & CODE: self.rom_bus = value access |= ON_ROM else: cycles = self.rom_s[region] if sequential else self.rom_n[region] self._rom_access(address & ~1, bool(access & CODE), sequential, cycles) value = self.cartridge.read16(address, bool(sequential)) if not access & CODE: self.rom_bus = value * 0x10001 # the Game Pak's 16 bits on both halves access |= ON_ROM if width == 8: value = value >> ((address & 1) << 3) & 0xFF elif page == 0x02: self.step(self.ewram32 if width == 32 else self.ewram16) offset = address & 0x3FFFF value = ( self._ewram32[offset >> 2] if width == 32 else self._ewram16[offset >> 1] if width == 16 else self.ewram[offset] ) elif page == 0x04: self.step(1) value = self.io.read(address, width) elif page == 0x00: self.step(1) value = ( self._read_bios(address, width) if address < 0x4000 else self._open_bus(address, width) ) elif page == 0x05: self._ppu_wait(self.ppu.palette_busy, 2 if width == 32 else 1) offset = address & 0x3FF value = ( self._palette32[offset >> 2] if width == 32 else self._palette16[offset >> 1] if width == 16 else self.ppu.palette[offset] ) elif page == 0x06: offset = address & 0x1FFFF ppu = self.ppu self._ppu_wait( ppu.obj_vram_busy if offset >= ppu.sprite_vram_boundary else ppu.bg_vram_busy, 2 if width == 32 else 1, ) if offset >= 0x18000: offset &= ~0x8000 if offset < self.ppu.sprite_vram_boundary: self.last_access = access return 0 # the bitmap modes' hole: 6018000-601BFFF (quirk 5) value = ( self._vram32[offset >> 2] if width == 32 else self._vram16[offset >> 1] if width == 16 else self.ppu.vram[offset] ) elif page == 0x07: self._ppu_wait(self.ppu.oam_busy, 1) # OAM's bus is 32 bits wide offset = address & 0x3FF value = ( self._oam32[offset >> 2] if width == 32 else self._oam16[offset >> 1] if width == 16 else self.ppu.oam[offset] ) self.oam_bus = self._oam32[offset >> 2] access |= ON_OAM elif page == 0x0E or page == 0x0F: self._stop_prefetch() self.step(self.sram_wait) byte = self.cartridge.read_sram(address) # An 8-bit bus: wider reads see the byte on every lane (quirk 6). value = byte * 0x01010101 & ((1 << width) - 1) else: self.step(1) value = self._open_bus(address, width) self.last_access = access return value def bus_write(self, address: int, width: int, value: int, access: int) -> None: self._parallel = 0 page = address >> 24 if page == 0x03: self.step(1) offset = address & 0x7FFF if width == 32: self._iwram32[offset >> 2] = value elif width == 16: self._iwram16[offset >> 1] = value else: self.iwram[offset] = value self._on_iwram_bus(address, width, value) access |= ON_IWRAM elif page == 0x02: self.step(self.ewram32 if width == 32 else self.ewram16) offset = address & 0x3FFFF if width == 32: self._ewram32[offset >> 2] = value elif width == 16: self._ewram16[offset >> 1] = value else: self.ewram[offset] = value elif page == 0x04: self.step(1) self.io.write(address, width, value) elif page == 0x05: offset = address & 0x3FF busy = self.ppu.palette_busy if width == 32: # two halfwords, each waiting its own turn (NBA WritePRAM) self._ppu_wait(busy, 1) self._palette16[offset >> 1 & ~1] = value & 0xFFFF self._ppu_wait(busy, 1) self._palette16[offset >> 1 | 1] = value >> 16 elif width == 16: self._ppu_wait(busy, 1) self._palette16[offset >> 1] = value else: self._ppu_wait(busy, 1) self._palette16[offset >> 1] = value * 0x0101 # both bytes (quirk 4) elif page == 0x06: if width == 32: # two halfwords, each waiting its own turn (NBA WriteVRAM) self._write_vram(address & ~3, 16, value & 0xFFFF) self._write_vram((address & ~3) | 2, 16, value >> 16) else: self._write_vram(address, width, value) elif page == 0x07: self._ppu_wait(self.ppu.oam_busy, 1) offset = address & 0x3FF if width == 32: self._oam32[offset >> 2] = value elif width == 16: self._oam16[offset >> 1] = value # OAM ignores 8-bit writes (quirk 4) self.oam_bus = self._oam32[offset >> 2] access |= ON_OAM elif 0x08 <= page <= 0x0D: sequential = self._rom_sequential(address, width, access) region = (page >> 1) - 4 self._stop_prefetch() cartridge = self.cartridge if width == 32: self.step( self.rom_s[region] * 2 if sequential else self.rom_n[region] + self.rom_s[region] ) cartridge.write16(address & ~3, value & 0xFFFF, bool(sequential)) cartridge.write16((address & ~3) | 2, value >> 16, True) else: self.step(self.rom_s[region] if sequential else self.rom_n[region]) cartridge.write16( address, value * 0x0101 if width == 8 else value, bool(sequential) ) elif page == 0x0E or page == 0x0F: self._stop_prefetch() self.step(self.sram_wait) # The byte lane the address selects from the (rotated) value (quirk 6). if width == 16: value >>= (address & 1) << 3 elif width == 32: value >>= (address & 3) << 3 self.cartridge.write_sram(address, value & 0xFF) else: self.step(1) # the BIOS and unused memory ignore writes self.last_access = access def _ppu_wait(self, busy: Callable[[], bool], cycles: int) -> None: """Clock a palette, VRAM or OAM access of ``cycles``: each cycle in which the PPU read the same memory is repeated (NBA ``Bus::ReadVRAM`` and friends; quirk 18).""" step = self.step for _ in range(cycles): step(1) while busy(): step(1) def _write_vram(self, address: int, width: int, value: int) -> None: """One 8- or 16-bit VRAM write, after its wait.""" offset = address & 0x1FFFF ppu = self.ppu boundary = ppu.sprite_vram_boundary self._ppu_wait(ppu.obj_vram_busy if offset >= boundary else ppu.bg_vram_busy, 1) if width == 8: if offset < boundary: self._vram16[offset >> 1] = value * 0x0101 # BG VRAM: both bytes # OBJ VRAM ignores 8-bit writes (quirk 4) return if offset >= 0x18000: offset &= ~0x8000 if offset < boundary: return # the bitmap modes' hole (quirk 5) self._vram16[offset >> 1] = value # ----- the BIOS and open bus ---------------------------------------------------------- def _read_bios(self, address: int, width: int) -> int: """The BIOS answers only while the CPU executes inside it; otherwise every read sees the last word it supplied (GBATEK "GBA Unpredictable Things"; quirk 1).""" address &= -(width >> 3) # the bus ignores the low bits the width does not use if self.cpu.r[15] < 0x4000: self.bios_latch = self._bios32[address >> 2] value = self.bios_latch >> ((address & 3) << 3) return value & ((1 << width) - 1) def _on_iwram_bus(self, address: int, width: int, value: int) -> None: """IWRAM's own 32-bit bus keeps what was last on each byte lane: a 16-bit or 8-bit access changes its lanes only (quirk 24).""" if width == 32: self.iwram_bus = value elif width == 16: shift = (address & 2) << 3 self.iwram_bus = self.iwram_bus & ~(0xFFFF << shift) | (value & 0xFFFF) << shift else: shift = (address & 3) << 3 self.iwram_bus = self.iwram_bus & ~(0xFF << shift) | (value & 0xFF) << shift def _open_bus(self, address: int, width: int) -> int: """What an unused address reads: the CPU's prefetched opcodes, shaped by where it executes and its state (GBATEK; NanoBoyAdvance ``ReadOpenBus``; quirk 2), or the DMA's latch right after a DMA.""" shift = (address & 3 & -(width >> 3)) << 3 # aligned to the width, as the bus is last = self.last_access if last & DMA_ACCESS: return self.dma.latch >> shift & ((1 << width) - 1) if last & ON_BUS and not last & CODE: # The CPU's last cycle moved data, not an opcode, and it is still on the bus: for # IWRAM and OAM the memory's whole 32-bit bus whatever the access's width, for # the Game Pak its 16 bits twice (alyosha-tas Bus/DMA_IWRAM_Bus, DMA_OAM_Bus, # LDRSH_misaligned; quirk 24). word = ( self.iwram_bus if last & ON_IWRAM else self.oam_bus if last & ON_OAM else self.rom_bus ) return (word >> shift) & ((1 << width) - 1) cpu = self.cpu older, newer = cpu.pipeline if cpu.thumb: r15 = cpu.r[15] region = r15 >> 24 if region == 0x03: word = older | newer << 16 if r15 & 2 == 0 else newer | older << 16 elif region == 0x00 or region == 0x07: # GBATEK: [$+4] and [$+6] when misaligned; $+6 is not fetched yet (NBA TODO). word = older | newer << 16 if r15 & 2 == 0 else newer * 0x10001 elif region in (0x02, 0x05, 0x06) or 0x08 <= region <= 0x0D: word = newer * 0x10001 else: word = 0 else: word = newer return word >> shift & ((1 << width) - 1) # ----- running ------------------------------------------------------------------------ def run(self, cycles: int) -> None: """Run for ``cycles`` system clocks (instructions may overrun by a few).""" scheduler = self.scheduler target = scheduler.now + cycles cpu_step = self.cpu.step while scheduler.now < target: if self.halted: self._run_halted(target) else: cpu_step() def _run_halted(self, target: int) -> None: """HALT: the CPU's clock is stopped; everything else runs until IE & IF is nonzero (IME is not consulted for waking). DMA still runs (NanoBoyAdvance ``Core::Run``).""" scheduler = self.scheduler irq = self.irq during = False # the wake-up came while a DMA had the bus while scheduler.now < target and not irq.available: if self.dma.runnable: self.dma.run() # A wake-up that came while the DMA had the bus has had its cycle by the # time the bus is free (alyosha-tas Interactions/Halt_DMA_IRQ_Read_OAM). during = irq.available and irq.available_at < scheduler.now continue self.step(max(1, min(scheduler.next_time, target) - scheduler.now)) if irq.available: if not during: self.step(1) self.halted = False def run_frame(self) -> None: """Run until the PPU next wraps from line 227 to line 0.""" frame = self.ppu.frame while self.ppu.frame == frame: self.run(1232) def halt(self) -> None: """A write of HALTCNT bit 7 = 0 from inside the BIOS.""" self.halted = True self.step(1) def is_halted(self) -> bool: return self.halted def cpu_waiting(self) -> bool: """The CPU wants the bus and a DMA has it: the CPU's clock is stopped.""" return self.bus_wait >= 0 def dma_overlapping(self) -> bool: """A DMA is running over the CPU's internal cycles: how many of its cycles the CPU's clock also ran is known when the CPU next asks for the bus.""" return self.bus_wait >= 0 and self._overlap > 0 def cpu_cycles(self) -> int: """Cycles the CPU's clock has run: the system clock less the cycles the CPU has waited for a DMA to free the bus (the IRQ synchronizer's clock; a HALT does not stop it).""" waiting = self.scheduler.now - self.bus_wait if self.bus_wait >= 0 else 0 return self.scheduler.now - self.waited_cycles - waiting