# SPDX-License-Identifier: MIT """The console board: the bus, the one timeline, HALT and RDY in the bus callbacks. **One timeline** (docs/timing.md "One timeline"). 6502-python calls :meth:`Board.read_byte` or :meth:`Board.write_byte` once per CPU cycle, in chip order, dummy accesses included. Machine time advances only inside those callbacks: each machine cycle is ANTIC's ``begin()`` (does it take this cycle?), the bus access (ANTIC's or the CPU's), then ANTIC's ``end()``, GTIA's two colour clocks and one POKEY ``tick()``: the access before the tick of the same cycle, and a tick in every cycle, halted and stalled ones included (pokey-python docs/adoption.md). ``step()``'s return value counts CPU cycles only and is never added on top. (A modelling choice: the serial order of record, docs/architecture.md.) **HALT** (docs/sally-halt.md): ANTIC's DMA cycles run at the top of both callbacks, before the CPU's own access, read or write: the clock is held, so the CPU's pending cycle is simply performed later (DOC [AHRM] 4.14 and [FSM] HALT wiring; TEST ROM antic_dmapattern, antic_pmdma). ``note_stall()`` is not called for them; a request raised during a stolen cycle lands in the callback of the CPU cycle that follows, which is how the held clock behaves (U2: HYPOTHESIS from the held clock, consistent with TEST ROM antic_dlitiming, antic_blockednmi, cpu_timing, pokey_irqtiming). **RDY** (WSYNC): only in ``read_byte``. While ANTIC holds RDY low the CPU repeats its read every cycle (the read is issued again each cycle: the bus shows it, DOC [AHRM] 4.9); ``note_stall()`` is called before each repeated cycle and ``dma_stalled`` is set on the read that was stretched. A write cycle ignores RDY, which gives ``INC WSYNC`` its documented behaviour (DOC [AHRM] 4.9; TEST ROM antic_wsync, cpu_timing). **The floating bus** (U5): :attr:`data_bus` is the last byte on the data bus, updated every cycle, DMA included; a refresh cycle leaves it alone (RAM does not drive the bus then, DOC [AHRM] 2.3). Reads of unmapped space and of an undriven cartridge half return it. HYPOTHESIS: [AHRM] 2.3 describes the 400/800's floating bus and nothing states the 5200's; TEST ROM gtia_phantomdma and antic_virtdma pass with it; a probe ROM reading $D000 after known DMA bytes on a console would settle it. **Interrupts**: ANTIC's NMI falls inside the cycle ANTIC says (``nmi_fire``); POKEY's /IRQ after a tick is the level of the next cycle, so the board hands it to the CPU at the start of the next machine cycle (TEST ROM pokey_irqtiming, pokey_timerirq). """ from __future__ import annotations from collections.abc import Callable from pokey_python import C012294, POKEY from sixfiveohtwo import MOS6502 from .antic import ANTIC, NO_DMA, REFRESH from .cartridge.mappings import Cartridge from .gtia import GTIA from .machine import Machine FRAME_WIDTH = 456 # DOC: 228 colour clocks per line ([AHRM] 4.2), two half-clock pixels each FRAME_LINES = 262 # DOC: [AHRM] 4.2 Table 6 class Board: def __init__(self, machine: Machine, bios: bytes, cartridge: Cartridge) -> None: if len(bios) != 2048: raise ValueError("the 5200 BIOS is 2048 bytes") self.machine = machine self.bios = bytes(bios) self.cartridge = cartridge power = machine.power_on self.ram = bytearray([power.ram_fill]) * 0x4000 self.antic = ANTIC(machine.lines, power.line, power.cycle) self.gtia = GTIA(pal=machine.pal_gtia) # pokey-python docs/adoption.md: the C012294 variant (mix() through its fitted # curve); every register 0 at power-on unless seeded (core B1.8, a choice). self.pokey = POKEY(C012294) if power.pokey_seed is not None: self.pokey.power_on(power.pokey_seed) self.cpu = MOS6502(self.read_byte, self.write_byte) self.cycles = 0 # machine cycles since power, halted and stalled ones included self.halted_cycles = 0 self.stalled_cycles = 0 self.data_bus = 0xFF # HYPOTHESIS: power-on bus value unknown (U8); any value would do self.frames = 0 self.frame = bytearray(FRAME_WIDTH * FRAME_LINES) self._irq_line = False self._irq_next = False # Observers of every bus cycle: f(kind, address, value, cycle) with kind # "R"/"W" for the CPU, "D" for ANTIC DMA, "S" for a WSYNC-repeated read. self.bus_observers: list[Callable[[str, int, int, int], None]] = [] self.on_frame: Callable[[Board], None] | None = None self.audio = None # a media.AudioTap, polled once per machine cycle # Seeded faults, to show that a gate can fail (tests and scripts only): # "drop_dummy_read" (a read of the address just read costs no cycle) and # "steal_one_short" (the refresh slot at cycle 57 goes to the CPU). self.faults: set[str] = set() self._last_read = -1 # Named switch for U6 (see _finish); consecutive CPU writes to page 1. self.nmi_lost_on_p_push = True # C12: decode GTIA at $D000-$D0FF as well. Off: DOC [FSM] Figure 2-2A draws # the $D000 block "N/C" and [AHRM] 13.2 puts GTIA at $C000 only. self.gtia_at_d000 = False self.nmis_lost = 0 self._stack_writes = 0 self.cpu.request_reset() # -- the address decoder ------------------------------------------------- # The memory map: DOC [AHRM] 13.2, 13.4 and the [FSM] decoder sheet (RAM # $0000-$3FFF, cartridge $4000-$BFFF, GTIA $C000, ANTIC $D400, POKEY $E800, # BIOS $F800); register mirrors TEST ROM antic_addrmirror, gtia_addrmirror, # pokey_addrmirror. def peek(self, address: int) -> int: """What a read of ``address`` would return, with no side effects (debugger).""" if address < 0x4000: return self.ram[address] if address < 0xC000: value = self.cartridge.window[address - 0x4000] return self.data_bus if value < 0 else value if address >= 0xF800 or (address >= 0xF000 and self.machine.f000_mirror): return self.bios[address & 0x7FF] return self.data_bus def _read(self, address: int) -> int: if address < 0x4000: value = self.ram[address] elif address < 0xC000: value = self.cartridge.read(address) if value is None: value = self.data_bus elif address < 0xD000: value = self.gtia.read(address) elif address >= 0xF800: value = self.bios[address & 0x7FF] elif 0xE800 <= address < 0xF000: value = self.pokey.read(address & 0x0F) elif 0xD400 <= address < 0xD500: value = self.antic.read(address) elif address >= 0xF000 and self.machine.f000_mirror: value = self.bios[address & 0x7FF] elif self.gtia_at_d000 and address < 0xD100: value = self.gtia.read(address) # C12 switch, off by default else: value = self.data_bus # U5: the floating bus self.data_bus = value return value def _write(self, address: int, value: int) -> None: self.data_bus = value if address < 0x4000: self.ram[address] = value elif address < 0xC000: self.cartridge.access(address) elif address < 0xD000: self.gtia.write(address, value) elif 0xE800 <= address < 0xF000: self.pokey.write(address & 0x0F, value) elif 0xD400 <= address < 0xD500: self.antic.write(address, value) elif self.gtia_at_d000 and 0xD000 <= address < 0xD100: self.gtia.write(address, value) # C12 switch, off by default # -- one machine cycle ---------------------------------------------------- def _finish(self, value: int) -> None: """The rest of a machine cycle once the bus holds ``value``.""" antic = self.antic antic.end(value) self.gtia.cycle(antic.an_a, antic.an_b, antic.halt, value) self._finish_rest() def _finish_rest(self) -> None: antic = self.antic gtia = self.gtia pokey = self.pokey pokey.tick() if antic.nmi_fire: if self.nmi_lost_on_p_push and self._stack_writes == 3: # U6: ANTIC's NMI falling in the cycle an interrupt sequence # pushes P is lost (DOC [AHRM] 4.8 "Missed NMIs"; TEST ROM # antic_blockednmi). The pulse is too short for the 6502 to # see it once the sequence has passed its hijack point (DIE: # [IJOR] sheet 2, a two-cycle pulse). self.nmis_lost += 1 else: self.cpu.request_non_maskable_interrupt() self._irq_next = pokey.irq self.cycles += 1 if self.audio is not None: self.audio.poll() if gtia.line_done: gtia.line_done = False row = antic.vcount if antic.hcount < 100: row -= 1 # the blank edge came at the very end of the previous line (frame # buffer bookkeeping, not hardware behaviour) if 0 <= row < FRAME_LINES: start = row * FRAME_WIDTH self.frame[start : start + FRAME_WIDTH] = gtia.line if antic.hcount == 0 and antic.vcount == 0: self.frames += 1 if self.on_frame is not None: self.on_frame(self) def _sync_irq(self) -> None: level = self._irq_next if level != self._irq_line: self._irq_line = level if level: self.cpu.request_maskable_interrupt() else: self.cpu.clear_maskable_interrupt() def _dma_cycle(self, address: int) -> None: # A refresh cycle: nothing drives the bus (DOC [AHRM] 2.3, 4.14). value = self.data_bus if address == REFRESH else self._read(address) self.halted_cycles += 1 if self.bus_observers: for observer in self.bus_observers: observer("D", address, value, self.cycles) self._finish(value) def read_byte(self, address: int) -> int: antic = self.antic if self.faults and "drop_dummy_read" in self.faults and address == self._last_read: self._last_read = -1 return self._read(address) self._last_read = address stalled = False while True: if self._irq_next != self._irq_line: self._sync_irq() dma = antic.begin() if dma != NO_DMA: if self.faults and "steal_one_short" in self.faults and antic.hcount == 57: pass # the seeded fault: this stolen cycle is not taken else: self._dma_cycle(dma) continue if antic.wsync_at >= 0 and self.cycles >= antic.wsync_at + 2: # RDY low: the read is repeated this cycle and the next one tries again. # RDY falls two cycles after the WSYNC write: TEST ROM antic_wsync, # cpu_timing (DOC [AHRM] 4.9 gives the restart at cycle 105). self.cpu.note_stall() value = self._read(address) self.stalled_cycles += 1 if self.bus_observers: for observer in self.bus_observers: observer("S", address, value, self.cycles) self._finish(value) stalled = True continue break self._stack_writes = 0 self.cpu.dma_stalled = stalled value = self._read(address) if self.bus_observers: for observer in self.bus_observers: observer("R", address, value, self.cycles) self._finish(value) return value def write_byte(self, address: int, value: int) -> None: antic = self.antic while True: if self._irq_next != self._irq_line: self._sync_irq() dma = antic.begin() if dma == NO_DMA: break self._dma_cycle(dma) self._write(address, value) self._stack_writes = self._stack_writes + 1 if address >> 8 == 1 else 0 if self.bus_observers: for observer in self.bus_observers: observer("W", address, value, self.cycles) self._finish(value) # -- running ---------------------------------------------------------------- def capture_state(self): """The CPU's state (so a ``sixfiveohtwo.DebugSession`` can drive the board).""" return self.cpu.capture_state() def step(self) -> int: """One CPU step (instruction, interrupt entry or reset); machine cycles it took.""" before = self.cycles self.cpu.step() return self.cycles - before def run_frame(self) -> None: """Run until the next frame boundary (ANTIC's line 0, cycle 0).""" target = self.frames + 1 step = self.cpu.step while self.frames < target: step() def run_cycles(self, cycles: int) -> None: target = self.cycles + cycles step = self.cpu.step while self.cycles < target: step() def reset(self) -> None: """The console's Reset: the 5200 resets the CPU (and ANTIC's cleared registers). HYPOTHESIS for which chips the Reset line reaches beyond the CPU: the [FSM] reset circuit sheet would settle it (ANTIC per [IJOR]'s reset input). """ self.antic.reset() self.cpu.request_reset()