# Timing: what the board does on each cycle All counts are system-clock cycles (16,777,216 Hz). The core (`arm7tdmi-python`) makes one callback per CPU bus cycle and says what kind it is; **this board turns each callback into clocks** and advances every device inside it. Rows name their source and the test that judges them; "NBA" means NanoBoyAdvance 1.8.3's source (a detector that passes the most hardware tests measured here, [validation.md](validation.md)), "GBATEK" the pinned text. ## From a callback to clocks ``` read(address, width, access) access: SEQ=1, CODE=2, LOCK=8 write(address, width, value, access) idle(address) one I cycle ``` | Callback | Clocks | | --- | --- | | `idle()` | 1 (or 0 while it overlaps a running DMA; [DMA](#dma)) | | BIOS, IWRAM, I/O, OAM | 1 for any width | | Palette, VRAM | 1 for 8/16 bits, 2 for 32 bits; +1 when the PPU holds the bus that cycle | | EWRAM | 1 + w for 8/16, 2 × (1 + w) for 32; w = 2 by default (`4000800` bits 24–27: w = 15 − value) | | Game Pak ROM, 16 bits | 1 + N-wait or 1 + S-wait of the region (table below), or 1 if the prefetch buffer has it | | Game Pak ROM, 32 bits | (16-bit N or S) + (16-bit S): two halves, the second always S | | Game Pak SRAM/Flash | 1 + SRAM wait, any width (8-bit bus; 16/32 replicate the byte) | | unused | 1 | Game Pak wait states from `WAITCNT` (GBATEK "GBA System Control"; NBA `UpdateWaitStateTable` writes them as total cycles): | | N (first) | S (second) | | --- | --- | --- | | WS0 `8000000` | 1 + (4, 3, 2, 8)[bits 2–3] → 5, 4, 3, 9 | 1 + (2, 1)[bit 4] → 3, 2 | | WS1 `A000000` | 1 + (4, 3, 2, 8)[bits 5–6] | 1 + (4, 1)[bit 7] → 5, 2 | | WS2 `C000000` | 1 + (4, 3, 2, 8)[bits 8–9] | 1 + (8, 1)[bit 10] → 9, 2 | | SRAM `E000000` | 1 + (4, 3, 2, 8)[bits 0–1] | same as N | The board, not the core, decides **N or S on the Game Pak**: 1. The core's `SEQ` is the TRM's pin. After an `idle()` the core says S (merged IS); the GBA times that access as **N** (GBATEK "Prefetch Disable Bug"; every accurate detector; judged by the mGBA suite timing group and alyosha-tas `prefetcher/*`). The board applies this by calling the core's `arm7tdmi_python.gba_access(access, after_idle)` on every access, never with its own copy of the rule (arm7tdmi-python `17fd0c8`). 2. An access at a **128 KiB boundary** (`address & 1FFFF == 0`) is N whatever `SEQ` says (GBATEK; `hw-test/bus/128kb-boundary`, which NBA and mGBA both fail in part). 3. The first access after **disabling the prefetch buffer** is N (NBA `prefetch_buffer_was_disabled`; alyosha-tas `timing/prefetch_enable*`). 4. After a DMA touched the Game Pak, the CPU's next Game Pak access is N (alyosha-tas `DMA/readme.txt`: the cartridge's address counter moved). ## The prefetch buffer Only when WAITCNT bit 14 is set. The skeleton is NBA's (`Bus::Prefetch`, `StopPrefetch`, `Step` in `bus/timing.cpp`); alyosha-tas's `prefetcher/*` ROMs (hardware, GBA Player) overrule it in the five places marked **(h)**. State: `active`, `head` (the next halfword it can hand out), `count` (halfwords buffered, at most 8), `last` (the halfword being fetched), `countdown` (cycles until it lands), `duty` (the region's 16-bit S time), `paused`, `lockstep`. | Event | Effect | | --- | --- | | `CODE` read at `head` with the opcode buffered (`count ≥` 1 Thumb, 2 ARM) | 1 cycle; `count −=` 1 or 2, `head +=` 2 or 4 | | `CODE` read at `head`, the rest of the opcode in flight (`last == head + 2·count`) | wait for it to land (`countdown`, plus `duty` for an ARM opcode's second half); then as above | | ... unless the read is a branch (N), the buffer is empty, its fetch is only now starting (`countdown == duty`), and it has never got ahead of the CPU since it started (`lockstep`) | **(h)** the CPU's own N access instead: stop, then as below | | `CODE` read from the Game Pak, anything else (a branch past halfwords still buffered included) | **(h)** stop the buffer (below; what it holds and what is in flight are dropped), pay the normal access, then start it: `count = 0`, `last = head = address + 2` (Thumb) or `+ 4` (ARM), `countdown = duty`, `lockstep` | | any non-`CODE` Game Pak access | stop the buffer, then the normal access | | every cycle that passes (inside any callback) | `countdown −=` cycles; when it reaches 0, `count += 1` and fetch the next halfword (`last += 2`, `countdown += duty`) unless the buffer is full **(h)** or the next halfword is at a 128 KiB boundary **(h)**: then it pauses | | a `CODE` fetch that finds a paused buffer emptied | N, not S (h) | | a `CODE` fetch past a buffer paused at a 128 KiB boundary | **(h)** the stopped buffer keeps its `duty` rhythm: one cycle more when the fetch comes one cycle before a fetch would have landed | | stop | if the CPU is executing from the Game Pak and a halfword is one cycle from landing (`countdown == 1`), the access pays **one extra cycle**; then `active = false` | The buffer holds halfwords in both states: Thumb code reached by a `BX` from ARM reads the halfwords of the words ARM code buffered (`prefetcher_branch_thumb_arm`). NBA counts opcodes (an ARM word is one entry), so its rule "in ARM, `countdown == duty/2 + 1`" for the stop penalty is the first halfword of a word one cycle from landing. "Lockstep" is the readme's case "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": a fetch the CPU and the buffer start in the same cycle is the CPU's, but once an internal cycle or a data access has let the buffer fetch on its own, a branch to its next halfword waits for it (`prefetcher_branch_thumb_4` against `_2`). NBA 1.8.3 fails 8 of alyosha-tas's 18 `prefetcher/*` ROMs and mGBA 16 ([validation.md](validation.md)); the board passes 17. `scripts/nba_lockstep.py --nba-model prefetch` swaps in NBA's buffer. ## DMA | Rule | Value | Source / judge | | --- | --- | --- | | Start-up after the enable bit's 0→1 write (immediate mode) | 2 cycles, then the channel requests the bus | NBA `DMA_activated` +2; `hw-test/dma/start-delay` (NBA passes), Hades-Tests `dma-start-delay` (NBA 4/8: open) | | Cost of n units | 2N + 2(n−1)S + 2I; 4I when both ends are Game Pak | GBATEK "Transfer Rate/Timing" | | Game Pak boundary inside a DMA | the next access is N, even when decrementing or fixed | alyosha-tas `DMA/*` | | `hw-test/dma/force-nseq-access` | a DMA's Game Pak and EWRAM accesses are N at a point the test pins | NBA passes, mGBA fails | | Priority | DMA0 > 1 > 2 > 3; a higher channel interrupts a lower one between units | GBATEK; destoer `dma_priority` | | CPU and DMA | the CPU stops at its next bus access; its I cycles overlap the DMA | NBA `Bus::Idle`; alyosha-tas `Interactions/*` | | Two DMAs end to end | a channel whose start delay ends as another's closing cycle does runs next; a cycle later, the CPU's access has begun and the channel waits for it | alyosha-tas `DMA_pause_timing_end_4`, `_end_3` | | `LOCK` | DMA never starts between SWP's read and write | NBA; core contract | | HBlank DMA | requested at the HBlank flag's rise (line cycle 1,007 in NBA) on lines 0–159 | NBA `RequestHblankDMA` | | VBlank DMA | requested at the start of line 160 | NBA | | Video capture (DMA3, special) | lines 2–161, 3 cycles after the line starts; stops at 162 | NBA; GBATEK | | Sound FIFO (DMA1/2, special) | 4 words when the FIFO has three words or fewer at the timer overflow that takes its sample, runnable 3 cycles later | NanoBoyAdvance; alyosha-tas `fifo_dma/*` (C28) | ## Interrupt latency The core samples `cpu.irq` at the start of each `step()` (the end of the previous instruction) and does not model a synchronizer. The board provides the GBA's delay (`irq.py`): 1. A source raises its IF bit in the cycle the event happens (an I/O write to IE/IF/IME lands one cycle after the write's callback). 2. One cycle later, `IE & IF` (and IME) is re-evaluated. 3. One cycle of the CPU's clock after that, the CPU's IRQ input follows (the synchronizer). 4. The CPU looks at the input when it begins a bus cycle; the board copies it to `cpu.irq` at the start of every CPU access, so what the core sees at an instruction boundary is the input as it was when the instruction's last cycle began (quirk 23). With one-cycle accesses that is three cycles from step 1 to the boundary, as in NBA `hw/irq/irq.cpp` (which counts two cycles in step 3 and looks at the boundary). With wait states the look comes before them. Judged by `hw-test/irq/irq-delay` (NBA passes, mGBA fails 2 of 3), destoer `irq_delay`, alyosha-tas `irq/*` (16 ROMs: NBA fails 2, mGBA 14) and `Interactions/*`. The synchronizer runs on the CPU's clock, which a DMA stops only while the CPU waits for the bus: not through internal cycles the DMA overlaps, and not in HALT (quirk 10; alyosha-tas `Interactions/ReadMe.txt`). **HALT**: the board stops calling `step()`; each cycle it clocks the devices and checks `IE & IF ≠ 0`; when true it resumes (IME and CPSR.I decide only whether the IRQ is then taken). `hw-test/haltcnt` pins the cost of the HALTCNT write and the wake-up (NBA 5/6, mGBA 2/6). A CPU that the wake-up reaches while a DMA has the bus goes on as the DMA's last write ends (quirk 10). ## Timers | Rule | Value | Source / judge | | --- | --- | --- | | A write to TMxCNT_L (reload) takes effect | 1 cycle after the write | NBA `TM_write_reload`; `hw-test/timer/reload` | | A write to TMxCNT_H takes effect | 1 cycle after the write; a 0→1 start loads the counter and counts from the next prescaler edge | NBA `TM_write_control`; `hw-test/timer/start-stop` | | Prescaler | a free-running divider, phase observable from reset | alyosha-tas `timer/timer.gba` | | Tick before reload | the counter ticks once before reloading when started at FFFF | alyosha-tas `timer/readme.txt`; `hw-test/timer/tick-before-reload` | | Overflow IRQ | raised the cycle the counter wraps; disabling the timer that same cycle still raises it | alyosha-tas `irq/readme.txt` | The mGBA suite's "Timer count-up" group (936 cases) and "Timer IRQ" (90) measure these; NBA 1.8.3 passes all of both **with the real BIOS** and loses 89 count-up cases with the free BIOS (C3 in [undocumented-behavior.md](undocumented-behavior.md)). ## The PPU's line One line is 1,232 cycles (308 dots × 4). NBA's event times from the start of a line (the cycle VCOUNT changes): | Cycle | Event | | --- | --- | | 0 | VCOUNT += 1 (227 → 0); at line 160 VBlank flag set and VBlank DMA requested; at 227 VBlank flag cleared | | 1 | VCount-match flag updated; VBlank IRQ (line 160) | | 2 | VCount-match IRQ | | 40 | DISPCNT latched (a three-deep latch: a write takes effect on BG enables two lines later; `hw-test/ppu/dispcnt-latch`) | | 1,007 | HBlank flag set; HBlank DMA (lines 0–159) | | 1,008 | HBlank IRQ | | 1,232 | next line | mGBA puts the HBlank flag at 1,008 (`VIDEO_HDRAW_LENGTH`). **Both fail the mGBA suite's six "H-blank bit start" cases**, so neither number is settled (C1). GBATEK says 1,006 ("the H-Blank flag is "0" for a total of 1006 cycles"). The judge is the suite case plus `hw-test/ppu/status-irq-dma`. Within the visible part the PPU fetches VRAM, palette and OAM on fixed cycles per mode, and a CPU access that collides is delayed (`hw-test/ppu/ram-access-timing`, alyosha-tas `ppu/Sprite_*`; NBA fails 3 of those). The OBJ engine's per-line budget is 1,210 cycles (954 when DISPCNT bit 5, HBlank interval free, is set) (GBATEK "OBJ Attributes"; NBA's sprite fetch runs from cycle 266 of the previous line in its own event loop). A dot-exact model of these fetches is milestone work: the archived NBA `ppu/mode*` and `exact-timing` ROMs describe them, with hardware photographs. ## Sound | Rule | Value | Source and judge | | --- | --- | --- | | The Game Boy channels' clock | 4,194,304 Hz: one of the `gb-apu-python` core's T-cycles is four system cycles; the pulse and noise channels count 2 MHz ticks (8 cycles), the wave channel a digit every 8 x (2048 - n) cycles | GBATEK's rates; `tests/test_apu.py` | | The frame sequencer | a step every 32,768 cycles (512 Hz) from power-on, on the system clock's bit 14 falling; lengths on every other step, the sweep on every fourth, envelopes on every eighth | NanoBoyAdvance `s_cycles_per_step`; no hardware judge (C26) | | A FIFO sample | taken on the selected timer's overflow cycle | NanoBoyAdvance; GBATEK | | A FIFO's DMA request | when three words or fewer remain at that overflow; runnable **three** cycles later | alyosha-tas `fifo_dma/fifo_2`, `fifo_3`, `fifo_4` (they fail at two) | | A FIFO request while the channel's own refill is moving its words (one that finds it still waiting adds nothing) | the refill reads a fifth word (written nowhere); the next request moves three | alyosha-tas `fifo_dma/fifo.gba`'s five hardware numbers (C28: a fit) | | A DMA's IRQ | raised one cycle after the channel's last write | alyosha-tas `fifo_dma/fifo_6`; GBAHawk | | The mixer | a sample every 512 cycles from power-on (32,768 Hz); SOUNDBIAS bits 14-15 halve the interval up to three times | NanoBoyAdvance `StepMixer`; GBATEK | The channels are caught up only when something looks at them (a register access, a mixer sample), in the core's own 4-T steps with the sequencer's edges in order between them.