# SPDX-License-Identifier: MIT """The four DMA channels: registers, internal latches, priority, start conditions, timing. Registers and modes: GBATEK §GBA DMA Transfers (DOC); docs/timing.md "DMA"; docs/memory-map.md "DMA and the bus latch". Open questions: U-DMA-1 (start delay), U-DMA-2 (switch cost). How a transfer runs (each rule tagged): - The internal source, destination and count load when enable goes 0 to 1; a repeat reloads the count and, in increment/reload mode, the destination (DOC). - Priority 0 > 1 > 2 > 3; a channel that becomes due while a lower one runs takes the bus between two units, and the lower one resumes after it (DOC). - "For n data units, the DMA transfer time is: 2N+2(n-1)S+xI ... Internal time for DMA processing is 2I (normally), or 4I (if both source and destination are in gamepak memory area)" (GBATEK "Transfer Rate/Timing"; DOC). Where the internal cycles fall (before the first read, after the last write) is not documented: START_IDLE and END_IDLE are FITTED (docs/timing.md "DMA"). - Each channel keeps its own 32-bit latch: a 16-bit read fills both halves, a 16-bit write takes the half the destination's alignment selects (hw-test dma/latch; TEST ROM). A read from below 02000000 does not update it (same test), and every DMA read copies the latch to the CPU's open-bus latch (alyosha-tas Bus/ReadMe.txt; TEST ROM). """ from __future__ import annotations from gba_python.irq import DMA0 from gba_python.scheduler import NEVER IMMEDIATE, VBLANK, HBLANK, SPECIAL = 0, 1, 2, 3 # Cycles from the enable write (immediate) or the start condition to the DMA taking the bus # (U-DMA-1). GBATEK: "wait 2 clock cycles before accessing any DMA related registers" (DOC). # FITTED to hw-test dma/start-delay and dma/force-nseq-access (docs/timing.md "DMA"). START_DELAY = 3 TRIGGER_DELAY = 2 # A sound FIFO's request: the DMA takes the bus before a CPU access starting at A only when # the overflow cycle O satisfies O + 5 <= A. TEST ROM: alyosha-tas fifo_dma/fifo_2 (hardware- # captured), whose eight cases move the overflow one cycle at a time past an I/O read: the # console's DMA lands before the read for O = A - 11 .. A - 5 and after it for O = A - 4 # (docs/validation.md "The FIFO DMA timing study"). 3, 4, 6 and 7 pass 2, 3, 5 and 3 of the nine # fifo_dma ROMs (5 passes 6). Provisional (U-DMA-4). FIFO_DELAY = 5 # The 2I (4I gamepak to gamepak) internal cycles, split before the first read and after the # last write. FITTED (docs/timing.md "DMA"). START_IDLE = 1 END_IDLE = 1 # A channel that takes the bus from a lower one between two of its units spends neither # internal cycle (0); 1 spends both as for a start from the CPU. TEST ROM: the AGS aging # cartridges' DMA test 9 (an immediate DMA reading TM0CNT, preempted by an H-blank DMA of a # higher channel, for the pairs 0/1, 1/2, 2/3) passes with 0 and fails with 1, or with only # one of the two skipped (docs/validation.md "Rung 6"). Provisional (U-DMA-2). NESTED_IDLE = 0 SOURCE_MASK = (0x07FFFFFF, 0x0FFFFFFF, 0x0FFFFFFF, 0x0FFFFFFF) # DOC DEST_MASK = (0x07FFFFFF, 0x07FFFFFF, 0x07FFFFFF, 0x0FFFFFFF) # DOC COUNT_MASK = (0x3FFF, 0x3FFF, 0x3FFF, 0xFFFF) # 0 means the maximum (DOC) CONTROL_MASK = (0xF7E0, 0xF7E0, 0xF7E0, 0xFFE0) # readable bits: mGBA suite io-read.c class Channel: __slots__ = ( "control", "count", "count_reg", "dad", "dest", "due", "fifo", "first_unit", "index", "latch", "pending", "running", "sad", "source", ) def __init__(self, index: int) -> None: self.index = index self.sad = 0 self.dad = 0 self.count_reg = 0 self.control = 0 self.source = 0 self.dest = 0 self.count = 0 self.latch = 0 self.pending = False # its start condition has happened self.due = NEVER # when it takes the bus self.running = False # started and not finished (it may be paused) self.first_unit = True self.fifo = False # sound FIFO mode for this run @property def timing(self) -> int: return (self.control >> 12) & 3 class DMA: def __init__(self, board) -> None: self.board = board self.channels = [Channel(i) for i in range(4)] self.active = None # the channel whose units are on the bus # ---------------------------------------------------------------------------------- # Start conditions def update_due(self) -> None: due = NEVER for channel in self.channels: if channel.pending and channel.due < due: due = channel.due self.board.dma_due = due def trigger(self, timing: int, time: int) -> None: """A start condition: V-blank, H-blank, or the special one (video capture).""" for channel in self.channels: if channel.control & 0x8000 and channel.timing == timing and not channel.pending: if timing == SPECIAL and channel.index in (1, 2): continue # sound FIFO channels answer fifo_request if timing == SPECIAL and channel.index == 0: continue # "prohibited" (DOC) self.make_pending(channel, time + TRIGGER_DELAY) def fifo_request(self, fifo_address: int, time: int) -> None: """A sound FIFO asks for data: the DMA1/2 in special timing whose destination is that FIFO (HYPOTHESIS: by destination address, U-SND-7).""" for channel in self.channels[1:3]: if ( channel.control & 0x8000 and channel.timing == SPECIAL and (channel.dad & ~3) == fifo_address and not channel.pending ): channel.fifo = True self.make_pending(channel, time + FIFO_DELAY) def end_capture(self) -> None: """VCOUNT = 162 ends a video capture: DMA3's enable bit clears (GBATEK §GBA DMA Transfers: "it gets stopped when VCOUNT=162", and its "Capture Enable=AutoCleared ???"; DOC with GBATEK's own doubt). TEST ROM: the AGS aging cartridges' DMA test 7 (a capture of VCOUNT into EWRAM over one frame, then the enable cleared by the program at the next frame's line 162) passes only when the capture stops after one frame; with the enable kept it captures a second frame and fails (docs/validation.md "Rung 6"). Provisional: the cartridge's verdict says the second frame is not captured, not that bit 15 is the mechanism (a channel kept enabled but never restarted would pass too).""" channel = self.channels[3] if channel.control & 0x8000 and channel.timing == SPECIAL: channel.control &= ~0x8000 channel.pending = False channel.running = False channel.due = NEVER self.update_due() def make_pending(self, channel: Channel, due: int) -> None: channel.pending = True channel.due = due if not channel.running: channel.first_unit = True self.update_due() # ---------------------------------------------------------------------------------- # Running def run(self) -> None: """Run due channels, highest priority first, until none is due (bus order of record 2). The CPU's next access is then non-sequential (hw-test dma/force-nseq-access).""" bus = self.board.bus while True: channel = None for candidate in self.channels: if candidate.pending and candidate.due <= bus.now: channel = candidate break if channel is None: break previous = self.active self.active = channel self.transfer(channel) self.active = previous bus.cpu_seq_broken = True self.update_due() def higher_due(self, channel: Channel) -> bool: now = self.board.bus.now for other in self.channels[: channel.index]: if other.pending and other.due <= now: return True return False def transfer(self, channel: Channel, nested: bool = False) -> None: """Run ``channel`` until its count is done. ``nested``: it took the bus from a lower channel between two units (``run_higher``), so the bus never went back to the CPU and the internal cycles are not spent (NESTED_IDLE).""" bus = self.board.bus index = channel.index if not channel.running: channel.running = True channel.first_unit = True if not nested or NESTED_IDLE: bus.dma_idle(START_IDLE) bus.dma_cart_fresh = True fifo = channel.fifo word = fifo or bool(channel.control & 0x0400) width = 32 if word else 16 size = 4 if word else 2 dest_control = 2 if fifo else (channel.control >> 5) & 3 source_control = (channel.control >> 7) & 3 dest_step = (size, -size, 0, size)[dest_control] source_step = (size, -size, 0, 0)[source_control] # 3 is "prohibited": HYPOTHESIS fixed while channel.count > 0: if self.higher_due(channel): # Paused between units; it resumes non-sequentially (HYPOTHESIS, U-DMA-2). channel.first_unit = True self.run_higher(channel) bus.dma_cart_fresh = True seq = not channel.first_unit channel.first_unit = False source = channel.source & SOURCE_MASK[index] dest = channel.dest & DEST_MASK[index] source &= ~(size - 1) dest &= ~(size - 1) self.unit(channel, source, dest, width, seq) channel.source = (channel.source + source_step) & 0xFFFFFFFF channel.dest = (channel.dest + dest_step) & 0xFFFFFFFF channel.count -= 1 if not nested or NESTED_IDLE: bus.dma_idle(END_IDLE) self.finish(channel) def run_higher(self, channel: Channel) -> None: bus = self.board.bus while self.higher_due(channel): for other in self.channels[: channel.index]: if other.pending and other.due <= bus.now: previous = self.active self.active = other self.transfer(other, nested=True) self.active = previous break def unit(self, channel: Channel, source: int, dest: int, width: int, seq: bool) -> None: bus = self.board.bus if source >= 0x02000000 and source < 0x10000000: value = bus.dma_read(source, width, seq) if width == 16: value &= 0xFFFF channel.latch = value | value << 16 else: channel.latch = value half = channel.latch else: # Below 02000000 (the BIOS, unused): not read; the old latch is written (hw-test # dma/latch; TEST ROM). The access still takes a cycle (HYPOTHESIS: priced as an # unused-region access). bus.dma_idle(1) half = channel.latch # Every DMA read copies its bus to the CPU's open-bus latch; a 16-bit one copies the # half it read to both halves (alyosha-tas Bus/ReadMe.txt; TEST ROM). if width == 16: piece = (channel.latch >> ((source & 2) << 3)) & 0xFFFF bus.open_bus = piece | piece << 16 value = (half >> ((dest & 2) << 3)) & 0xFFFF else: bus.open_bus = channel.latch value = half bus.dma_write(dest, width, value, seq) def finish(self, channel: Channel) -> None: board = self.board bus = board.bus channel.running = False channel.pending = False channel.due = NEVER fifo = channel.fifo channel.fifo = False if channel.control & 0x4000: board.irq.request(DMA0 << channel.index, bus.now) repeat = channel.control & 0x0200 and channel.timing != IMMEDIATE if repeat: channel.count = 4 if fifo else self.count_of(channel) if (channel.control >> 5) & 3 == 3 and not fifo: channel.dest = channel.dad else: channel.control &= ~0x8000 self.update_due() def count_of(self, channel: Channel) -> int: count = channel.count_reg & COUNT_MASK[channel.index] return count or COUNT_MASK[channel.index] + 1 # ---------------------------------------------------------------------------------- # Registers def read16(self, offset: int) -> int | None: index, field = divmod(offset - 0xB0, 12) channel = self.channels[index] if field == 10: return channel.control & CONTROL_MASK[index] return None # SAD, DAD and CNT_L are write-only (DOC) def write16(self, offset: int, value: int, mask: int, time: int) -> None: index, field = divmod(offset - 0xB0, 12) channel = self.channels[index] if field == 0: channel.sad = (channel.sad & ~mask) | (value & mask) elif field == 2: channel.sad = (channel.sad & ~(mask << 16)) | ((value & mask) << 16) elif field == 4: channel.dad = (channel.dad & ~mask) | (value & mask) elif field == 6: channel.dad = (channel.dad & ~(mask << 16)) | ((value & mask) << 16) elif field == 8: channel.count_reg = (channel.count_reg & ~mask) | (value & mask) else: old = channel.control new = (old & ~mask) | (value & mask) if index != 3: new &= ~0x0800 # Game Pak DRQ is DMA3's only (DOC) channel.control = new if not old & 0x8000 and new & 0x8000: self.enable(channel, time) elif old & 0x8000 and not new & 0x8000: channel.pending = False channel.running = False channel.due = NEVER self.update_due() def enable(self, channel: Channel, time: int) -> None: """Enable 0 to 1: load the internal registers (GBATEK; DOC).""" index = channel.index channel.source = channel.sad & SOURCE_MASK[index] channel.dest = channel.dad & DEST_MASK[index] channel.count = self.count_of(channel) channel.running = False channel.fifo = False eeprom = self.board.bus.eeprom if ( index == 3 and eeprom is not None and ( 0x0D000000 <= channel.dest < 0x0E000000 or 0x0D000000 <= channel.source < 0x0E000000 ) ): eeprom.fix_size_from_dma(channel.count) if channel.timing == IMMEDIATE: self.make_pending(channel, time + START_DELAY) elif channel.timing == SPECIAL and index in (1, 2): channel.count = 4