Skip to main content

saturnus_core/machine/
mod.rs

1//! Per-model machine wiring: CPU + [`Hardware`], time keeping, interrupt
2//! sources, SHUTDN handling and the LCD.
3//!
4//! Time: the CPU reports a cycle count per instruction; every cycle advances
5//! the 8192-Hz timer clock by `8192 / clock_hz` ticks (accumulated exactly
6//! in integer arithmetic). Interrupt sources are sampled after each time
7//! advance (wiki: hardware/interrupts):
8//! - timer expiry edges (not masked by INTOFF; wiki:
9//!   questions/interrupt-maskability),
10//! - the ON key (non-maskable),
11//! - the keyboard: a rising edge of "any matrix key down" seen by the ~1 ms
12//!   keyboard poll, which scans the whole keyboard whatever OUT holds (wiki:
13//!   hardware/keyboard "Scanning model"; RSI and the SHUTDN wake still
14//!   look at IN through OUT, as their sources describe), runs only while TIMER2 runs and
15//!   only interrupts while interrupts are enabled (wiki: emulators/emu48
16//!   SP16, SP31),
17//! - card detect: SMP (#10E bit 1) holds NINT low after a card change,
18//!   which sets HST.MP and raises a non-maskable interrupt (wiki:
19//!   hardware/card-ports, emulators/emu48 SP16/SP19; Duchesne counts card
20//!   insertion and removal as non-maskable, wiki: hardware/interrupts),
21//! - the UART: a rising edge of its interrupt request (rx start, rx full,
22//!   tx empty, per the IOC enables; wiki: hardware/uart). Not masked by
23//!   INTOFF, like the timers. Sources disagree: Mastracci 2.3 lists the
24//!   UART as maskable, while Ervin 4.1.2 says INTOFF stops only keyboard
25//!   interrupts and Duchesne 2.1 counts only keys as maskable (wiki:
26//!   hardware/interrupts, questions/interrupt-maskability). Ervin and
27//!   Duchesne are followed; ROM J's serial path executes INTOFF itself
28//!   (#003FF) and INTON when done (#00485), which only matters for keys.
29//!   A pending UART edge also wakes the CPU from SHUTDN (wiki:
30//!   hardware/interrupts "SHUTDN and wake-up", emulators/emu48 SP14).
31//!
32//! Serial line: [`Machine::serial_push`] queues bytes on the wire; the UART
33//! receives them at line rate (11.375 bit times per byte at the #10D baud
34//! rate) as emulated time passes. Bytes the calculator transmits collect
35//! for [`Machine::serial_drain`] as their stop bit ends.
36//!
37//! Display refresh stall: while DON is set the display controller fetches
38//! one row per 4096-Hz tick from RAM and the CPU waits for the bus (wiki:
39//! hardware/display). This is modelled as a flat slowdown, not per row:
40//! every instruction executed with the display on costs 13% more time,
41//! Voyage's measured speed difference between display on and off (wiki:
42//! hardware/display "Voyage additions"). The tutorial's 22-23 us per 244 us
43//! row would give about 10%; Voyage's figure is the measured one and is
44//! used here. Approximate: real stalls depend on when an instruction hits
45//! a row fetch. Time spent in SHUTDN is not stretched. The 42S has no
46//! stall: its display RAM sits in the Lewis chip (inferred; wiki:
47//! hardware/lewis).
48//!
49//! Calibration: before the stall, every instruction's table count is
50//! multiplied by [`Model::cycle_scale_permille`], fitted to real-hardware
51//! benchmark times (wiki: questions/instruction-speed-vs-hardware). The
52//! tables alone run the ROMs 19-34% faster than the real machines with no
53//! documented cause; see the decision log, iteration 7. SHUTDN time is not
54//! scaled either: the timers run on the crystal.
55
56mod hardware;
57mod lcd;
58mod model;
59mod pioneer_rom;
60#[cfg(feature = "profile")]
61pub mod profile;
62
63use std::fmt;
64
65pub use hardware::Port;
66pub(crate) use hardware::{Card, Hardware};
67pub use lcd::{
68    Annunciators, Framebuffer, LCD_HEIGHT, LCD_HEIGHT_28S, LCD_HEIGHT_42S, LCD_WIDTH,
69    LCD_WIDTH_28S, Lcd,
70};
71pub(crate) use model::LewisBoard;
72pub use model::{INTL_17B_BYTES, Model};
73pub use pioneer_rom::address_order as pioneer_address_order;
74
75use crate::cpu::regs::HST_MP;
76use crate::cpu::{ADDR_MASK, Bus as _, Cpu, Event};
77use crate::error::Error;
78use crate::io::{IoRegisters, Key};
79use crate::modules::{Flash, Nce1, Ram, Rom};
80use hardware::{FRAME_TICKS, KEY_IN_MASK};
81
82/// Timer clock rate (wiki: hardware/timers).
83const TICKS_PER_SECOND: u64 = crate::io::timers::TICKS_PER_SECOND as u64;
84/// Timer ticks between two keyboard polls: 8 ticks at 8192 Hz ≈ 1 ms.
85pub(crate) const SCAN_TICKS: u32 = 8;
86/// Upper bound for one SHUTDN time skip, so tick counts stay in `u32`.
87const MAX_SKIP_TICKS: u64 = 1 << 28;
88/// Time a single [`Machine::step`] may skip while shut down: one second.
89const STEP_SKIP_TICKS: u64 = TICKS_PER_SECOND;
90/// Display refresh stall: extra time per instruction while DON is set, in
91/// percent (wiki: hardware/display, Voyage p. 193 "about 13%").
92const STALL_PERCENT: u64 = 13;
93/// Denominator of the fractional instruction time carried between steps:
94/// per-mille calibration ([`Model::cycle_scale_permille`]) times percent
95/// stall.
96pub(crate) const TIME_FRACTION: u64 = 1000 * 100;
97/// The HDW register window in a ROM upload (nibble addresses).
98const IO_WINDOW: std::ops::Range<usize> = 0x100..0x140;
99/// Smallest card image in bytes (1 KB).
100pub const CARD_MIN_BYTES: usize = 1024;
101/// Largest card image any port of any model takes: 4 MB, 48GX port 2
102/// (wiki: hardware/card-ports). Per port and model see
103/// [`Model::card_max_bytes`].
104pub const CARD_MAX_BYTES: usize = 4096 * 1024;
105/// Size of a new, empty RAM card: 128 KB, the largest card every port of
106/// every model with slots takes.
107pub const NEW_CARD_BYTES: usize = 128 * 1024;
108
109/// Why a run stopped before its cycle budget was used up.
110#[derive(Clone, Copy, Debug, PartialEq, Eq)]
111pub enum Halt {
112    /// The CPU met an undefined opcode at `pc`; `nibbles[..len]` are the
113    /// nibbles the decoder read. PC has already advanced past them.
114    InvalidOpcode {
115        /// Address of the opcode.
116        pc: u32,
117        /// Nibbles read by the decoder.
118        nibbles: [u8; 8],
119        /// Number of valid entries in `nibbles`.
120        len: u8,
121    },
122}
123
124impl fmt::Display for Halt {
125    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126        match self {
127            Halt::InvalidOpcode { pc, nibbles, len } => {
128                write!(f, "invalid opcode at #{pc:05X}: ")?;
129                for n in nibbles.iter().take(usize::from(*len)) {
130                    write!(f, "{n:X}")?;
131                }
132                Ok(())
133            }
134        }
135    }
136}
137
138/// A complete calculator: CPU, hardware and the clock that ties them.
139#[derive(Clone, Debug)]
140pub struct Machine {
141    /// The Saturn CPU (public only with the `internals` feature).
142    #[cfg(feature = "internals")]
143    pub cpu: Cpu,
144    #[cfg(not(feature = "internals"))]
145    pub(crate) cpu: Cpu,
146    /// Memory, I/O and keyboard (public only with the `internals`
147    /// feature).
148    #[cfg(feature = "internals")]
149    pub hw: Hardware,
150    #[cfg(not(feature = "internals"))]
151    pub(crate) hw: Hardware,
152    pub(crate) model: Model,
153    /// CPU stopped by SHUTDN.
154    pub(crate) shutdown: bool,
155    /// Total CPU cycles elapsed (including refresh stalls and time skipped
156    /// in SHUTDN).
157    pub(crate) cycles: u64,
158    /// Fractional timer ticks, in units of 1/clock_hz tick.
159    pub(crate) tick_acc: u64,
160    /// Fractional instruction time (calibration and stall), in units of
161    /// 1/[`TIME_FRACTION`] cycle.
162    pub(crate) stall_acc: u64,
163    /// Timer ticks since the last keyboard poll.
164    pub(crate) scan_acc: u32,
165    /// OR(IN[8:0]) at the last keyboard poll.
166    pub(crate) key_level: bool,
167    /// ON was pressed and the interrupt is not delivered yet.
168    pub(crate) on_edge: bool,
169    /// A timer interrupt edge is waiting for delivery.
170    pub(crate) timer_irq: bool,
171    /// A keyboard interrupt edge is waiting for delivery.
172    pub(crate) key_irq: bool,
173    /// A card-detect interrupt edge is waiting for delivery.
174    pub(crate) card_irq: bool,
175    /// A UART interrupt edge is waiting for delivery.
176    pub(crate) uart_irq: bool,
177    /// Checksum of the system ROM, binds saved states to it.
178    pub(crate) rom_sum: u64,
179    /// Executed-instruction profile (feature `profile`; not saved).
180    #[cfg(feature = "profile")]
181    pub profile: profile::Profile,
182}
183
184impl Machine {
185    /// Build a powered-on `model` from its packed ROM image. The image must
186    /// have exactly [`Model::rom_bytes`] bytes; for the 49G it is the 2 MB
187    /// flash image (or the same unpacked, 4 MB), for the 39G and 40G the
188    /// 1 MB ROM (or the same unpacked, 2 MB), for the 17BII also the 96 KB
189    /// international image, mapped from #00000 to #2FFFF; see
190    /// [`Model::accepts_rom_len`]. A Pioneer image in dump order is put in
191    /// address order first ([`pioneer_address_order`]).
192    pub fn new(model: Model, rom_packed: &[u8]) -> Result<Self, Error> {
193        if model == Model::Hp49g {
194            // The whole 2 MB flash image; an unpacked image (one nibble
195            // per byte, 4 MB, as the 1.19-6 emulator ROM) is accepted too.
196            let flash = if rom_packed.len() == 2 * model.rom_bytes() {
197                Flash::from_unpacked(rom_packed)?
198            } else {
199                Flash::from_packed(rom_packed)?
200            };
201            let nce1 = Nce1::Flash(Box::new(flash));
202            return Ok(Self::with_hardware(model, Hardware::new(model, nce1)));
203        }
204        if matches!(model, Model::Hp39g | Model::Hp40g) {
205            return Self::new_aplet_49(model, rom_packed);
206        }
207        let expected = model.rom_bytes();
208        if !model.accepts_rom_len(rom_packed.len()) {
209            return Err(Error::RomSize {
210                expected,
211                actual: rom_packed.len(),
212            });
213        }
214        // A Pioneer image may come in dump order (pioneer_rom).
215        let image = if model.is_lewis() {
216            pioneer_rom::address_order(rom_packed)
217        } else {
218            std::borrow::Cow::Borrowed(rom_packed)
219        };
220        let nce1 = Nce1::Rom(Rom::from_packed(&image));
221        Ok(Self::with_hardware(model, Hardware::new(model, nce1)))
222    }
223
224    /// The 39G or 40G from its 1 MB ROM image, packed (1 MB file) or
225    /// unpacked (2 MB file, one nibble per byte: hpcalc's `rom.39g`). The
226    /// image is an upload from a calculator and carries the I/O register
227    /// window at #00100-#0013F, which is zeroed here as Emu48's Convert
228    /// does (wiki: hardware/hp38g "ROM image", hardware/hp39g-40g); the
229    /// CPU never reads those nibbles once HDW is configured.
230    fn new_aplet_49(model: Model, image: &[u8]) -> Result<Self, Error> {
231        let mut nibbles: Vec<u8> = if image.len() == 2 * model.rom_bytes() {
232            image.to_vec()
233        } else if image.len() == model.rom_bytes() {
234            image.iter().flat_map(|&b| [b & 0xF, b >> 4]).collect()
235        } else {
236            return Err(Error::RomSize {
237                expected: model.rom_bytes(),
238                actual: image.len(),
239            });
240        };
241        nibbles[IO_WINDOW].fill(0);
242        let nce1 = Nce1::BankedRom(Rom::from_nibbles(nibbles));
243        Ok(Self::with_hardware(model, Hardware::new(model, nce1)))
244    }
245
246    /// A powered-on `model` around already built hardware (its NCE1 device
247    /// decides the ROM checksum that binds saved states).
248    pub(crate) fn with_hardware(model: Model, hw: Hardware) -> Self {
249        let rom_sum = crate::state::rom_checksum(hw.nce1.nibbles());
250        let mut m = Self {
251            cpu: Cpu::new(),
252            hw,
253            model,
254            shutdown: false,
255            cycles: 0,
256            tick_acc: 0,
257            stall_acc: 0,
258            scan_acc: 0,
259            key_level: false,
260            on_edge: false,
261            timer_irq: false,
262            key_irq: false,
263            card_irq: false,
264            uart_irq: false,
265            rom_sum,
266            #[cfg(feature = "profile")]
267            profile: profile::Profile::default(),
268        };
269        m.cpu.timing = model.cycle_table();
270        m.reset();
271        m
272    }
273
274    /// Hardware reset: CPU registers, memory controller (all chips
275    /// unconfigured), bank latch and I/O registers back to power-on; RAM contents,
276    /// cards, held keys and the serial wire's queues are kept.
277    pub fn reset(&mut self) {
278        self.cpu.reset();
279        self.hw.mc.reset();
280        // Unlike the RESET instruction (which holds the picture, see
281        // `HeldFrame`), a hardware reset also clears the I/O registers and
282        // so DON: nothing is shown, and the next picture after DON comes
283        // from the bitmaps the ROM sets up, not from before the reset.
284        self.hw.held = None;
285        self.hw.clear_latch();
286        // The flash command interface returns to read array, its write
287        // gate closes with #11C (cleared below).
288        self.hw.nce1.reset();
289        let old_uart = std::mem::take(&mut self.hw.io.uart);
290        self.hw.io = IoRegisters::new();
291        self.hw.io.uart.keep_wire(old_uart);
292        self.hw.lewis.reset();
293        self.hw.lewis_slave.reset();
294        // Card detection is off after reset, so this raises no event.
295        let pins = self.hw.card_pins();
296        self.hw.io.set_card_status(pins);
297        self.hw.set_out(self.cpu.regs.out);
298        self.shutdown = false;
299        self.scan_acc = 0;
300        self.key_level = false;
301        self.on_edge = false;
302        self.timer_irq = false;
303        self.key_irq = false;
304        self.card_irq = false;
305        self.uart_irq = false;
306        self.stall_acc = 0;
307    }
308
309    /// The emulated model.
310    pub fn model(&self) -> Model {
311        self.model
312    }
313
314    /// CPU cycles elapsed since construction.
315    pub fn cycles(&self) -> u64 {
316        self.cycles
317    }
318
319    /// True while the CPU is stopped by SHUTDN.
320    pub fn is_shutdown(&self) -> bool {
321        self.shutdown
322    }
323
324    /// Execute one instruction, or, while shut down, skip time up to the
325    /// next event (at most one second). Returns the cycles that elapsed
326    /// (0 when the call only woke the CPU).
327    pub fn step(&mut self) -> Result<u32, Halt> {
328        let budget = self.ticks_to_cycles(STEP_SKIP_TICKS);
329        self.step_within(budget)
330    }
331
332    /// As [`Machine::step`], but a shut-down CPU skips at most `budget`
333    /// cycles (at least 1), so a caller can stop at its own next event.
334    pub fn step_for(&mut self, budget: u64) -> Result<u32, Halt> {
335        self.step_within(budget.max(1))
336    }
337
338    /// Run until the cycle counter has advanced by at least `n`.
339    pub fn run_cycles(&mut self, n: u64) -> Result<(), Halt> {
340        let end = self.cycles.saturating_add(n);
341        while self.cycles < end {
342            self.step_within(end - self.cycles)?;
343        }
344        Ok(())
345    }
346
347    /// Whether the model's keyboard has `k` ([`Model::has_key`]).
348    pub fn has_key(&self, k: Key) -> bool {
349        self.model.has_key(k)
350    }
351
352    /// Press `k`. Pressing ON raises the (non-maskable) ON interrupt. A key
353    /// the model lacks (see [`Machine::has_key`]) is refused with
354    /// [`Error::KeyNotOnModel`] and changes nothing.
355    pub fn key_down(&mut self, k: Key) -> Result<(), Error> {
356        self.check_key(k)?;
357        if k == Key::On && !self.hw.keyboard.on_pressed() {
358            self.on_edge = true;
359        }
360        self.hw.keyboard.press(k);
361        Ok(())
362    }
363
364    /// Release `k`; a key the model lacks is refused as by
365    /// [`Machine::key_down`].
366    pub fn key_up(&mut self, k: Key) -> Result<(), Error> {
367        self.check_key(k)?;
368        self.hw.keyboard.release(k);
369        Ok(())
370    }
371
372    /// Whether `k` is held down (pressed and not released).
373    pub fn key_is_down(&self, k: Key) -> bool {
374        self.hw.keyboard.is_pressed(k)
375    }
376
377    /// Release every key of the keyboard matrix and ON at once, as if the
378    /// user let go of all of them; nothing else changes (a host's own key
379    /// queue is its own to clear).
380    pub fn release_all_keys(&mut self) {
381        self.hw.keyboard.release_all();
382    }
383
384    fn check_key(&self, k: Key) -> Result<(), Error> {
385        if self.has_key(k) {
386            Ok(())
387        } else {
388            Err(Error::KeyNotOnModel {
389                key: k.name(),
390                model: self.model.name(),
391            })
392        }
393    }
394
395    /// The nibble at `addr` through the current memory mapping, without
396    /// side effects.
397    pub fn peek(&self, addr: u32) -> u8 {
398        self.hw.peek(addr)
399    }
400
401    /// Write nibble `value` (low 4 bits) at `addr` through the current
402    /// memory mapping, as a CPU write would: RAM and cards take it, mask
403    /// ROM ignores it, and a write into the I/O registers or the 49G's
404    /// flash has the side effects the CPU's would. For hosts that patch
405    /// memory (a debugger's poke, a test setting a flag).
406    pub fn poke(&mut self, addr: u32, value: u8) {
407        self.hw.write_nibble(addr & ADDR_MASK, value & 0xF);
408    }
409
410    /// The program counter: the address of the next instruction.
411    pub fn pc(&self) -> u32 {
412        self.cpu.regs.pc
413    }
414
415    /// The display contrast as the ROM set it: the raw 5-bit value, 0-31,
416    /// higher is darker (see [`Model::contrast_range`]).
417    pub fn contrast(&self) -> u8 {
418        self.hw.contrast()
419    }
420
421    /// Whether the display is switched on: DON of the model's display
422    /// controller (#100 bit 3 on the 48 family, DSPCTL bit 3 on the 42S's
423    /// Lewis). The one place hosts ask.
424    pub fn display_on(&self) -> bool {
425        self.hw.display_on()
426    }
427
428    /// The current LCD pixels: 131x64, or 131x16 on the 42S. While an
429    /// UNCNFG has taken the display bitmaps out of the memory map, the
430    /// picture from before it (see `HeldFrame` in `hardware.rs`).
431    pub fn lcd(&self) -> Lcd {
432        if self.hw.profile().lewis == Some(LewisBoard::Clamshell) {
433            Lcd::render_clamshell(&self.hw.lewis, &self.hw.lewis_slave)
434        } else if self.hw.profile().lewis.is_some() {
435            Lcd::render_lewis(&self.hw.lewis)
436        } else {
437            match &self.hw.held {
438                Some(h) if self.hw.io.display_on() => h.lcd.clone(),
439                _ => self.hw.render_lcd(),
440            }
441        }
442    }
443
444    /// The current display: pixels, annunciators and contrast. The
445    /// annunciators are dark while TIMER2 is stopped (wiki: emulators/emu48
446    /// SP19, "TIMER2CTRL's RUN bit also governs the annunciators") or AON
447    /// is clear.
448    pub fn framebuffer(&self) -> Framebuffer {
449        let annunciators = if self.hw.profile().lewis == Some(LewisBoard::Clamshell) {
450            Annunciators::from_clamshell(&self.hw.lewis_slave)
451        } else if self.hw.profile().lewis.is_some() {
452            Annunciators::from_lewis(&self.hw.lewis)
453        } else if self.hw.io.timers.t2_running() {
454            Annunciators::from_bits(self.hw.io.annunciators())
455        } else {
456            Annunciators::default()
457        };
458        Framebuffer {
459            pixels: self.lcd(),
460            annunciators,
461            contrast: self.hw.contrast(),
462        }
463    }
464
465    /// Insert a writable RAM card into `port` (wiki: hardware/card-ports).
466    /// `packed` holds two nibbles per byte, the even address in the low
467    /// nibble, like a ROM image; its length must be a power of two from
468    /// [`CARD_MIN_BYTES`] to [`Model::card_max_bytes`] for the port (128 KB
469    /// on both 48SX ports and 48GX port 1, 4 MB on 48GX port 2). A card
470    /// already in the port is replaced. With card detection enabled the
471    /// ROM sees a card-detect interrupt.
472    pub fn insert_card(&mut self, port: Port, packed: &[u8]) -> Result<(), Error> {
473        let n = packed.len();
474        let max = self.model.card_max_bytes(port);
475        if max == 0 {
476            return Err(Error::NoSuchPort {
477                port: port.number(),
478            });
479        }
480        if !n.is_power_of_two() || !(CARD_MIN_BYTES..=max).contains(&n) {
481            return Err(Error::CardSize { actual: n, max });
482        }
483        let mut ram = Ram::new(n * 2);
484        for (dst, &b) in ram.as_mut_slice().chunks_mut(2).zip(packed) {
485            dst[0] = b & 0xF;
486            dst[1] = b >> 4;
487        }
488        self.hw.set_card(
489            port,
490            Some(hardware::Card {
491                ram,
492                writable: true,
493            }),
494        );
495        Ok(())
496    }
497
498    /// Remove the card from `port`; returns whether there was one.
499    pub fn remove_card(&mut self, port: Port) -> bool {
500        let had = self.hw.card(port).is_some();
501        if had {
502            self.hw.set_card(port, None);
503        }
504        had
505    }
506
507    /// The system ROM (the 49G's whole flash, all 16 banks in order) as
508    /// the machine holds it, one nibble per element. A host reads the
509    /// ROM's own tables from it (command names, see `saturnus-objects`)
510    /// without going through the current memory mapping.
511    pub fn rom_nibbles(&self) -> &[u8] {
512        self.hw.nce1.nibbles()
513    }
514
515    /// A number that moves whenever [`Machine::rom_nibbles`] may have
516    /// changed (the 49G's flash programmed or erased, or replaced by a
517    /// loaded state); constant for mask ROM. Cheap: a host that caches
518    /// something read from the ROM compares it on every use.
519    pub fn rom_generation(&self) -> u64 {
520        self.hw.nce1.generation()
521    }
522
523    /// The contents of the card in `port`, packed like
524    /// [`Machine::insert_card`] takes them, or `None` for an empty port.
525    pub fn card_image(&self, port: Port) -> Option<Vec<u8>> {
526        self.hw.card(port).map(|c| {
527            c.ram
528                .as_slice()
529                .chunks(2)
530                .map(|p| p[0] | (p.get(1).copied().unwrap_or(0) << 4))
531                .collect()
532        })
533    }
534
535    /// Whether the model has a serial port (see [`Model::has_serial`]);
536    /// false on the 42S. Hosts that bridge the serial line check this
537    /// first.
538    pub fn has_serial(&self) -> bool {
539        self.model.has_serial()
540    }
541
542    /// Queue `bytes` arriving on the serial wire. The UART receives them
543    /// one per 11.375 bit times at the baud rate in #10D, starting now,
544    /// while emulated time runs. Bytes arriving while the port is off
545    /// (IOC SON clear) or looped back (TCS LPB) are lost, as on the real
546    /// line. On a model without a serial port ([`Machine::has_serial`]
547    /// false: the 42S) this does nothing: the bytes are not queued,
548    /// [`Machine::serial_pending`] stays 0 and nothing is ever received.
549    pub fn serial_push(&mut self, bytes: &[u8]) {
550        if self.has_serial() {
551            self.hw.io.uart.push(bytes);
552        }
553    }
554
555    /// The bytes the calculator transmitted since the last drain.
556    pub fn serial_drain(&mut self) -> Vec<u8> {
557        self.hw.io.uart.drain()
558    }
559
560    /// Pushed bytes not yet delivered to the UART's receive register.
561    pub fn serial_pending(&self) -> usize {
562        self.hw.io.uart.pending()
563    }
564
565    /// Drop pushed bytes that have not started on the wire yet, e.g. when
566    /// the host on the other end disconnects; a byte already on the wire
567    /// finishes. Returns how many were dropped.
568    pub fn serial_clear_inbound(&mut self) -> usize {
569        self.hw.io.uart.clear_inbound()
570    }
571
572    /// Whether the calculator's serial port is on (IOC SON): its software
573    /// opened it (a Kermit server, XRECV, `OPENIO`). Bytes arriving while
574    /// it is off are lost.
575    pub fn serial_on(&self) -> bool {
576        self.hw.io.uart.is_on()
577    }
578
579    /// The serial baud rate the calculator selected (#10D).
580    pub fn serial_baud(&self) -> u32 {
581        self.hw.io.uart.baud()
582    }
583
584    /// One step; a shut-down CPU skips at most `budget` cycles (>= 1).
585    fn step_within(&mut self, budget: u64) -> Result<u32, Halt> {
586        if self.shutdown {
587            return Ok(self.sleep(budget));
588        }
589        #[cfg(feature = "profile")]
590        let (p_before, int_before, sel) = (
591            self.cpu.regs.p,
592            self.cpu.regs.in_interrupt,
593            self.hw.select(self.cpu.regs.pc),
594        );
595        let s = self.cpu.step(&mut self.hw);
596        #[cfg(feature = "profile")]
597        self.profile.record(&s, p_before, int_before, sel);
598        let mut halt = None;
599        match s.event {
600            Some(Event::InvalidOpcode { pc, nibbles, len }) => {
601                halt = Some(Halt::InvalidOpcode { pc, nibbles, len });
602            }
603            Some(Event::Shutdown) => {
604                // SHUTDN does not stop the CPU if a wake condition is
605                // already present (wiki: emulators/emu48 SHUTDN). The
606                // OUT = 0 "cold start" case of SASM is not modelled.
607                if !self.wake_condition() {
608                    self.shutdown = true;
609                }
610                // SHUTDN resets the 48GX bank latch (wiki: emulators/emu48
611                // SP23), even when the CPU does not stop; not the 49G's
612                // (see `HardwareProfile::shutdn_clears_latch`).
613                if self.hw.profile().shutdn_clears_latch {
614                    self.hw.clear_latch();
615                }
616            }
617            // RTI re-enters the handler while a level request is held:
618            // ON (wiki: emulators/emu48 SP8, "RTI re-enters at once if ON
619            // is pressed, NINT or NINT2 is low") and the UART's USRQ,
620            // unless the CPU already re-vectored for a pending interrupt.
621            // USRQ is a level (wiki: emulators/emu48 "UART facts"); a
622            // request whose edge vectored into a handler that returned at
623            // once (ST bit 15 clear, RTN without RTI) must come back when
624            // the ROM re-enables interrupts with RSI and RTI, or the
625            // receiver stays full and every later byte overruns (ROM J,
626            // AllowIntr at #010E8-#01113; wiki: hardware/uart "Facts
627            // settled while building saturnus"). Treating USRQ like NINT
628            // here is inferred.
629            Some(Event::Rti)
630                if (self.hw.keyboard.on_pressed() || self.hw.io.uart.irq_level)
631                    && !self.cpu.regs.in_interrupt =>
632            {
633                self.cpu.interrupt();
634            }
635            Some(Event::Rti) | None => {}
636        }
637        // Table cycles, times the model's calibration, times the refresh
638        // stall while the display is on, carrying the fraction.
639        let table = u64::from(s.cycles);
640        // No stall on the 42S: its display RAM is inside the Lewis, and
641        // the 13% is a 48 measurement (inferred; no Lewis figure).
642        let percent = if self.hw.display_on() && self.hw.profile().lewis.is_none() {
643            100 + STALL_PERCENT
644        } else {
645            100
646        };
647        self.stall_acc += table * u64::from(self.model.cycle_scale_permille()) * percent;
648        let cycles = self.stall_acc / TIME_FRACTION;
649        self.stall_acc %= TIME_FRACTION;
650        #[cfg(feature = "profile")]
651        {
652            self.profile.stall_cycles += cycles - table;
653        }
654        self.advance(cycles);
655        match halt {
656            Some(h) => Err(h),
657            None => Ok(u32::try_from(cycles).unwrap_or(u32::MAX)),
658        }
659    }
660
661    /// Anything that ends SHUTDN: a timer with WAKE expired, a key seen on
662    /// the driven rows, ON held, or an undelivered interrupt.
663    fn wake_condition(&self) -> bool {
664        self.hw.io.timers.wake()
665            || self.hw.lewis_slave.timers.wake()
666            || self.hw.read_in_lines() != 0
667            || self.hw.keyboard.on_pressed()
668            || self.on_edge
669            || self.timer_irq
670            || self.key_irq
671            || self.card_irq
672            || self.uart_irq
673            || self.hw.io.module_pulled()
674    }
675
676    /// Shut-down step: wake if a wake condition holds (returns 0, no
677    /// instruction taken), otherwise skip time to the next timer event,
678    /// the next UART event, the end of `budget`, or the next keyboard poll
679    /// while a key is held.
680    fn sleep(&mut self, budget: u64) -> u32 {
681        if self.wake_condition() {
682            self.shutdown = false;
683            self.deliver_interrupts();
684            return 0;
685        }
686        let cycles = self.cycles_until_event().min(budget).max(1);
687        self.advance(cycles);
688        u32::try_from(cycles).unwrap_or(u32::MAX)
689    }
690
691    /// Cycles a shut-down CPU can skip before something may change: the
692    /// next timer event, the next UART event, or the next keyboard poll
693    /// while a key is held. At least 1.
694    fn cycles_until_event(&self) -> u64 {
695        let mut ticks = u64::from(self.hw.io.timers.ticks_until_event())
696            .min(u64::from(self.hw.lewis_slave.timers.ticks_until_event()))
697            .min(MAX_SKIP_TICKS);
698        if self.hw.keyboard.read_in(KEY_IN_MASK) != 0 {
699            ticks = ticks.min(u64::from(SCAN_TICKS));
700        }
701        let mut cycles = self.ticks_to_cycles(ticks.max(1));
702        if let Some(c) = self.hw.io.uart.cycles_until_event(self.model.clock_hz()) {
703            cycles = cycles.min(c);
704        }
705        cycles.max(1)
706    }
707
708    /// While the CPU is shut down with nothing to wake it: the cycles it
709    /// will skip before the next timer or UART event (or keyboard poll
710    /// while a key is held), so a host can sleep for real instead of
711    /// stepping. `None` while the CPU runs or a wake condition holds.
712    pub fn idle_cycles(&self) -> Option<u64> {
713        if self.shutdown && !self.wake_condition() {
714            Some(self.cycles_until_event())
715        } else {
716            None
717        }
718    }
719
720    /// CPU cycles until `ticks` more timer ticks have elapsed (rounded up).
721    fn ticks_to_cycles(&self, ticks: u64) -> u64 {
722        let hz = u64::from(self.model.clock_hz());
723        (ticks * hz)
724            .saturating_sub(self.tick_acc)
725            .div_ceil(TICKS_PER_SECOND)
726    }
727
728    /// Advance time by `c` CPU cycles, then sample the interrupt sources.
729    fn advance(&mut self, c: u64) {
730        let hz = u64::from(self.model.clock_hz());
731        self.cycles = self.cycles.saturating_add(c);
732        self.tick_acc += c * TICKS_PER_SECOND;
733        let mut ticks = self.tick_acc / hz;
734        self.tick_acc %= hz;
735        let elapsed = ticks;
736        self.hw.io.uart.advance(c, self.model.clock_hz());
737        while ticks > 0 {
738            let t = u32::try_from(ticks).unwrap_or(u32::MAX);
739            self.hw.io.tick(t);
740            if self.hw.profile().lewis == Some(LewisBoard::Clamshell) {
741                self.hw.lewis_slave.timers.tick(t);
742            }
743            ticks -= u64::from(t);
744        }
745        if let Some(h) = &mut self.hw.held {
746            h.ticks += elapsed;
747            if h.ticks >= FRAME_TICKS {
748                self.hw.held = None;
749            }
750        }
751        self.poll_interrupts(elapsed);
752    }
753
754    /// Latch interrupt edges after `ticks` timer ticks, and deliver them
755    /// unless the CPU is shut down (then they wake it first).
756    fn poll_interrupts(&mut self, ticks: u64) {
757        // The 28S's two chips share the interrupt line (inferred: the
758        // ROM's handler polls both chips' timer controls).
759        if self.hw.io.timers.take_interrupt() | self.hw.lewis_slave.timers.take_interrupt() {
760            self.timer_irq = true;
761        }
762        if self.hw.io.take_card_interrupt() {
763            self.card_irq = true;
764        }
765        if self.hw.io.uart.take_interrupt() {
766            self.uart_irq = true;
767        }
768        // MP is set whenever NINT is pulled low (wiki: hardware/interrupts).
769        if self.hw.io.module_pulled() {
770            self.cpu.regs.hst |= HST_MP;
771        }
772        // Keyboard poll every ~1 ms; one poll covers a long skip, since
773        // keys only change between steps. Stopped TIMER2 stops the poll
774        // (wiki: emulators/emu48 SP31). The poll is the chip's own scan of
775        // the whole keyboard, not a read of IN through the OUT lines the
776        // ROM drives (wiki: hardware/keyboard "Scanning model", Ervin 2):
777        // a key held while the ROM scans row by row (the Lewis ROMs'
778        // debounce does, every 2 ms) is one key-down, not one per row
779        // change. Seen through OUT, each scan was a new rising edge that
780        // re-entered the keyboard handler, so a held key starved the
781        // ROM's main loop until it was let go (wiki: hardware/hp42s
782        // "Held keys").
783        let acc = u64::from(self.scan_acc) + ticks;
784        if acc >= u64::from(SCAN_TICKS) {
785            self.scan_acc = (acc % u64::from(SCAN_TICKS)) as u32;
786            if self.hw.io.timers.t2_running() {
787                let level = self.hw.keyboard.read_in(KEY_IN_MASK) & self.hw.key_in_mask() != 0;
788                self.hw.io.set_key_down(level);
789                if level && !self.key_level && self.cpu.regs.interrupts_enabled {
790                    self.key_irq = true;
791                }
792                self.key_level = level;
793            }
794        } else {
795            self.scan_acc = acc as u32;
796        }
797        if !self.shutdown {
798            self.deliver_interrupts();
799        }
800    }
801
802    /// Raise one CPU interrupt for all latched sources (the handler polls
803    /// every source itself).
804    fn deliver_interrupts(&mut self) {
805        let any = self.timer_irq || self.on_edge || self.key_irq || self.card_irq || self.uart_irq;
806        self.uart_irq = false;
807        self.timer_irq = false;
808        self.on_edge = false;
809        self.key_irq = false;
810        self.card_irq = false;
811        if any {
812            self.cpu.interrupt();
813        }
814    }
815}
816
817#[cfg(test)]
818mod tests;