# Start here: the Game Boy Advance as a board author needs it Everything outside the ARM7TDMI is this repository's job: the memory map and its wait states, the Game Pak prefetch buffer, four DMA channels, four timers, the interrupt controller, HALT and STOP, the keypad, the serial port, the BIOS and its read protection, the picture processor and the sound unit. The CPU is `arm7tdmi-python` (`/data/emu/arm7tdmi-python`); its bus contract is in its `docs/handoff-brief.md` and summarised in [handoff-brief.md](handoff-brief.md). Sources, by the name the pin lists give them: **GBATEK** (`reference/docs/gbatek.txt`, revision of 2025-04-16; section names are quoted so you can grep), **CowBite** (`reference/docs/CowBiteSpec.htm`), **Tonc** (`reference/docs/tonc`), **gbadoc** (`reference/docs/gbadoc`). GBATEK is the base document and is itself mostly hardware-corrected; where the cycle-level emulators and hardware tests go further than it, this file says which and the test that shows it. NanoBoyAdvance 1.8.3 (`reference/src/NanoBoyAdvance/src/nba/src`, "NBA") is cited as the most complete *implementation*, never as proof (it is a detector: [validation.md](validation.md)). ## The machine | | | | --- | --- | | Models | AGB (GBA), AGS (GBA SP), OXY (Micro), the Game Boy Player (GameCube); the NDS and 3DS in GBA mode are *not* the reference (they fail `hw-test/ppu/vram-mirror`, below) | | Reference model | AGB-001 with CPU AGB (any revision); revisions as data if a test ever separates them | | System clock | 16,777,216 Hz (2^24), one cycle ≈ 59.6 ns. Every count in these documents is in these cycles | | Frame | 228 lines × 1,232 cycles = 280,896 cycles ≈ 59.727 Hz | | CPU | ARM7TDMI at the system clock; no cache; no coprocessor | | Game Boy mode | The same chip runs DMG/CGB cartridges with an SM83 inside (GBATEK "GBA Memory Usage in CGB Mode"). **Out of scope for the first build** (decided below) | ## Buses and the memory map GBATEK "GBA Memory Map", with the bus width that decides how many accesses a CPU request becomes, and the cycles per access at power-on wait states: | Region | Address | Size, mirrored | Bus | Read | Write | Cycles 8/16/32 | | --- | --- | --- | --- | --- | --- | --- | | BIOS | `0000000` | 16 KiB, not mirrored | 32 | 8/16/32 | — | 1/1/1 | | EWRAM (on-board) | `2000000` | 256 KiB, mirrored through `2FFFFFF` | 16 | 8/16/32 | 8/16/32 | 3/3/6 (WAITCNT-like control at `4000800`) | | IWRAM (on-chip) | `3000000` | 32 KiB, mirrored through `3FFFFFF` | 32 | 8/16/32 | 8/16/32 | 1/1/1 | | I/O | `4000000` | `0400`, not mirrored (except `4000800`, every 64 KiB) | 32 | 8/16/32 | 8/16/32 | 1/1/1 | | Palette | `5000000` | 1 KiB, mirrored | 16 | 8/16/32 | 16/32 (8 = both bytes) | 1/1/2, +1 if the PPU is using it | | VRAM | `6000000` | 96 KiB, mirrored in 128 KiB steps (64+32+32) | 16 | 8/16/32 | 16/32 (8: BG doubles, OBJ ignores) | 1/1/2, +1 if the PPU is using it | | OAM | `7000000` | 1 KiB, mirrored | 32 | 8/16/32 | 16/32 (8 ignored) | 1/1/1, +1 if the PPU is using it | | Game Pak ROM, WS0/1/2 | `8000000`/`A000000`/`C000000` | ≤ 32 MiB each, the same ROM | 16 | 8/16/32 | (flash carts) | WAITCNT: N and S differ; 32-bit = N+S or S+S | | Game Pak SRAM/Flash | `E000000` | 64 KiB, mirrored through `FFFFFFF` | 8 | 8 (16/32 read the byte replicated) | 8 | WAITCNT SRAM field | | Unused | elsewhere | | | open bus | ignored | 1 | Address lines A28–A31 are not connected (`10000000`+ is unused memory, open bus). The board receives **unaligned** addresses from the core (its contract: `LDR` from `3000001` reaches the bus as `3000001`); forcing alignment is the memory system's, i.e. this board's. ### Wait states (`WAITCNT`, `4000204`) GBATEK "GBA System Control". Each Game Pak access is **1 cycle plus wait states**. The fields: | Field | Bits | Values (wait states) | | --- | --- | --- | | SRAM | 0–1 | 4, 3, 2, 8 | | WS0 first (N) | 2–3 | 4, 3, 2, 8 | | WS0 second (S) | 4 | 2, 1 | | WS1 first (N) | 5–6 | 4, 3, 2, 8 | | WS1 second (S) | 7 | 4, 1 | | WS2 first (N) | 8–9 | 4, 3, 2, 8 | | WS2 second (S) | 10 | 8, 1 | | PHI output | 11–12 | not emulated | | Prefetch enable | 14 | see below | | CGB cartridge (read only) | 15 | 0 for a GBA cartridge | Power-on value `0000`; commercial games write `4317` (WS0 3/1, SRAM 8, WS2 8/8, prefetch on). Rules the board applies, all hardware-tested: - A 32-bit Game Pak access is two 16-bit accesses; the second is always S. - **Every 128 KiB boundary** of Game Pak ROM forces N (`LDMIA [801FFF8]` is N at `8020000`: GBATEK; judged by `hw-test/bus/128kb-boundary` and alyosha-tas `prefetcher/prefetcher_boundary_*`, `DMA/readme.txt`: for DMA "the NEXT access will use non-sequential timing, even if in decrement or fixed mode"). - **S after an internal cycle is N for the Game Pak.** The core reports the TRM's merged-IS `SEQ` (the fetch after an I cycle is S); the GBA's memory controller times that fetch as N. GBATEK calls the visible case the "Prefetch Disable Bug" (opcodes with I cycles that do not change R15 fetch 1N instead of 1S when prefetch is off). The board sees the `idle()` before the fetch and converts with the core's shared helper `arm7tdmi_python.gba_access(access, after_idle)`, never its own copy (core decision 1, decided by the user; [handoff-brief.md](handoff-brief.md)). - `4000800` (internal memory control) sets EWRAM's wait states (bits 24–27, default `D` = 2 waits) and can disable WRAM; GBATEK "4000800h". Mirrored every 64 KiB in I/O, the only I/O register that is. ### The Game Pak prefetch buffer GBATEK "GBA GamePak Prefetch" is short; NBA's `bus/timing.cpp` and alyosha-tas `prefetcher/readme.txt` (hardware, GBA Player) fill it in. When WAITCNT bit 14 is set and the CPU is **executing from Game Pak ROM**, the cartridge interface keeps fetching sequential halfwords into an 8-halfword buffer (4 ARM words) whenever the CPU is not using the Game Pak bus: - An opcode fetch that hits the buffer's head costs 1 cycle. - One that hits the halfword *being* fetched waits for the remaining countdown. - Anything else (a miss, a data access to the Game Pak or SRAM, a fetch from another region) stops the buffer. A data access that lands while the buffer is in the last cycle of a halfword costs one extra cycle (NBA's `StopPrefetch`, judged by alyosha-tas `prefetcher/*`, mGBA suite timing). - A full buffer stops and later restarts with N timing (alyosha-tas). - The buffer stops at a 128 KiB boundary as if full (alyosha-tas). - Only opcodes benefit; data reads from ROM do not. - Disabling prefetch makes the next Game Pak access N (NBA's `prefetch_buffer_was_disabled`; alyosha-tas `timing/prefetch_enable*`). The board can do all of this from the core's callbacks because each carries `CODE` (opcode fetch, nOPC) and `SEQ`, and `idle()` marks the cycles when the buffer runs ahead. This is the hardest piece of the board; [timing.md](timing.md) lists its cycle rules and the tests that pin each one. ## DMA Four channels (GBATEK "GBA DMA Transfers"), priority DMA0 > DMA1 > DMA2 > DMA3, registers SAD/DAD/CNT_L/CNT_H at `40000B0` + 12×n. Start timing: immediate, VBlank, HBlank, special (DMA1/2: sound FIFO; DMA3: video capture, lines 2–161). DMA0 cannot read the Game Pak; only DMA3 can write it; none can touch SRAM. - **The CPU stops while DMA owns the bus**, but keeps executing internal cycles in parallel: DMA started during an I cycle overlaps with following I cycles until the CPU next touches the bus (NBA `Bus::Idle`; alyosha-tas `Interactions/*` on hardware: "the IRQ pipeline will be stalled if the cpu is waiting to do a read or write, but not if it is doing internal cycles such as multiply. Halt counts as an internal cycle"). The core's `idle()` callbacks are exactly where the board runs this overlap. - **Locked cycles** (`LOCK`, SWP's read and write) are never split by DMA (NBA `Bus::Read`: no DMA on `Lock`). - Start-up latency: 2 cycles after the enable bit's rising edge (NBA `DMA_activated` at +2; judged by `hw-test/dma/start-delay`, Hades-Tests `dma-start-delay`); timing per transfer `2N + 2(n−1)S + xI`, x = 2, or 4 when both ends are Game Pak (GBATEK). - The DMA has its own **open-bus latch** that CPU open-bus reads see after a DMA (alyosha-tas `Bus/ReadMe.txt`, `hw-test/dma/latch`, Hades-Tests `dma-latch`). - Sound FIFO DMA moves 4 words per request, ignores CNT_L and the width bit, and does not increment the destination. ## Timers Four 16-bit up-counters at `4000100` + 4×n (GBATEK "GBA Timers"); prescaler 1/64/256/1024 from the system clock, or count-up on the previous timer's overflow (not timer 0). Writes to `TMxCNT_L` set the reload, not the counter; the reload is copied in on overflow and on a 0→1 start edge. Both register writes take effect one cycle late, the control write's start another cycle later (NBA `TM_write_reload` +1, `TM_write_control` +1 then +2; judged by `hw-test/timer/*`, Hades-Tests `timer-basic`, mGBA suite "Timer count-up"). Timers 0/1 clock the sound FIFOs. The prescaler's phase at power-on is observable (alyosha-tas `timer/timer.gba`: "Tests state of the clock divider after power on"), which is one reason the real BIOS's boot path matters ([undocumented-behavior.md](undocumented-behavior.md) C3). ## Interrupts, HALT, STOP `IE` `4000200`, `IF` `4000202` (write 1 to acknowledge), `IME` `4000208` (GBATEK "GBA Interrupt Control"). Fourteen sources: VBlank, HBlank, VCount, timers 0–3, serial, DMA 0–3, keypad, Game Pak. - The board drives the core's `cpu.irq` level; the core samples it at the start of each `step()`. The GBA's controller adds latency between a source firing and the line moving: NBA updates IE&IF one cycle after the event and the line two cycles after that (`hw/irq/irq.cpp`); judged by `hw-test/irq/irq-delay`, alyosha-tas `irq/*`, destoer `irq_delay`. The latency belongs here, not in the core (its contract: "the board delays its line by however much the hardware tests show"). - The BIOS IRQ vector at `18` saves r0–r3, r12, lr and jumps through `[3007FFC]` (GBATEK "BIOS Interrupt handling"); `3007FF8` is the IntrWait flag. - **HALT** (`HALTCNT` `4000301` bit 7 = 0, or SWI 2): the CPU clock stops until `IE & IF ≠ 0` (IME is not consulted for waking). The board stops calling `step()` and keeps clocking everything else; DMA continues (alyosha-tas: HALT counts as an internal cycle for the DMA/IRQ interaction). - **STOP** (bit 7 = 1, SWI 3): sound, video and timers stop too, until a keypad, Game Pak or serial interrupt. - `POSTFLG` `4000300`: the BIOS sets 1 after the first boot. ## Keypad and serial - `KEYINPUT` `4000130`: 10 buttons, 0 = pressed. `KEYCNT` `4000132`: an interrupt when any (OR) or all (AND) selected keys are down. The keypad IRQ wakes STOP. - **Serial** (`SIOCNT` `4000128`, `RCNT` `4000134`, multiplayer, normal 8/32, UART, JOY BUS, general-purpose): the first build emulates **no link partner**: registers, the internal-clock normal-mode transfer timing and its IRQ, and RCNT's GPIO reads, which is what the mGBA suite's SIO groups and alyosha-tas `Serial/*` check. Multiplayer with another console is later work. ## The BIOS 16 KiB of ARM code at `0`: reset, the exception vectors, the SWI functions (division, square root, arctangent, decompression, CpuSet, sound driver helpers, Halt/Stop/IntrWait), and the boot animation that checks the cartridge's logo and header checksum. - **Read protection**: data reads from the BIOS succeed only while the CPU executes inside it; otherwise they return the **last opcode the BIOS fetched** (after boot `[DC+8]`, during IRQ `[134+8]`, after IRQ `[13C+8]`, after SWI `[188+8]`; GBATEK "GBA Unpredictable Things"). The board tracks it from the core's `CODE` reads below `4000` and decides "inside the BIOS" from the address of the latest opcode fetch. Judged by jsmolka `bios.gba`, Hades-Tests `bios-openbus`, the mGBA suite's memory group. - **Bring your own**: Nintendo's BIOS is never fetched or committed. The free replacement pinned here is **Cult-of-GBA BIOS** (MIT, prebuilt `bios.bin` in `reference/src/bios-cult-of-gba`). It is good enough to boot most code but it is not the same program, so anything that depends on the BIOS's code, its cycle counts or its last-fetched opcode differs. Measured here: the mGBA suite loses 46 memory, 12 BIOS-math and 120 timing tests on NanoBoyAdvance with it ([validation.md](validation.md)), and MAME does not boot with it. **Judge runs use the real BIOS**; the free one is for CI and for people without a dump. Normmatt's `gba_bios` is a disassembly that needs the real BIOS to build, so it is not an alternative. - Local default (Aubrey's No-Intro `[BIOS]` set, read in place): `/data/emu/source/myrient.erista.me/files/No-Intro/Nintendo - Game Boy Advance/[BIOS] Nintendo Game Boy Advance Boot ROM (World).zip`, SHA-1 `300c20df6731a33952ded8c436f7f186d25d3492` (the retail BIOS; MAME's `gba.bin` has the same hash), SHA-256 `fd2547724b505f487e6dcb29ec2ecff3af35a841a77ab2e85fd87350abd36570`. The same directory holds the GameCube (Game Boy Player) variant (SHA-1 `3d4b5d09…`) and a beta. ### Open bus Reads from unused memory return the CPU's **prefetched opcode** (GBATEK "GBA Unpredictable Things"): for ARM `[$+8]`; for Thumb it depends on the region the code runs from (EWRAM/palette/VRAM/ROM: the halfword `[$+4]` twice; BIOS/OAM: `[$+4]` and `[$+6]` or `[$+2]` and `[$+4]` by alignment; IWRAM: one half new, one half left over). After a DMA, the DMA's latch instead (alyosha-tas, NBA `ReadOpenBus`). Write-only and unused I/O follow the same rule for whole unused words, and read 0 where the low half is readable. The board knows the pipeline because it served every `CODE` read; it needs no peek into the core. ## The picture processor GBATEK "GBA LCD Video Controller", "LCD Dimensions and Timings". - **Scanline**: 308 dots × 4 cycles = 1,232 cycles; 240 visible dots (960 cycles), then HBlank. **Frame**: 228 lines, 160 visible, VBlank 160–227. The HBlank flag in DISPSTAT rises well after the 960th cycle: GBATEK says 1,006, NBA 1,007, mGBA 1,008, and both emulators fail the mGBA suite's "H-blank bit start" cases (C1 in [undocumented-behavior.md](undocumented-behavior.md)). GBATEK says no HBlank IRQ is generated during VBlank; NBA and mGBA both generate them (C2). VCOUNT reads 0–227; the VCount match flag and IRQ use DISPSTAT bits 8–15. - **Modes**: 0 (four text BGs), 1 (two text, one affine), 2 (two affine), 3 (240×160 15-bit bitmap), 4 (240×160 8-bit, two pages), 5 (160×128 15-bit, two pages). In bitmap modes OBJ tiles start at `6014000`. - **Sprites**: 128 in OAM, regular or affine (32 parameter groups), 8×8 to 64×64, 16- or 256-colour, semi-transparent, OBJ-window, mosaic; the OBJ engine has a per-line cycle budget (1,210 cycles, or 954 with HBlank interval free) that limits how many render. - **Windows**: WIN0, WIN1, the OBJ window and outside, each enabling layers and effects. - **Effects**: alpha blending (EVA/EVB), brighten and darken (EVY), mosaic for BGs and OBJs. - **Affine BGs** latch BGxX/BGxY at the start of the frame and on writes, accumulate PB/PD per line (`hw-test/ppu/bgx`, `bgpd`). - **Green swap** (`4000002`): an undocumented register (`hw-test/ppu/greenswap`). - **VRAM access timing**: the PPU's own fetches occupy VRAM/palette/OAM on particular cycles, and a CPU access that collides waits a cycle (`hw-test/ppu/ram-access-timing`, alyosha-tas `ppu/Sprite_*`). This is what makes a dot-exact PPU necessary, not just a line renderer. - Output: 240×160, BGR555 per pixel. The LCD's own colour response is a display filter, not board state. ## The sound unit GBATEK "GBA Sound Controller". Two halves mixed together: - **The Game Boy's four channels** (square with sweep, square, wave, noise), at `4000060`–`400008F` with GBA register spacing. Differences from the DMG (GBATEK "Sound Channel 3"): the wave channel has **two 32-sample banks** (select and 64-sample mode in `SOUND3CNT_L`) and a forced 75 % volume; the PSG master volume is scaled 25/50/100 % by `SOUNDCNT_H`; the frame sequencer is clocked from the system clock (there is no DIV). - **DMA sound A and B**: two 32-byte FIFOs (`40000A0`, `40000A4`) of signed 8-bit samples, each popped on timer 0 or 1's overflow and refilled by DMA1/2 when half empty; volume 50/100 %, left/right enables, FIFO reset bits. - **Mixing and output**: everything is summed with `SOUNDBIAS` (default `200`), clipped to 10 bits and sampled at 32,768 Hz/9 bits (or up to 262,144 Hz at 6 bits), then sent as PWM at the system clock. - **The four Game Boy channels are the `gb-apu-python` core** (its AGB row), pinned by revision. The family rule is **never copy a chip file between repositories; extract on the second consumer**: this board was that second consumer, so the channels were extracted *with their history* from `gameboy-python`, which pins the core too ([handoff-brief.md](handoff-brief.md), decision 4). The GBA's differences in the channels (the two wave banks as a shift register, the 64-digit ring, the forced 75 %) are rules of that row, there. This board's `apu.py` is their host: the register map, the clock (four system cycles to one of the core's), the frame sequencer's clock, the FIFOs, the mixer and SOUNDBIAS. ## Game Boy (CGB) mode A CGB cartridge in an AGB switches the chip into its SM83 mode: the BIOS is not used, a separate GBC boot ROM (`[BIOS] ... Game Boy Color Mode Boot ROM`, also in the local set) runs, the LCD shows a 160×144 window. That machine is `gameboy-python` with an AGB model row plus `sm83-python`; it is **out of scope for the first build** and recorded as later work (decided by the directive that started this repository; [handoff-brief.md](handoff-brief.md)). ## A suggested module shape ``` src/gba_python/ board.py the bus callbacks: region decode, wait states, prefetch buffer, open bus, BIOS latch scheduler.py the event queue that every device schedules on (cycle-stamped) io.py the I/O map: one table of registers, read masks and handlers dma.py four channels, priority, start-up delay, the DMA latch, parallel I-cycles timer.py four timers, prescaler phase, cascade, FIFO ticks irq.py IE/IF/IME, the line delay, HALT/STOP wake-up keypad.py KEYINPUT/KEYCNT serial.py SIOCNT/RCNT, no partner ppu/ dot-timed: line timing, BG text/affine/bitmap fetchers, OBJ engine, windows, blending apu.py FIFOs, mixer, SOUNDBIAS; hosts the Game Boy channels from gb-apu-python cartridge/ ROM, SRAM, Flash 64K/128K, EEPROM 512 B/8 KiB, RTC on GPIO (cartridge.md) bios.py loading and the protection latch; the default path and hashes above testrom.py the result protocols: jsmolka r12, mGBA suite END lines, screens ```