// SPDX-License-Identifier: MIT //! Rung 4: AcidSAP's ten POKEY tests (Avery Lee, MIT; Acid800 1.2) on the core. //! //! Each test runs in the test-only machine below (6502-rust, RAM, the POKEY core, WSYNC, //! VCOUNT and refresh DMA) and decides pass or fail by its own convention: the N flag when it //! reaches `_sap_testEnd`. Every test runs on a machine with a 2-cycle and a 3-cycle IRQ delay //! (AHRM 5.7; the tests accept both). Needs the built AcidSAP files, found through the //! environment variable `ACIDSAP_DIR` (scripts/env.sh sets it to the reference's fetched //! `reference/acid800/out/Release/AcidSAP/standalone`); without it each test says so and //! passes, as the reference's tests skip. //! //! Transcribed from pokey-python's `tests/test_acidsap.py` and `tests/acidsap.py` (at 6ed1ffa). //! The reference's harness runs on 6502-python at 741419a (its `acid` extra); this one on //! 6502-rust, transcribed from that commit and proven equivalent to it. Where Rust forced a //! difference: the machine is the CPU's `Bus`, and the calls the Python harness makes on its //! `cpu` from inside a bus callback (`note_stall`, the IRQ request calls) go to the `Frame` //! the callback is handed. `twotone`, a strict xfail in the reference, is a test that its //! verdict is not a pass. use std::collections::{HashMap, VecDeque}; use std::path::{Path, PathBuf}; use pokey::POKEY; use sixfiveohtwo::{Bus, Frame, Mos6502, N as FLAG_N}; // -- the machine (tests/acidsap.py) ----------------------------------------- // // A test-only AcidSAP machine: 6502-rust, 64 KB of RAM, the POKEY core, a sliver of ANTIC. // // AcidSAP (Avery Lee, MIT; Acid800 1.2) is Acid800 cut down to what a SAP type D // player offers: a 6502, RAM, POKEY, and from ANTIC only WSYNC and VCOUNT. Each // standalone test is a `.sap` file whose INIT is $2000; it ends by jumping to // `_sap_testEnd` (address from its `.lab` file) with the N flag set for a // failure and clear for a pass; its text goes to $1000 (`_disp_putchar`). // // The machine, cycle by cycle (every bus cycle is one callback; the callback // performs the access, then ticks POKEY: B0.1): // // - 114 cycles per scan line, 262 lines (NTSC). // - Refresh DMA halts the CPU at cycles 25, 29, ..., 57 of every line, with // playfield DMA off [AHRM 4.14 "Memory refresh DMA"]. POKEY still ticks. // - WSYNC ($D40A): one more cycle runs, then RDY holds the CPU's next read // until cycle 105; a write at cycle 104 or later waits for the next line's 105 // [AHRM 4.9]. RDY does not stop write cycles [AHRM 4.9, // "Read-modify-write instructions"]. // - VCOUNT ($D40B): line / 2, the new value from cycle 111 of the line before; // $83 on cycle 111 of the last line [AHRM 4.10]. // - /IRQ: the CPU sees in cycle c the line as it stood after tick c - 1 - lag; // `lag` 0 is the 2-cycle machine of AHRM 5.7 (a 130XE in Acid800's // comments), 1 the 3-cycle one (an 800XL). // - No NMIs (SAP mode). Other I/O ($D000-$D7FF outside POKEY and ANTIC) reads // $FF and ignores writes. POKEY starts as a SAP player leaves it: SKCTL = 3, // everything else 0. const LINE: u64 = 114; const LINES: u64 = 262; /// AHRM 4.14: nine cycles from 25, every four fn refresh(hpos: u64) -> bool { (25..58).step_by(4).any(|c| c == hpos) } const WSYNC_RELEASE: u64 = 105; // AHRM 4.9 const WSYNC_DEADLINE: u64 = 103; const VCOUNT_EARLY: u64 = 111; // AHRM 4.10 const STUB: u16 = 0x0600; // where INIT "returns" to: JMP * (the tests never return) type Segments = Vec<(usize, Vec)>; /// The header tags and the binary segments of a SAP file. fn load_sap(path: &Path) -> (HashMap, Segments) { let data = std::fs::read(path).expect("read SAP"); let split = data.windows(2).position(|w| w == [0xFF, 0xFF]).unwrap(); let mut header = HashMap::new(); for line in String::from_utf8_lossy(&data[..split]).lines() { if !line.trim().is_empty() { let (key, value) = line.split_once(' ').unwrap_or((line, "")); header.insert(key.to_string(), value.trim().to_string()); } } let mut segments = Vec::new(); let mut pos = split; while pos + 4 <= data.len() { if data[pos] == 0xFF && data[pos + 1] == 0xFF { pos += 2; continue; } let start = data[pos] as usize | (data[pos + 1] as usize) << 8; let end = data[pos + 2] as usize | (data[pos + 3] as usize) << 8; pos += 4; let stop = (pos + end - start + 1).min(data.len()); segments.push((start, data[pos..stop].to_vec())); pos += end - start + 1; } (header, segments) } fn load_labels(path: &Path) -> HashMap { let mut labels = HashMap::new(); let text = String::from_utf8_lossy(&std::fs::read(path).expect("read labels")).into_owned(); for line in text.lines() { let parts: Vec<&str> = line.split_whitespace().collect(); if parts.len() == 3 { labels.insert( parts[2].to_string(), u16::from_str_radix(parts[1], 16).unwrap(), ); } } labels } struct Machine { ram: Vec, chip: POKEY, cycle: u64, hpos: u64, vline: u64, /// RDY low for reads in cycles [from, until) rdy: Vec<(u64, u64)>, seen: VecDeque, lag: usize, cpu_irq: bool, } impl Machine { // -- time ------------------------------------------------------------ fn tick(&mut self) { self.chip.tick(); if self.seen.len() == self.lag + 1 { self.seen.pop_front(); } self.seen.push_back(self.chip.irq); self.cycle += 1; self.hpos += 1; if self.hpos == LINE { self.hpos = 0; self.vline = (self.vline + 1) % LINES; } } fn sync_irq(&mut self, frame: &mut Frame) { let level = self.seen[0]; if level != self.cpu_irq { self.cpu_irq = level; if level { frame.request_maskable_interrupt(); } else { frame.clear_maskable_interrupt(); } } } /// Burn the cycles in which the CPU is halted before this access. fn halts(&mut self, is_read: bool, frame: &mut Frame) { self.sync_irq(frame); let mut stalled = false; for _ in 0..3 * LINE { // bounded: a WSYNC wait is under two lines let rdy = is_read && self .rdy .iter() .any(|&(a, b)| a <= self.cycle && self.cycle < b); if !rdy && !refresh(self.hpos) { return; } if is_read && !stalled { frame.note_stall(); } stalled = true; self.tick(); self.sync_irq(frame); if is_read { frame.note_stall(); } } panic!("the CPU stayed halted for three lines"); } fn wsync(&mut self) { // AHRM 4.9: one more cycle runs, then the next read waits for cycle 105 let release = if self.hpos <= WSYNC_DEADLINE { self.cycle + WSYNC_RELEASE - self.hpos } else { self.cycle + LINE - self.hpos + WSYNC_RELEASE }; let mut windows: Vec<(u64, u64)> = self .rdy .iter() .copied() .filter(|w| w.1 > self.cycle) .collect(); if !windows.iter().any(|&(_, until)| until == release) { // an RMW's second write, same line windows.push((self.cycle + 2, release)); } self.rdy = windows; } fn vcount(&self) -> u8 { let mut line = self.vline; if self.hpos >= VCOUNT_EARLY { // AHRM 4.10, and its end-of-frame anomaly line += 1; if line == LINES && self.hpos > VCOUNT_EARLY { line = 0; } } (line >> 1) as u8 } fn text(&self) -> String { let mut out = String::new(); for &byte in &self.ram[0x1000..0x1400] { if byte == 0 { break; } out.push(if byte == 0x9B { '\n' } else if (32..127).contains(&byte) { byte as char } else { '?' }); } out } } // -- the bus ------------------------------------------------------------- impl Bus for Machine { fn read(&mut self, address: u16, frame: &mut Frame) -> u8 { self.halts(true, frame); let page = address >> 8; let value = if page == 0xD2 { self.chip.read((address & 0x0F) as u8) } else if page == 0xD4 && address & 0x0F == 0x0B { self.vcount() } else if (0xD0..=0xD7).contains(&page) { 0xFF } else { self.ram[address as usize] }; self.tick(); value } fn write(&mut self, address: u16, value: u8, frame: &mut Frame) { self.halts(false, frame); let page = address >> 8; if page == 0xD2 { self.chip.write((address & 0x0F) as u8, value); } else if page == 0xD4 && address & 0x0F == 0x0A { self.wsync(); } else if (0xD0..=0xD7).contains(&page) { // other I/O ignores writes } else { self.ram[address as usize] = value; } self.tick(); } } struct Run { cpu: Mos6502, labels: HashMap, } impl Run { fn new(sap: &Path, lag: usize) -> Self { let (header, segments) = load_sap(sap); assert_eq!( header.get("TYPE").map(String::as_str), Some("D"), "SAP type" ); let labels = load_labels(&sap.with_extension("lab")); let mut ram = vec![0u8; 0x10000]; for (start, data) in segments { ram[start..start + data.len()].copy_from_slice(&data); } let mut chip = POKEY::default(); chip.write(15, 3); // SKCTL = 3, as a SAP player leaves it chip.tick(); // INIT is called as a subroutine; it never returns in these tests ram[STUB as usize..STUB as usize + 3].copy_from_slice(&[ 0x4C, STUB as u8, (STUB >> 8) as u8, ]); let ret = STUB - 1; ram[0x01FF] = (ret >> 8) as u8; ram[0x01FE] = ret as u8; let machine = Machine { ram, chip, cycle: 0, hpos: 0, vline: 0, rdy: Vec::new(), seen: VecDeque::from(vec![false; lag + 1]), lag, cpu_irq: false, }; let mut cpu = Mos6502::new(machine); cpu.s = 0xFD; cpu.pc = u16::from_str_radix(&header["INIT"], 16).unwrap(); Run { cpu, labels } } // -- running a test ---------------------------------------------------- /// Run to `_sap_testEnd`: (Some(true) pass / Some(false) fail / None out of time, the text). fn run(&mut self, max_cycles: u64) -> (Option, String) { let end = self.labels["_sap_testEnd"]; let mut verdict = None; while self.cpu.bus.cycle < max_cycles { self.cpu.step(); if self.cpu.pc == end { verdict = Some(self.cpu.p & FLAG_N == 0); break; } } (verdict, self.cpu.bus.text()) } } // -- the tests (tests/test_acidsap.py) ------------------------------------------ fn sap_dir() -> Option { std::env::var_os("ACIDSAP_DIR").map(PathBuf::from) } fn acidsap(name: &str, lag: usize, expect_pass: bool) { let Some(dir) = sap_dir() else { eprintln!("skipped: ACIDSAP_DIR is not set (scripts/env.sh sets it)"); return; }; let sap = dir.join(format!("pokey_{name}.sap")); if !sap.is_file() { eprintln!("skipped: AcidSAP not fetched ({} missing)", sap.display()); return; } let mut machine = Run::new(&sap, lag); let (verdict, text) = machine.run(2_000_000); if expect_pass { assert!( verdict.is_some(), "did not finish in 2,000,000 cycles: {text:?}" ); assert!(verdict.unwrap(), "{text}"); } else { // the reference's strict xfail: the test must not pass assert_ne!( verdict, Some(true), "{name} passed, but the reference expects it to fail" ); } } macro_rules! acid_tests { ($($test:ident: $name:literal, $lag:literal, $pass:literal;)*) => { $(#[test] fn $test() { acidsap($name, $lag, $pass); })* }; } // Tests that need the serial shift registers, which decision 2 leaves unbuilt: // "twotone": needs the output shift register (decision 2): spaces never reach two-tone. acid_tests! { test_acidsap_addrmirror_2cycle: "addrmirror", 0, true; test_acidsap_addrmirror_3cycle: "addrmirror", 1, true; test_acidsap_asyncrecv_2cycle: "asyncrecv", 0, true; test_acidsap_asyncrecv_3cycle: "asyncrecv", 1, true; test_acidsap_default_2cycle: "default", 0, true; test_acidsap_default_3cycle: "default", 1, true; test_acidsap_inittiming_2cycle: "inittiming", 0, true; test_acidsap_inittiming_3cycle: "inittiming", 1, true; test_acidsap_irqtiming_2cycle: "irqtiming", 0, true; test_acidsap_irqtiming_3cycle: "irqtiming", 1, true; test_acidsap_noise_2cycle: "noise", 0, true; test_acidsap_noise_3cycle: "noise", 1, true; test_acidsap_seroc_2cycle: "seroc", 0, true; test_acidsap_seroc_3cycle: "seroc", 1, true; test_acidsap_timergranularity_2cycle: "timergranularity", 0, true; test_acidsap_timergranularity_3cycle: "timergranularity", 1, true; test_acidsap_timerirq_2cycle: "timerirq", 0, true; test_acidsap_timerirq_3cycle: "timerirq", 1, true; test_acidsap_twotone_2cycle_xfail: "twotone", 0, false; test_acidsap_twotone_3cycle_xfail: "twotone", 1, false; } #[test] fn test_src_never_imports_the_harness() { // decision 6: the harness and 6502-rust stay in tests/ let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); for entry in std::fs::read_dir(src).unwrap() { let path = entry.unwrap().path(); let text = std::fs::read_to_string(&path).unwrap(); assert!( !text.contains("sixfiveohtwo") && !text.contains("acidsap"), "{}", path.display() ); } }