// 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 //! `Board.read_byte` or `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): `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). //! //! A transcription of a5200-python's `board.py` (at cf82d44): same names (Python's leading //! underscores kept), same order, same comments. Rust-forced differences: //! //! - **The board is the CPU's bus.** In Python the board owns `self.cpu = //! MOS6502(self.read_byte, self.write_byte)`; in Rust the CPU owns its bus, so //! [`Board::new`] returns the CPU holding the board (`Cpu = Mos6502`, the board at //! `cpu.bus`), with the reset requested as Python's constructor does. The board's //! "running" methods (`step`, `run_frame`, `run_cycles`, `reset`, `capture_state`) are the //! [`Running`] trait on `Cpu`; `step` is `board_step` there (the CPU has its own `step`). //! - The CPU's interrupt inputs, `note_stall()` and `dma_stalled` are reached through the //! `&mut Frame` 6502-rust hands every bus callback, so `_finish`, `_finish_rest`, //! `_sync_irq` and `_dma_cycle` take it. //! - `bus_observers` are boxed closures `f(kind, address, value, cycle, antic)`: a Rust //! closure cannot hold the board that calls it, so it is handed ANTIC (what Python's //! observers read through their board: `debug.BeamWatch`, `trace_jsonl`). The kind is a //! `char`; a refresh cycle's address is ANTIC's `REFRESH` (-2), as in Python. //! - `on_frame` is called with `&Board`; `audio` is an `Option` polled with the //! chips it reads (`AudioTap::poll(&pokey, consol)`). //! - `_read` and `_write` are `pub` (Python's underscore is a convention its tests cross). //! - `faults` is a set of names (`HashSet<&str>`), as in Python. `ram` and `frame` are //! `Vec`; `cycles`, `halted_cycles`, `stalled_cycles`, `frames` and `nmis_lost` are `u64`. use std::collections::HashSet; use pokey::{C012294, POKEY}; use sixfiveohtwo::{Bus, CpuState, Frame, Mos6502}; use crate::antic::{ANTIC, NO_DMA, REFRESH}; use crate::cartridge::mappings::Cartridge; use crate::gtia::GTIA; use crate::machine::Machine; use crate::media::AudioTap; pub const FRAME_WIDTH: usize = 456; // DOC: 228 colour clocks per line ([AHRM] 4.2), two half-clock pixels each pub const FRAME_LINES: usize = 262; // DOC: [AHRM] 4.2 Table 6 /// An observer of every bus cycle: f(kind, address, value, cycle, antic) with kind /// 'R'/'W' for the CPU, 'D' for ANTIC DMA, 'S' for a WSYNC-repeated read. pub type Observer = Box; /// Called with the board at each frame boundary. pub type OnFrame = Box; /// The CPU with the board as its bus (Rust-forced, see the module header). pub type Cpu = Mos6502; pub struct Board { pub machine: Machine, pub bios: Vec, pub cartridge: Cartridge, pub ram: Vec, pub antic: ANTIC, pub gtia: GTIA, pub pokey: POKEY, pub cycles: u64, // machine cycles since power, halted and stalled ones included pub halted_cycles: u64, pub stalled_cycles: u64, pub data_bus: u8, // HYPOTHESIS: power-on bus value unknown (U8); any value would do pub frames: u64, pub frame: Vec, pub _irq_line: bool, pub _irq_next: bool, // 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. pub bus_observers: Vec, pub on_frame: Option, pub audio: Option, // 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). pub faults: HashSet<&'static str>, pub _last_read: i32, // Named switch for U6 (see _finish); consecutive CPU writes to page 1. pub nmi_lost_on_p_push: bool, // 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. pub gtia_at_d000: bool, pub nmis_lost: u64, pub _stack_writes: u32, } impl Board { /// A powered board inside its CPU, the reset requested (Python's `Board(machine, bios, /// cartridge)`). pub fn new(machine: Machine, bios: &[u8], cartridge: Cartridge) -> Result { if bios.len() != 2048 { return Err("the 5200 BIOS is 2048 bytes".to_string()); } let power = machine.power_on; // 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). let mut pokey = POKEY::new((*C012294).clone(), false); if power.pokey_seed.is_some() { pokey.power_on(power.pokey_seed); } let board = Board { machine, bios: bios.to_vec(), cartridge, ram: vec![power.ram_fill; 0x4000], antic: ANTIC::new(machine.lines as i32, power.line as i32, power.cycle as i32), gtia: GTIA::new(machine.pal_gtia, false), pokey, cycles: 0, halted_cycles: 0, stalled_cycles: 0, data_bus: 0xFF, frames: 0, frame: vec![0; FRAME_WIDTH * FRAME_LINES], _irq_line: false, _irq_next: false, bus_observers: Vec::new(), on_frame: None, audio: None, faults: HashSet::new(), _last_read: -1, nmi_lost_on_p_push: true, gtia_at_d000: false, nmis_lost: 0, _stack_writes: 0, }; let mut cpu = Mos6502::new(board); cpu.frame.request_reset(); Ok(cpu) } // -- 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. /// What a read of `address` would return, with no side effects (debugger). pub fn peek(&self, address: u16) -> u8 { let address = address as usize; if address < 0x4000 { return self.ram[address]; } if address < 0xC000 { let value = self.cartridge.window[address - 0x4000]; return if value < 0 { self.data_bus } else { value as u8 }; } if address >= 0xF800 || (address >= 0xF000 && self.machine.f000_mirror) { return self.bios[address & 0x7FF]; } self.data_bus } pub fn _read(&mut self, address: u16) -> u8 { let a = address as usize; let value; if a < 0x4000 { value = self.ram[a]; } else if a < 0xC000 { value = match self.cartridge.read(address) { Some(v) => v, None => self.data_bus, }; } else if a < 0xD000 { value = self.gtia.read(a as i32); } else if a >= 0xF800 { value = self.bios[a & 0x7FF]; } else if (0xE800..0xF000).contains(&a) { value = self.pokey.read((a & 0x0F) as u8); } else if (0xD400..0xD500).contains(&a) { value = self.antic.read(a as i32); } else if a >= 0xF000 && self.machine.f000_mirror { value = self.bios[a & 0x7FF]; } else if self.gtia_at_d000 && a < 0xD100 { value = self.gtia.read(a as i32); // C12 switch, off by default } else { value = self.data_bus; // U5: the floating bus } self.data_bus = value; value } pub fn _write(&mut self, address: u16, value: u8) { let a = address as usize; self.data_bus = value; if a < 0x4000 { self.ram[a] = value; } else if a < 0xC000 { self.cartridge.access(address); } else if a < 0xD000 { self.gtia.write(a as i32, value); } else if (0xE800..0xF000).contains(&a) { self.pokey.write((a & 0x0F) as u8, value); } else if (0xD400..0xD500).contains(&a) { self.antic.write(a as i32, value); } else if self.gtia_at_d000 && (0xD000..0xD100).contains(&a) { self.gtia.write(a as i32, value); // C12 switch, off by default } } // -- one machine cycle ---------------------------------------------------- /// The rest of a machine cycle once the bus holds `value`. fn _finish(&mut self, value: u8, frame: &mut Frame) { let antic = &mut self.antic; antic.end(value); self.gtia.cycle(antic.an_a, antic.an_b, antic.halt, value); self._finish_rest(frame); } fn _finish_rest(&mut self, frame: &mut Frame) { self.pokey.tick(); if self.antic.nmi_fire { if self.nmi_lost_on_p_push && 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 { frame.request_non_maskable_interrupt(); } } self._irq_next = self.pokey.irq; self.cycles += 1; if let Some(audio) = self.audio.as_mut() { audio.poll(&self.pokey, self.gtia.consol_out.get()); } if self.gtia.line_done { self.gtia.line_done = false; let mut row = self.antic.vcount; if self.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 && (row as usize) < FRAME_LINES { let start = row as usize * FRAME_WIDTH; self.frame[start..start + FRAME_WIDTH].copy_from_slice(&self.gtia.line); } } if self.antic.hcount == 0 && self.antic.vcount == 0 { self.frames += 1; if let Some(mut on_frame) = self.on_frame.take() { on_frame(self); self.on_frame = Some(on_frame); } } } fn _sync_irq(&mut self, frame: &mut Frame) { let level = self._irq_next; if level != self._irq_line { self._irq_line = level; if level { frame.request_maskable_interrupt(); } else { frame.clear_maskable_interrupt(); } } } fn _observe(&mut self, kind: char, address: i32, value: u8) { let cycles = self.cycles; let antic = &self.antic; for observer in self.bus_observers.iter_mut() { observer(kind, address, value, cycles, antic); } } fn _dma_cycle(&mut self, address: i32, frame: &mut Frame) { // A refresh cycle: nothing drives the bus (DOC [AHRM] 2.3, 4.14). let value = if address == REFRESH { self.data_bus } else { self._read(address as u16) }; self.halted_cycles += 1; if !self.bus_observers.is_empty() { self._observe('D', address, value); } self._finish(value, frame); } pub fn read_byte(&mut self, address: u16, frame: &mut Frame) -> u8 { if !self.faults.is_empty() && self.faults.contains("drop_dummy_read") && address as i32 == self._last_read { self._last_read = -1; return self._read(address); } self._last_read = address as i32; let mut stalled = false; loop { if self._irq_next != self._irq_line { self._sync_irq(frame); } let dma = self.antic.begin(); if dma != NO_DMA { if !self.faults.is_empty() && self.faults.contains("steal_one_short") && self.antic.hcount == 57 { // the seeded fault: this stolen cycle is not taken } else { self._dma_cycle(dma, frame); continue; } } if self.antic.wsync_at >= 0 && self.cycles as i64 >= self.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). frame.note_stall(); let value = self._read(address); self.stalled_cycles += 1; if !self.bus_observers.is_empty() { self._observe('S', address as i32, value); } self._finish(value, frame); stalled = true; continue; } break; } self._stack_writes = 0; frame.dma_stalled = stalled; let value = self._read(address); if !self.bus_observers.is_empty() { self._observe('R', address as i32, value); } self._finish(value, frame); value } pub fn write_byte(&mut self, address: u16, value: u8, frame: &mut Frame) { loop { if self._irq_next != self._irq_line { self._sync_irq(frame); } let dma = self.antic.begin(); if dma == NO_DMA { break; } self._dma_cycle(dma, frame); } self._write(address, value); self._stack_writes = if address >> 8 == 1 { self._stack_writes + 1 } else { 0 }; if !self.bus_observers.is_empty() { self._observe('W', address as i32, value); } self._finish(value, frame); } } impl Bus for Board { fn read(&mut self, address: u16, frame: &mut Frame) -> u8 { self.read_byte(address, frame) } fn write(&mut self, address: u16, value: u8, frame: &mut Frame) { self.write_byte(address, value, frame) } } // -- running ---------------------------------------------------------------- /// The board's running methods, on the CPU that holds it (Rust-forced, see the module header). pub trait Running { /// The CPU's state (so a debugger can drive the board). fn capture_state(&self) -> CpuState; /// One CPU step (instruction, interrupt entry or reset); machine cycles it took. fn board_step(&mut self) -> u64; /// Run until the next frame boundary (ANTIC's line 0, cycle 0). fn run_frame(&mut self); fn run_cycles(&mut self, cycles: u64); /// 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). fn reset(&mut self); } impl Running for Cpu { fn capture_state(&self) -> CpuState { Mos6502::capture_state(self) } fn board_step(&mut self) -> u64 { let before = self.bus.cycles; self.step(); self.bus.cycles - before } fn run_frame(&mut self) { let target = self.bus.frames + 1; while self.bus.frames < target { self.step(); } } fn run_cycles(&mut self, cycles: u64) { let target = self.bus.cycles + cycles; while self.bus.cycles < target { self.step(); } } fn reset(&mut self) { self.bus.antic.reset(); self.frame.request_reset(); } }