// SPDX-License-Identifier: MIT // Follows, where noted as [MiS], Atari7800_MiSTer (k7800) by Jamie Blanks, MIT License, // Copyright (c) 2019-2026 Jamie Blanks: the HALT rounding sally.sv captures. No HDL // copied. Full notice: NOTICE, section 3. //! The 7800 board: one MARIA-clock timeline, both decoders, INPTCTRL, HALT and RDY, //! the floating data bus. //! //! **One timeline** (docs/timing.md "What a cycle looks like to the board"). //! 6502-rust calls [`Board::read_byte`] or [`Board::write_byte`] once per //! CPU cycle, dummy cycles included. Inside each call the board advances the //! MARIA clock (crystal / 2) and everything that hangs off it, one clock at a //! time: MARIA, the TIA (one half colour clock per MARIA clock: MARIA supplies //! the TIA's 3.58 MHz clock, DOC: [MT84] 2.1), and, once per Φ2 period, the RIOT's //! pulse count and the cartridge's `tick`. `step()`'s returned cycle //! count is never used for time. //! //! A cycle, in order: //! //! 1. **HALT** (top of both callbacks). While MARIA asks for the bus and the //! INPTCTRL gate lets HALT through, whole Φ2 periods of 4 clocks pass with the //! CPU's clock held (DOC: [MT84] 2.1, C1): MARIA's DMA reads happen inside them, //! the RIOT and the cartridge still count them (DOC: two reports in timing.md, //! no trace; U10, a PCLK0 capture across DMA would settle it). The CPU's divider //! keeps its phase across the DMA, so the CPU resumes at the first period //! boundary after MARIA lets go (HYPOTHESIS for U2, consistent with "HALT is low //! for a whole number of CPU cycles", [MiS] sally.sv's reported capture (DOC), //! docs/timing.md "Rounding to the CPU's cycle"; a PCLK0 capture would settle it). //! 2. **RDY** (reads only): while MARIA's WSYNC latch or the TIA's RDY holds the //! line low (the two are wire-ANDed, DOC: [1702B] pins), the read repeats in //! 4-clock periods; `note_stall()` is called as each begins, as famicom-python //! does for its DMC DMA, because a DLI can arrive while the CPU waits. //! 3. **The cycle**: 6 MARIA clocks if the address is in a slow row of [MT84] //! Figure 2 (TIA, 6532), or for every cycle while MEN = 0 (the 2600 decoder); //! 4 otherwise (DOC: [MT84] Figure 2, [1702B] p. 29). A read takes its value after //! all but the last clock (Φ2 high); a write lands on the last clock, where Φ2 //! falls (HYPOTHESIS, U3: [1702B] p. 29's diagram or [GLD] would settle the //! shape; the TIA takes it on that step, as a2600-python's board does, DIE). //! 4. The cartridge sees the cycle (address, data, R/W, HALT false). //! //! **Two decoders, chosen by INPTCTRL D1 (MEN)**, both from [MT84] Figure 2 (DOC: the //! decoder as a truth table, read off the page image at 200 dpi, p. 9): //! //! - MEN = 1 ("7800 mode"): TIA at $00-$1F (A8/A9 don't care: $100, $200, $300), //! MARIA at $20-$3F (same mirrors), 6532 ports at $280-$2FF/$380-$3FF, 6532 RAM //! at $480-$4FF/$580-$5FF, RAM1 $1800-$1FFF, RAM0 $2000-$27FF and its zero/one //! page shadows $040-$0FF/$140-$1FF. Two places where Figure 2 and [SG] App. 1 //! disagree are numbered C14 ($240-$2FF/$340-$3FF) and C15 ($2800-$2FFF); the //! board follows [SG] in both (DOC), see docs/undocumented-behavior.md. //! - MEN = 0 ("2600 mode" in Figure 2): only A12 and A7 decode: A12 = 1 the //! cartridge (or the BIOS while EXT = 0), else A7 = 0 the TIA, A7 = 1 the 6532; //! **every cycle slow** (DOC). This is also the decoder at power-on, before the //! BIOS writes INPTCTRL for the first time (DOC: [SG], INPTCTRL powers up 0). //! //! **INPTCTRL** (DOC: [SG] "INPTCTRL register"): any write to the TIA's addresses //! while unlocked also writes the latch: D0 lock, D1 MEN (MARIA and system RAM), D2 //! EXT (cartridge instead of BIOS in the upper half), D3 TIA-EN. HALT reaches the //! CPU only after two writes (DOC: [SG]). EXT = 0 maps the BIOS over $8000-$FFFF; //! the ROM repeats every its-own-size there (HYPOTHESIS, U19: the console //! schematic's decoder would settle what a console returns). //! //! **The floating bus**: [`Board::data_bus`] is the last byte on the bus; TIA reads //! drive D7/D6 only (DIE: a2600-python's Sim2600 judge, C17), undriven addresses //! return the latch (DOC: the wiki's M.I.A. bus-capacitance note, C18; start-here.md). //! //! Rust-forced differences (a7800-python `board.py` at d6b220d): //! //! - The board is 6502-rust's [`Bus`]: the reference's `self.cpu` calls //! (`request_non_maskable_interrupt`, `request_maskable_interrupt`, `note_stall`, //! `dma_stalled`) go to the CPU's [`Frame`], which the core hands every bus callback; //! a board driven without a CPU (the unit tests) is handed a spare frame, where the //! reference's `cpu is None` skips them, with nothing else that differs. //! - `maria.read = self.dma_read`: MARIA is the board's field, so its DMA reads go //! through [`Port`], the board's other fields borrowed beside MARIA for the length of an //! advance (maria.rs, "The DMA read"); [`Port::read_device`] and [`Port::dma_read`] are //! the reference's `_read_device` and `dma_read`. `self.clocks` is read through the //! port, which holds the value it had when the advance began, as the reference's //! `_advance` adds its clocks only after its loop. //! - The RIOT is shared (`Rc>`), as a2600-rust's board takes it (a //! controller reads its port when the TIA is read). //! - `faults` lives in MARIA ([`Maria::faults`]), the one set the reference shares. //! - `on_inptctrl` is handed `(clocks, value)`: the reference's lambda reads //! `board.clocks` from the board it closes over. //! - The light gun's sensor reads MARIA's picture from inside the TIA's pad callback in //! the reference; here the board, just before a TIA read that asks the pads, has the gun //! look ([`LightGun::look`], the same render and the same pixel) and the gun's pad //! callback uses what it saw (controllers.rs). use std::cell::RefCell; use std::rc::Rc; use a2600::riot::RIOT; use a2600::tia::TIA; use sixfiveohtwo::{Bus, Frame}; use crate::cartridge::connector::Cartridge; use crate::controllers::LightGun; use crate::machine::Machine; use crate::maria::{DmaBus, Faults, Maria}; pub const FAST: u32 = 4; // MARIA clocks; DOC: [MT84] 2.1, [1702B] p. 29 pub const SLOW: u32 = 6; pub const PERIOD: u32 = 4; // INPTCTRL bits (DOC: [SG]). pub const LOCK: u8 = 0x01; pub const MEN: u8 = 0x02; pub const EXT: u8 = 0x04; pub const TIA_EN: u8 = 0x08; /// An observer of every bus cycle: `(kind, address, value, clock)`; kind is /// 'R'/'W' for the CPU and 'D' for a MARIA DMA read. pub type BusObserver = Box; /// Called after every INPTCTRL write with the board's clock and the new value. pub type InptctrlCallback = Box; pub struct Board { pub machine: Machine, pub cartridge: Box, pub maria: Maria, pub tia: TIA, pub riot: Rc>, pub ram: Vec, // $1800-$27FF: RAM1, RAM0; DOC [MT84] pub bios: Option>, pub inptctrl: u8, // DOC: [SG] (timing.md "Power-on and reset") pub inptctrl_writes: u32, // HALT reaches the CPU after two (DOC: [SG]) pub locked: bool, pub clocks: u64, // MARIA clocks since power pub periods: u64, // Φ2 periods since power: the RIOT's and the cartridge's count pub slow_cycles: u64, pub halted_periods: u64, // periods the CPU's clock was held by HALT pub stalled_periods: u64, // periods a read was repeated for RDY pub data_bus: u8, pub bus_observers: Vec, pub on_inptctrl: Option, pub nmi_after: Option, // a DLI waits for the period count to pass this pub light_gun: Option, // Instrumentation for the DLI timing test (the reference wraps `_halted` and the // CPU's request): the period count at the last HALT release, and, when `Some`, the // periods from that release to each NMI request. Not hardware values. pub released_at: u64, pub nmi_delays: Option>, } /// The board's fields beside MARIA, borrowed for one advance or one access. pub struct Port<'a> { pub cartridge: &'a mut dyn Cartridge, pub tia: &'a mut TIA, pub riot: &'a RefCell, pub ram: &'a mut [u8], pub bios: Option<&'a [u8]>, pub inptctrl: u8, pub data_bus: &'a mut u8, pub periods: u64, pub clocks: u64, pub bus_observers: &'a mut Vec, pub light_gun: Option<&'a mut LightGun>, } impl Port<'_> { /// The TIA read, with the light gun looking first when the read asks the pads. #[inline] fn tia_read(&mut self, maria: &mut Maria, address: u16) -> u8 { if address & 0x0F >= 8 { if let Some(gun) = self.light_gun.as_mut() { gun.look(maria); } } self.tia.read(address) } /// The console's own devices; None where none responds (the cartridge's turn). /// Decode: DOC, [MT84] Figure 2 and [SG] App. 1; TIA D5-D0 from the bus: DIE (C17); /// the BIOS mirrored by its size: HYPOTHESIS (U19). pub fn read_device(&mut self, maria: &mut Maria, address: u16) -> Option { let control = self.inptctrl; if control & MEN == 0 { if address & 0x1000 != 0 { if control & EXT == 0 { if let Some(bios) = self.bios { return Some(bios[address as usize & (bios.len() - 1)]); } } return None; } if address & 0x80 != 0 { return Some(self.riot.borrow_mut().read(address, self.periods)); } return Some(self.tia_read(maria, address) | (*self.data_bus & 0x3F)); } if address < 0x0400 { let low = address & 0xFF; if low < 0x20 { return Some(self.tia_read(maria, address) | (*self.data_bus & 0x3F)); } if low < 0x40 { return maria.read_register(low as u8); } if address & 0x200 == 0 { // $040-$0FF, $140-$1FF: RAM0 shadows (DOC: [SG] row 6) return Some(self.ram[0x800 | (address as usize & 0x1FF)]); } if address & 0x80 != 0 { return Some(self.riot.borrow_mut().read(address, self.periods)); } return None; // $240-$27F, $340-$37F (DOC: [SG], C14) } if address < 0x0600 { if address & 0x80 != 0 { return Some(self.riot.borrow_mut().read(address & 0x7F, self.periods)); // 6532 RAM } return None; } if address < 0x1800 { return None; } if address < 0x2800 { return Some(self.ram[address as usize - 0x1800]); } if address < 0x3000 { return Some(self.ram[0x800 | (address as usize & 0x7FF)]); // DOC: [SG] row 7 (C15) } if address & 0x8000 != 0 && control & EXT == 0 { if let Some(bios) = self.bios { return Some(bios[address as usize & (bios.len() - 1)]); } } None } } impl DmaBus for Port<'_> { /// One DMA read by MARIA (HALT asserted): the decoder still selects /// (DOC: [MT84] Figure 2's footnote on par23); the cartridge sees it with halt true. /// What a DMA read of the TIA or MARIA's registers ($00-$3F) returns: the bus latch, /// HYPOTHESIS (U12; [GLD] or a capture would settle it). fn dma_read(&mut self, maria: &mut Maria, address: u16) -> u8 { let driven = self.cartridge.access(address, *self.data_bus, true, true, self.clocks); let value = if address >= 0x40 { self.read_device(maria, address) } else { None }; let value = match value { Some(v) => v, None => driven.unwrap_or(*self.data_bus), }; *self.data_bus = value; for observer in self.bus_observers.iter_mut() { observer('D', address, value, self.clocks); } value } } impl Board { pub fn new(machine: Machine, cartridge: Box, bios: Option>) -> Board { let power = machine.power_on; let maria = Maria::new( machine.lines, machine.vblank_end, machine.dma_lines, power.line, power.clock, ); // The TIA revision is the 2600-mode row's (a2600-python docs/api.md: the PAL // 7800's from the #699 tables, TEST ROM; the NTSC 7800's the reference 10444D, // unmeasured there); the power-on phase is this board's own (PowerOn below). let mut tia = TIA::new(power.tia_hclock, machine.mode_2600.tia_revision); // I0-I3 with nothing charging them read 0 (DOC: the 2600 schematic, a2600-python // C19); I4/I5 pulled up (DOC: schematic). tia.inputs = 0x30; let mut riot = RIOT::new( power.riot_ram_fill, power.riot_timer_value, power.riot_timer_divider, power.riot_timer_first_decrement, ); riot.input_b = machine.switches; Board { machine, cartridge, maria, tia, riot: Rc::new(RefCell::new(riot)), ram: vec![power.ram_fill; 0x1000], bios, inptctrl: 0, inptctrl_writes: 0, locked: false, clocks: 0, periods: 0, slow_cycles: 0, halted_periods: 0, stalled_periods: 0, data_bus: 0, bus_observers: Vec::new(), on_inptctrl: None, nmi_after: None, light_gun: None, released_at: 0, nmi_delays: None, } } /// The seeded faults (shared with MARIA, as in the reference). pub fn faults(&mut self) -> &mut Faults { &mut self.maria.faults } /// MARIA and the rest of the board, borrowed apart. #[inline] pub fn split(&mut self) -> (&mut Maria, Port<'_>) { ( &mut self.maria, Port { cartridge: &mut *self.cartridge, tia: &mut self.tia, riot: &self.riot, ram: &mut self.ram, bios: self.bios.as_deref(), inptctrl: self.inptctrl, data_bus: &mut self.data_bus, periods: self.periods, clocks: self.clocks, bus_observers: &mut self.bus_observers, light_gun: self.light_gun.as_mut(), }, ) } // -- time --------------------------------------------------------------- #[inline] fn advance(&mut self, clocks: u32) { let (maria, mut port) = self.split(); for _ in 0..clocks { maria.clock(&mut port); port.tia.step(None); } self.clocks += clocks as u64; } #[inline] fn period_end(&mut self, frame: &mut Frame) { self.periods += 1; self.cartridge.tick(self.data_bus); if self.cartridge.irq() { frame.request_maskable_interrupt(); } } /// MARIA owns the bus: whole 4-clock periods with the CPU's clock held. fn halted(&mut self, frame: &mut Frame) { self.maria.granted = true; while self.maria.halt { self.advance(PERIOD); self.halted_periods += 1; self.period_end(frame); } self.maria.granted = false; self.released_at = self.periods; self.take_dli(); } /// A DLI raised by the DMA that just ended reaches the CPU's NMI "one cycle /// after HALT- is released" (DOC: [1702B] p. 14): it is requested at the top of /// the second CPU cycle after the release (6502-python counts a request made /// in a cycle's callback as arriving during that cycle). fn take_dli(&mut self) { if self.maria.nmi { self.maria.nmi = false; self.nmi_after = Some(self.periods - if self.maria.faults.has(Faults::DLI_EARLY) { 1 } else { 0 }); } } fn request_nmi(&mut self, frame: &mut Frame) { if let Some(delays) = self.nmi_delays.as_mut() { delays.push(self.periods - self.released_at); } frame.request_non_maskable_interrupt(); } /// What happens before every CPU cycle: a due DLI, then HALT. #[inline] fn top(&mut self, frame: &mut Frame) { if let Some(after) = self.nmi_after { if self.periods > after { self.nmi_after = None; self.request_nmi(frame); } } if self.maria.halt && self.inptctrl_writes >= 2 { // DOC: [SG] INPTCTRL self.halted(frame); } else if self.maria.nmi { self.take_dli(); // a DMA that ran beside the CPU (HALT still gated off) } if let Some(after) = self.nmi_after { if self.periods > after { self.nmi_after = None; // only the seeded "dli-early" fault is due already self.request_nmi(frame); } } } pub fn halt_enabled(&self) -> bool { self.inptctrl_writes >= 2 } // -- the decoders -------------------------------------------------------- /// Figure 2's slow rows (TIA, 6532), or any cycle under the 2600 decoder (DOC: [MT84]). pub fn is_slow(&self, address: u16) -> bool { if self.inptctrl & MEN == 0 { return true; } if address >= 0x0600 { return false; } if address < 0x0400 { if address & 0xE0 == 0 { return !self.maria.faults.has(Faults::FAST_TIA); // TIA: $00-$1F, A8/A9 free } return address & 0x280 == 0x280; // 6532 ports: $280-$2FF, $380-$3FF } address & 0x80 != 0 // 6532 RAM: $480-$4FF, $580-$5FF } /// The console's own devices (`Port::read_device`, MARIA beside it). pub fn read_device(&mut self, address: u16) -> Option { let (maria, mut port) = self.split(); port.read_device(maria, address) } /// Perform a console-device write except the TIA's; true if a device took it. /// Decode as [`Port::read_device`] (DOC). fn write_device(&mut self, address: u16, value: u8) -> bool { let control = self.inptctrl; if control & MEN == 0 { if address & 0x1000 != 0 { return false; } if address & 0x80 != 0 { self.riot.borrow_mut().write(address, value, self.periods); } return true; } if address < 0x0400 { let low = address & 0xFF; if low < 0x20 { return true; } if low < 0x40 { self.maria.write_register(low as u8, value); return true; } if address & 0x200 == 0 { self.ram[0x800 | (address as usize & 0x1FF)] = value; return true; } if address & 0x80 != 0 { self.riot.borrow_mut().write(address, value, self.periods); return true; } return false; } if address < 0x0600 { if address & 0x80 != 0 { self.riot.borrow_mut().write(address & 0x7F, value, self.periods); return true; } return false; } if address < 0x1800 { return false; } if address < 0x2800 { self.ram[address as usize - 0x1800] = value; return true; } if address < 0x3000 { self.ram[0x800 | (address as usize & 0x7FF)] = value; return true; } false } fn is_tia(&self, address: u16) -> bool { if self.inptctrl & MEN == 0 { return address & 0x1080 == 0; } address < 0x0400 && address & 0xE0 == 0 } /// The latch takes TIA-selected writes with A5 = 0 (DOC: [SG]: "mapped to /// $0000-$001F"; under MEN = 0 the TIA select also covers $20-$7F, and /// whether the latch sees those is unknown: HYPOTHESIS, U23, the console /// schematic's latch wiring would settle it). Lock until power-off: DOC, [SG]. fn write_inptctrl(&mut self, address: u16, value: u8) { if address & 0x20 != 0 { return; } if self.locked && !self.maria.faults.has(Faults::IGNORE_LOCK) { return; } self.inptctrl = value & 0x0F; self.inptctrl_writes += 1; self.locked = value & LOCK != 0; self.maria.enabled = value & MEN != 0; if self.inptctrl_writes == 2 && !self.maria.halt { self.maria.granted = false; // HALT now reaches the CPU: the bus is given per DMA } if let Some(callback) = self.on_inptctrl.as_mut() { callback(self.clocks, value); } } // -- one CPU cycle --------------------------------------------------------- pub fn read_byte(&mut self, address: u16, frame: &mut Frame) -> u8 { self.top(frame); if self.maria.rdy_low || self.tia.rdy_low { while self.maria.rdy_low || self.tia.rdy_low { frame.note_stall(); self.advance(PERIOD); self.stalled_periods += 1; self.period_end(frame); self.top(frame); } frame.dma_stalled = true; } else { frame.dma_stalled = false; } let slow = self.is_slow(address); if slow { self.slow_cycles += 1; } self.advance((if slow { SLOW } else { FAST }) - 1); let t = self.clocks; let driven = self.cartridge.access(address, self.data_bus, true, false, t); let value = match self.read_device(address) { Some(v) => v, None => driven.unwrap_or(self.data_bus), }; self.data_bus = value; for observer in self.bus_observers.iter_mut() { observer('R', address, value, t); } self.advance(1); self.period_end(frame); value } pub fn write_byte(&mut self, address: u16, value: u8, frame: &mut Frame) { self.top(frame); let slow = self.is_slow(address); if slow { self.slow_cycles += 1; } self.advance((if slow { SLOW } else { FAST }) - 1); let t = self.clocks; self.data_bus = value; self.cartridge.access(address, value, false, false, t); if self.is_tia(address) { self.write_inptctrl(address, value); let (maria, mut port) = self.split(); maria.clock(&mut port); self.tia.step(Some(((address & 0x3F) as u8, value))); self.clocks += 1; } else { self.write_device(address, value); self.advance(1); } for observer in self.bus_observers.iter_mut() { observer('W', address, value, t); } self.period_end(frame); } /// `dma_read` on its own (the reference's method; MARIA calls it through the port). pub fn dma_read(&mut self, address: u16) -> u8 { let (maria, mut port) = self.split(); port.dma_read(maria, address) } } impl Bus for Board { #[inline] fn read(&mut self, address: u16, frame: &mut Frame) -> u8 { self.read_byte(address, frame) } #[inline] fn write(&mut self, address: u16, value: u8, frame: &mut Frame) { self.write_byte(address, value, frame) } }