// SPDX-License-Identifier: MIT //! Mikey's eight timers and the four audio channels' timers: one shared prescaler //! (`mikey/timers.py`). //! //! Modelling level: cycle (every source clock is an event on the 16 MHz tick line). //! //! Sources, all DOC unless tagged otherwise: //! //! - Spec §10 and Appx 2 (`$FD00-$FD1F`, `$FD20-$FD3F`): eight 8-bit down //! counters, BKUP/CTLA/CNT/CTLB; source 0-6 = 1, 2, 4, 8, 16, 32, 64 µs; 7 = the //! linked predecessor; links 0 -> 2 -> 4 and 1 -> 3 -> 5 -> 7 -> audio 0 -> 1 -> 2 -> //! 3 -> 1. //! - LT timers guide (lynx-tests, MIT; measured on consoles): a count of N borrows on //! the N+1th clock; the interrupt is requested on the borrow, i.e. when the counter //! is already zero and is clocked again; DONE is sticky; DONE, the pending bit and //! the interrupt enable are independent; a CTLB write with bit 1 injects one clock. //! - Spec §16 defects: DONE must be clear for a (non-reloading) timer to count //! (C6: TEST ROM `timers` 5, 7 show a reloading timer keeps counting); //! RESET_DONE (CTLA bit 6) is a level (C5). //! //! Differences forced by Rust: the Python bank calls `on_borrow(index, when)` (Mikey's //! method) in the middle of a clock; a Rust bank cannot hold a mutable reference to the //! Mikey that owns it, so each borrow is pushed on `borrows`, in the same order, and Mikey //! drains the queue as soon as the bank's call returns (`Mikey::drain_borrows`). This is //! the same behaviour because nothing a borrow handler touches (the display, the UART, the //! audio shift registers, the pending bits by OR) is read by the counting itself. A //! timer's `successor` (a reference) is an index. use serde::{Deserialize, Serialize}; pub const TICKS_PER_US: i64 = 16; // DOC: 16 MHz crystal, 1 tick = 62.5 ns /// DOC (Appx 2, LT table): the fixed successor of each timer; 8-11 are audio 0-3. pub const SUCCESSOR: [(usize, usize); 10] = [ (0, 2), (2, 4), (1, 3), (3, 5), (5, 7), (7, 8), (8, 9), (9, 10), (10, 11), (11, 1), ]; /// One down counter. Plain integers only (the Rust transcription follows it). #[derive(Clone, Serialize, Deserialize)] pub struct Timer { pub backup: u8, pub count: u8, pub ctla: u8, pub done: u8, pub index: usize, pub irq_bit: u32, pub next_edge: i64, pub successor: Option, } impl Timer { pub fn new(index: usize) -> Timer { Timer { index, backup: 0, // DOC Appx 2: "Timers are reset to 0" ctla: 0, count: 0, done: 0, next_edge: -1, // tick of the next source clock, -1 when not prescaled successor: None, // DOC Appx 2 INTSET: bits 0-3, 5-7 = timers 0-3, 5-7; bit 4 is the UART, not timer 4. irq_bit: if index < 8 && index != 4 { 1 << index } else { 0 }, } } pub fn period(&self) -> i64 { TICKS_PER_US << (self.ctla & 7) } /// CTLB as read at tick `now`. /// /// DOC Appx 2 (FD27 text): "B2 = last clock state (0->1 causes count), B1 = borrow /// in (1 causes count), B0 = borrow out (count=0 and borrow in)": levels of the /// timer's input and output, not latches. TEST ROM audio2 1-3 (linked Timer 1 and /// audio 3 read $08 and $A8 after borrowing; prescaled Timer 7 and audio 3 read /// $04 / $34 just after a count; audio 0 $30 or $34) and LT timers ("CTLB RD/WR": /// a write of $0A reads $08): the borrow pulses are over by the time the CPU /// reads, so B0 and B1 read 0; a linked timer's input (its predecessor's borrow /// pulse) reads 0. TEST ROM timers 1: a stopped timer (CTLA $00) reads $00, so the /// input is gated by the count enable. HYPOTHESIS: a prescaled source is a square /// wave, high for the first half of its period after the counting edge. pub fn ctlb(&self, now: i64) -> u8 { let mut level = 0; if self.ctla & 0x08 != 0 && self.ctla & 7 != 7 { let period = self.period(); level = if now.rem_euclid(period) < period >> 1 { 1 } else { 0 }; } (self.done << 3) | (level << 2) } } /// The twelve counters on one prescaler. A borrow of timer `index` at tick `when` is /// queued on `borrows` for Mikey: the display (0, 2), the UART (4) and the audio shift /// registers (8-11). #[derive(Clone, Serialize, Deserialize)] pub struct TimerBank { pub next_event: i64, pub pending: u32, // INTSET/INTRST bits set by timer borrows and software pub timers: Vec, #[serde(skip)] pub borrows: Vec<(usize, i64)>, } impl Default for TimerBank { fn default() -> Self { Self::new() } } impl TimerBank { pub fn new() -> TimerBank { let mut timers: Vec = (0..12).map(Timer::new).collect(); for (i, j) in SUCCESSOR { timers[i].successor = Some(j); } TimerBank { timers, pending: 0, next_event: 1 << 62, borrows: Vec::new(), } } // -- time ------------------------------------------------------------------------- /// Place the timer's next source clock after `now`. /// /// HYPOTHESIS (U15): the prescaler runs from reset with every source's clock /// edge at a whole multiple of its period on the tick line; the phase at reset /// is not documented (Spec §14 says it may not be deterministic). The first /// interval is therefore N to N+1 periods (DOC Spec §10, LT). pub fn schedule(&mut self, index: usize, now: i64) { let timer = &mut self.timers[index]; if timer.ctla & 0x08 != 0 && timer.ctla & 7 != 7 { let period = timer.period(); timer.next_edge = (now.div_euclid(period) + 1) * period; } else { timer.next_edge = -1; } self.next(); } fn next(&mut self) { let edges = self .timers .iter() .map(|t| t.next_edge) .filter(|&e| e >= 0) .min(); self.next_event = edges.unwrap_or(1 << 62); } pub fn run_until(&mut self, tick: i64) { while self.next_event <= tick { let when = self.next_event; for index in 0..self.timers.len() { // index order: timers 0-7, then audio 0-3 if self.timers[index].next_edge == when { self.timers[index].next_edge = when + self.timers[index].period(); self.clock(index, when, false); } } self.next(); } } // -- counting --------------------------------------------------------------------- /// One input clock. `forced` is a software borrow-in (a CTLB write with bit 1): /// TEST ROM timers 1 (timer stopped, CTLB $00, CNT $80, write $0A -> CNT $7F) shows /// it counts with the count enable off; HYPOTHESIS: it also ignores DONE. pub fn clock(&mut self, index: usize, when: i64, forced: bool) { let timer = &mut self.timers[index]; let ctla = timer.ctla; if !forced { if ctla & 0x08 == 0 { return; } if ctla & 0x40 != 0 { timer.done = 0; // DOC §16: RESET_DONE is a level, not a pulse } if timer.done != 0 && ctla & 0x10 == 0 { return; // DOC §16 + TEST ROM timers 5/7: a done non-reloading timer stops } } if timer.count != 0 { timer.count -= 1; return; } // Terminal borrow (LT: on the clock that finds the count already zero). timer.done = 1; if ctla & 0x10 != 0 { timer.count = timer.backup; } if ctla & 0x80 != 0 && timer.irq_bit != 0 { self.pending |= timer.irq_bit; } let successor = timer.successor; self.borrows.push((index, when)); if let Some(successor) = successor { if self.timers[successor].ctla & 7 == 7 { self.clock(successor, when, false); } } } // -- registers --------------------------------------------------------------------- pub fn read(&self, index: usize, reg: u8, now: i64) -> u8 { let timer = &self.timers[index]; match reg { 0 => timer.backup, 1 => timer.ctla, 2 => timer.count, _ => timer.ctlb(now), } } pub fn write(&mut self, index: usize, reg: u8, value: u8, now: i64) { if reg == 0 { self.timers[index].backup = value; } else if reg == 1 { let timer = &mut self.timers[index]; timer.ctla = value; if value & 0x40 != 0 { timer.done = 0; } self.schedule(index, now); } else if reg == 2 { self.timers[index].count = value; } else { // TEST ROM (LT timers, "CTLB RD/WR"): CNT=$80, write $0A -> CTLB=$08, CNT=$7F: // bit 3 writes DONE, bit 1 injects one clock and does not stay set; bits 0 // and 2 are hardware levels (see Timer.ctlb). if value & 0x02 != 0 { self.clock(index, now, true); } self.timers[index].done = (value >> 3) & 1; } } }