"""The four DMA channels. GBATEK "GBA DMA Transfers"; the machinery is NanoBoyAdvance's ``hw/dma/dma.cpp``, the detector that passes the most hardware DMA tests measured here (docs/validation.md): - A channel enabled for immediate start, or requested by its start condition, joins the runnable set **two cycles later** (``hw-test/dma/start-delay``). - The DMA takes the bus at the CPU's next bus access, or at once if the CPU is in an internal cycle; the CPU's internal cycles overlap a running DMA (the board's ``idle``). - One run costs a cycle before the first unit and one after the last; each unit is a read and a write through the board's bus with the DMA flag, so wait states and the Game Pak's N/S rules apply. The first Game Pak access of a run is N. - A higher-priority channel that becomes runnable interrupts a lower one between units. - Reads below ``2000000`` (the BIOS) do not happen: the channel writes its own latch again. The latch of the last value any channel read is what the CPU sees as open bus right after a DMA (``hw-test/dma/latch``). - Sound FIFO channels (1 and 2, special timing) move 4 words to a fixed destination. A FIFO's request reaches the runnable set **three cycles** after the timer overflow, one more than the other start conditions: alyosha-tas ``fifo_dma/fifo_2``, ``fifo_3`` and ``fifo_4`` sweep the overflow against the instruction stream and pass only at three (GBAHawk, their author's emulator, counts three; NanoBoyAdvance two). A request that arrives while the channel is still running makes it read a fifth word, written nowhere, and the next request moves three (``fifo.gba``'s hardware numbers; docs/undocumented-behavior.md C28). - A channel's IRQ is raised a cycle after its last write (``fifo_6``). """ from __future__ import annotations from typing import TYPE_CHECKING from gba_python.irq import DMA0, IRQ from gba_python.scheduler import Event, Scheduler if TYPE_CHECKING: from gba_python.board import GBA DMA_ACCESS = 4 # the board's own access bit for a DMA cycle (the core leaves bit 2 free) SEQ = 1 INCREMENT, DECREMENT, FIXED, RELOAD = 0, 1, 2, 3 IMMEDIATE, VBLANK, HBLANK, SPECIAL = 0, 1, 2, 3 SRC_MASK = (0x07FFFFFF, 0x0FFFFFFF, 0x0FFFFFFF, 0x0FFFFFFF) DST_MASK = (0x07FFFFFF, 0x07FFFFFF, 0x07FFFFFF, 0x0FFFFFFF) LEN_MASK = (0x3FFF, 0x3FFF, 0x3FFF, 0xFFFF) STEP = ((2, -2, 0, 2), (4, -4, 0, 4)) # [word][control]: RELOAD increments like INCREMENT FIFO_DELAY = 3 # cycles from a FIFO's timer overflow to its DMA being runnable class Channel: __slots__ = ( "cnt_h", "dst", "dst_control", "enable", "event", "fifo", "fifo_again", "gamepak", "id", "interrupt", "latch_bus", "latch_dst", "latch_length", "latch_src", "length", "moving", "repeat", "src", "src_control", "timing", "word", ) def __init__(self, index: int) -> None: self.id = index self.src = self.dst = self.length = 0 self.cnt_h = 0 self.dst_control = self.src_control = INCREMENT self.timing = IMMEDIATE self.word = False self.repeat = self.interrupt = self.enable = self.gamepak = False self.latch_src = self.latch_dst = self.latch_length = 0 self.latch_bus = 0 # the last (half)word this channel read self.fifo_again = False # a FIFO request arrived while the channel was running self.moving = False # the channel has moved a unit of this transfer self.fifo = False self.event: Event | None = None class DMA: def __init__(self, scheduler: Scheduler, irq: IRQ, board: GBA) -> None: self.scheduler = scheduler self.irq = irq self.board = board self.channels = [Channel(index) for index in range(4)] self.runnable = 0 # bit set of channels ready to transfer self.transfers = 0 # times the DMA took the bus (the debugger's ``break dma``) self.hblank_set = self.vblank_set = self.video_set = 0 self.active = -1 self.reenter = False self.latch = 0 # the last value any channel read: the bus after a DMA @property def running(self) -> bool: return self.runnable != 0 # ----- start conditions --------------------------------------------------------------- def _schedule(self, bits: int) -> None: for index in range(4): if bits >> index & 1: self.channels[index].event = self.scheduler.add(2, self._activated, index) def _activated(self, index: int) -> None: self.channels[index].event = None if self.runnable >> index & 1 and self.channels[index].fifo: # A second request for a refill already asked for. One that finds the refill # moving its words is remembered (see _run_channel); one that finds it still # waiting, behind the CPU or a channel above it, adds nothing: no test ROM # covers that case, and Pokemon Mystery Dungeon's 32,768-cycle DMA0 holds both # FIFO channels through a dozen overflows. if self.channels[index].moving: self.channels[index].fifo_again = True return if self.runnable == 0: self.active = index elif index < self.active: self.active = index self.reenter = True self.runnable |= 1 << index def request_hblank(self) -> None: self._schedule(self.hblank_set) def request_vblank(self) -> None: self._schedule(self.vblank_set) def request_video(self) -> None: self._schedule(self.video_set) def request_fifo(self, fifo: int) -> None: channel = self.channels[1 + fifo] if channel.enable and channel.timing == SPECIAL: channel.event = self.scheduler.add(FIFO_DELAY, self._activated, channel.id) def stop_video(self) -> None: channel = self.channels[3] if channel.enable: channel.enable = False channel.cnt_h &= 0x7FFF self._written(channel, True) def has_video(self) -> bool: channel = self.channels[3] return channel.enable and channel.timing == SPECIAL # ----- running ------------------------------------------------------------------------ def _select_next(self) -> None: runnable = self.runnable self.active = (runnable & -runnable).bit_length() - 1 if runnable else -1 def run(self) -> int: """Run every runnable channel to completion; return the cycles it took.""" board = self.board start = self.scheduler.now self.transfers += 1 board.step(1) while self.runnable: self._run_channel() # The closing idle cycle hands the bus back to the CPU. A CPU that a HALT's wake-up # reached during the transfer has no access waiting and goes on as the last write # ends (alyosha-tas Interactions/Halt_DMA_IRQ; quirk 10). if not (board.halted and self.irq.available): board.step(1) return self.scheduler.now - start def _run_channel(self) -> None: board = self.board channel = self.channels[self.active] word = channel.word or channel.fifo dst_step = 0 if channel.fifo else STEP[word][channel.dst_control] src_step = STEP[word][channel.src_control] width = 32 if word else 16 touched_rom = False while channel.latch_length: if self.reenter: self.reenter = False return channel.moving = True src = channel.latch_src dst = channel.latch_dst access_src = access_dst = SEQ | DMA_ACCESS if not touched_rom: if src >= 0x08000000: access_src = DMA_ACCESS touched_rom = True elif dst >= 0x08000000: access_dst = DMA_ACCESS touched_rom = True if src >= 0x02000000: value = board.bus_read(src, width, access_src) channel.latch_bus = value if word else value << 16 | value self.latch = channel.latch_bus else: board.step(1) # the BIOS is not readable: the channel's latch is used if word: board.bus_write(dst, 32, channel.latch_bus, access_dst) else: value = channel.latch_bus >> 16 if dst & 2 else channel.latch_bus & 0xFFFF board.bus_write(dst, 16, value, access_dst) channel.latch_src = (src + src_step) & 0xFFFFFFFF channel.latch_dst = (dst + dst_step) & 0xFFFFFFFF channel.latch_length -= 1 owed = 4 if channel.fifo_again: # A request that reached the channel during its run: it reads one more word, which # goes nowhere, and the next request moves the three that are left (C28). channel.fifo_again = False if channel.latch_src >= 0x02000000: self.latch = channel.latch_bus = board.bus_read( channel.latch_src, 32, SEQ | DMA_ACCESS ) else: board.step(1) channel.latch_src = (channel.latch_src + src_step) & 0xFFFFFFFF owed = 3 self.runnable &= ~(1 << channel.id) channel.moving = False if channel.interrupt: # The request leaves the DMA a cycle after its last write (alyosha-tas fifo_6; # GBAHawk's DMA_IRQ_Delay). self.scheduler.add(1, self.irq.raise_, DMA0 + channel.id) if channel.repeat and channel.timing != IMMEDIATE: if channel.fifo: channel.latch_length = owed else: channel.latch_length = channel.length & LEN_MASK[channel.id] or ( LEN_MASK[channel.id] + 1 ) if channel.dst_control == RELOAD: channel.latch_dst = channel.dst & (~3 if channel.word else ~1) else: self._remove_from_sets(channel) channel.enable = False channel.cnt_h &= 0x7FFF self._select_next() # ----- registers ---------------------------------------------------------------------- def read_cnt_h(self, index: int) -> int: return self.channels[index].cnt_h def write(self, index: int, register: int, value: int, mask: int) -> None: """A write to one of the channel's halfwords: 0/2 SAD, 4/6 DAD, 8 CNT_L, 10 CNT_H.""" channel = self.channels[index] if register < 4: shift = register * 8 merged = (channel.src >> shift & 0xFFFF) & ~mask | value & mask channel.src = (channel.src & ~(0xFFFF << shift) | merged << shift) & SRC_MASK[index] elif register < 8: shift = (register - 4) * 8 merged = (channel.dst >> shift & 0xFFFF) & ~mask | value & mask channel.dst = (channel.dst & ~(0xFFFF << shift) | merged << shift) & DST_MASK[index] elif register == 8: channel.length = channel.length & ~mask | value & mask else: self._write_control(channel, channel.cnt_h & ~mask | value & mask, mask) def _write_control(self, channel: Channel, value: int, mask: int) -> None: was_enabled = channel.enable if mask & 0xFF: channel.dst_control = value >> 5 & 3 channel.src_control = channel.src_control & 2 | value >> 7 & 1 if mask & 0xFF00: channel.src_control = channel.src_control & 1 | (value >> 8 & 1) << 1 channel.word = bool(value & 0x400) channel.timing = value >> 12 & 3 channel.repeat = bool(value & 0x200) channel.gamepak = bool(value & 0x800) and channel.id == 3 channel.interrupt = bool(value & 0x4000) channel.enable = bool(value & 0x8000) channel.cnt_h = value & (0xFFE0 if channel.id == 3 else 0xF7E0) if mask & 0xFF00: self._written(channel, was_enabled) def _written(self, channel: Channel, was_enabled: bool) -> None: self._remove_from_sets(channel) bit = 1 << channel.id if channel.enable: if not was_enabled: # The enable bit's rising edge latches the addresses and the length. channel.latch_src = channel.src channel.latch_dst = channel.dst if channel.timing == SPECIAL and channel.id in (1, 2): channel.fifo = True channel.latch_length = 4 channel.latch_src &= ~3 channel.latch_dst &= ~3 self._add_to_sets(channel) else: channel.fifo = False align = ~3 if channel.word else ~1 channel.latch_src &= align channel.latch_dst &= align channel.latch_length = channel.length & LEN_MASK[channel.id] or ( LEN_MASK[channel.id] + 1 ) if channel.timing == IMMEDIATE: self._schedule(bit) else: self._add_to_sets(channel) if channel.dst >= 0x0D000000: self.board.cartridge.eeprom_size_hint(channel.length) elif channel.event is None: # Still enabled: a write while it runs takes effect from the next unit. self._add_to_sets(channel) if channel.id == self.active: self.reenter = True else: self.runnable &= ~bit if channel.event is not None: # Disabled during its two-cycle start-up: it never runs (NBA; exact hardware # behaviour unknown). self.scheduler.cancel(channel.event) channel.event = None if channel.id == self.active: self.reenter = True self._select_next() def _add_to_sets(self, channel: Channel) -> None: bit = 1 << channel.id if channel.timing == HBLANK: self.hblank_set |= bit elif channel.timing == VBLANK: self.vblank_set |= bit elif channel.timing == SPECIAL and channel.id == 3: self.video_set |= bit def _remove_from_sets(self, channel: Channel) -> None: bit = ~(1 << channel.id) self.hblank_set &= bit self.vblank_set &= bit self.video_set &= bit