huc6280/
core.rs

1// SPDX-License-Identifier: MIT
2//! Registers, the memory mapper, the cycle primitives and the addressing
3//! modes (`_core.py`).
4//!
5//! Every CPU cycle is one bus callback, in the chip's order, internal cycles
6//! and dummy reads included. A cycle is one of four kinds, readable as
7//! [`Pins::kind`] while the callback runs:
8//!
9//! - [`Kind::Read`]: [`Bus::read`]; the opcode fetch is the first cycle.
10//! - [`Kind::Write`][]: [`Bus::write`].
11//! - [`Kind::Dummy`]: [`Bus::idle`] with `Some(address)`; a read the chip
12//!   makes and throws away, at the address given (the byte after the opcode
13//!   for an implied instruction).
14//! - [`Kind::Idle`]: [`Bus::idle`] with `None`; an internal cycle with
15//!   nothing on the bus.
16//!
17//! The bus shapes (which cycle is which, and where the internal cycles sit)
18//! are those SingleStepTests huc6280 records (the reference's docs/timing.md,
19//! "The bus cycles"): MIT test data recorded from Mesen run as a closed box,
20//! **emulator tier** (C8). Hudson's manual gives totals only.
21//!
22//! The addresses the callbacks receive are 21-bit physical addresses: the
23//! mapper is in the core (the reference's docs/handoff-brief.md, "The core
24//! boundary"). Logical addresses are 16-bit; the top three bits pick one of
25//! eight mapping registers (HW HB-7), whose 8-bit value replaces them (U1, HW
26//! HB-3; pcetech 2.0).
27//!
28//! The U and C numbers are the entries of the reference's
29//! docs/undocumented-behavior.md; HW and SW are Hudson's hardware and
30//! software manuals.
31//!
32//! Differences forced by Rust:
33//!
34//! - The reference's host passes three callables and reaches the CPU from
35//!   inside them (`cpu.set_irq_lines`, `cpu.kind`, `cpu.high_speed`). A Rust
36//!   bus callback cannot borrow the CPU that is calling it, so what a
37//!   callback may see or change lives in [`Pins`], which every callback
38//!   receives: the frame (reset, NMI), the three maskable lines and their
39//!   disable register, `high_speed`, the cycle's kind and the opcode.
40//! - The reference's frame swaps its bus callables for confirming wrappers
41//!   when a request changes; here every cycle calls `Frame::access` first,
42//!   which does the same check (6502-rust's difference, inherited), through
43//!   `Pins::access`, which also records the lines as the reference's
44//!   `_confirm` override does.
45//! - The mixins' class attributes (the named switches) are fields of
46//!   [`HuC6280`], the string-valued ones enums.
47//! - A handler that takes a function (`_modify`'s operation) takes a
48//!   `fn(&mut Self, ...)` pointer.
49
50use sixfiveohtwo::frame::Frame;
51
52use crate::alu::DecimalFormula;
53use crate::control::{IrqPollCycle, VanishedInterrupt};
54use crate::hudson::TmaMultiple;
55
56// P (HW HB-4, HB-5). B is never stored: it reads as 1 whenever P is pushed by
57// PHP or BRK and as 0 when an interrupt pushes it (U5), and the corpus never
58// sets it. T is bit 5, the memory-operation flag (U4).
59pub const N: u8 = 0x80;
60pub const V: u8 = 0x40;
61pub const T: u8 = 0x20;
62pub const B: u8 = 0x10;
63pub const D: u8 = 0x08;
64pub const I: u8 = sixfiveohtwo::frame::I; // bit 2 on every part: the frame's
65pub const Z: u8 = 0x02;
66pub const C: u8 = 0x01;
67
68/// Zero page and stack are logical pages $20 and $21, through MPR1 (U1; HW
69/// HB-3: the address bus high byte is $21 for the stack).
70pub const ZERO_PAGE: u16 = 0x2000;
71pub const STACK_PAGE: u16 = 0x2100;
72
73/// A cycle's kind, as [`Pins::kind`] shows it.
74#[derive(Clone, Copy, Debug, PartialEq, Eq)]
75pub enum Kind {
76    Read,
77    Write,
78    Dummy,
79    Idle,
80}
81
82impl Kind {
83    /// The reference's name for the kind (`cpu.kind`).
84    pub const fn as_str(self) -> &'static str {
85        match self {
86            Kind::Read => "read",
87            Kind::Write => "write",
88            Kind::Dummy => "dummy",
89            Kind::Idle => "idle",
90        }
91    }
92}
93
94/// N and Z for an 8-bit result.
95#[inline]
96pub(crate) fn nz(value: u8) -> u8 {
97    (value & N) | if value == 0 { Z } else { 0 }
98}
99
100/// The host's side of the bus: exactly one call per cycle, in the chip's
101/// order, with 21-bit physical addresses.
102///
103/// Each call also gets the CPU's [`Pins`], so a device can change an
104/// interrupt line during the cycle it happens in (the poll then decides
105/// whether that was in time), and read the cycle's kind and the clock speed
106/// it runs at.
107pub trait Bus {
108    fn read(&mut self, address: u32, pins: &mut Pins) -> u8;
109    fn write(&mut self, address: u32, value: u8, pins: &mut Pins);
110    /// A cycle with no data transfer: `Some(address)` is the dummy read the
111    /// chip makes (the byte after the opcode of an implied instruction),
112    /// `None` an internal cycle. The default touches nothing (the
113    /// reference's `_no_idle`).
114    fn idle(&mut self, address: Option<u32>, pins: &mut Pins) {
115        let _ = (address, pins);
116    }
117}
118
119/// What a bus callback can see and change of the CPU while it runs: the
120/// frame's requests (reset, NMI), the three maskable inputs and their
121/// disable register, the clock switch, the cycle's kind and the opcode.
122///
123/// Between steps a board reaches the same things as `cpu.pins`, or through
124/// the methods of [`HuC6280`] that forward here.
125#[derive(Clone, Debug, PartialEq, Eq)]
126pub struct Pins {
127    /// 6502-rust's frame: reset, the NMI latch, and `IRQ_LINE`, which here
128    /// means "an enabled maskable source is asserted" and is kept by
129    /// [`Pins::set_irq_lines`] and [`Pins::set_irq_disable`]: a board does
130    /// not call the frame's `request_maskable_interrupt` itself.
131    pub frame: Frame,
132    /// The clock switch: `false` at 1.79 MHz (12 master clocks a cycle),
133    /// `true` at 7.16 MHz (3). Reset selects low (U10).
134    pub high_speed: bool,
135    pub(crate) kind: Kind,
136    pub(crate) opcode: u8,
137    // The three maskable sources in the layout of $1402/$1403 (control.rs).
138    pub(crate) lines: u8,
139    /// The lines as they stood at the last bus access (kept up to date by
140    /// `Pins::access`): what the poll sees if a line changes in an
141    /// instruction's last cycle.
142    pub(crate) lines_at_access: u8,
143    /// The lines the last instruction's poll saw, set when a line changed
144    /// after it (in the last cycle) and only until the next boundary; `None`
145    /// when the poll saw the lines as they stand.
146    /// `CpuState::polled_irq_lines` (issue 0005).
147    pub(crate) polled_lines: Option<u8>,
148    /// The lines the boundary's interrupt decision counts, per
149    /// `irq_poll_cycle` (U25).
150    pub(crate) poll_lines: u8,
151    pub(crate) irq_disable: u8,
152}
153
154impl Default for Pins {
155    fn default() -> Self {
156        Pins {
157            frame: Frame::default(),
158            high_speed: false,
159            kind: Kind::Idle,
160            opcode: 0,
161            lines: 0,
162            lines_at_access: 0,
163            polled_lines: None,
164            poll_lines: 0,
165            irq_disable: 0,
166        }
167    }
168}
169
170impl Pins {
171    /// Make a bus access: confirm a request change made since the last one
172    /// (`Frame::access`), and record the lines as they stand (the reference's
173    /// `_confirm` override, which sets `_lines_at_access`).
174    ///
175    /// The reference's `_confirm` runs only on the first access after a
176    /// request change; every change of the lines arms it
177    /// ([`Pins::set_irq_lines`]), so recording at every access keeps the same
178    /// value.
179    #[inline]
180    pub(crate) fn access(&mut self) {
181        self.frame.access();
182        self.lines_at_access = self.lines;
183    }
184
185    /// The current cycle's kind.
186    #[inline]
187    pub fn kind(&self) -> Kind {
188        self.kind
189    }
190
191    /// The opcode of the instruction being executed.
192    ///
193    /// It is set once the fetch cycle's read has returned, so every later
194    /// callback of the instruction (operand reads, the write of an
195    /// ST0/ST1/ST2) sees it; the fetch callback itself still sees the
196    /// previous instruction's. An interrupt entry leaves it unchanged.
197    #[inline]
198    pub fn opcode(&self) -> u8 {
199        self.opcode
200    }
201}
202
203/// A Hudson HuC6280 core whose memory and devices are a host's [`Bus`].
204///
205/// `step()` calls the bus once per cycle it returns, in the chip's order.
206/// Registers are plain fields: `a`, `x`, `y`, `s`, `pc` (logical, 16 bits),
207/// `p` (8 bits; B is not stored) and `mpr` (eight 8-bit mapping registers).
208/// The interrupt inputs, their poll and `step()`'s skeleton are 6502-rust's
209/// frame; the three maskable sources come in through
210/// [`Pins::set_irq_lines`] and [`Pins::set_irq_disable`].
211pub struct HuC6280<B: Bus> {
212    pub a: u8,
213    pub x: u8,
214    pub y: u8,
215    pub s: u8,
216    pub pc: u16,
217    pub p: u8,
218    /// MPR0-MPR7, the 8-bit mapping registers (physical A13-A20).
219    pub mpr: [u8; 8],
220    pub bus: B,
221    pub pins: Pins,
222    /// The last value TAM or TMA moved: what TMA with an operand of $00
223    /// returns (U11).
224    pub(crate) mpr_latch: u8,
225    /// T as the instruction fetch found it; the fetch clears it in P (U4).
226    pub(crate) t: u8,
227    pub(crate) cycles: u32,
228
229    // -- the named switches, each with the reference's default ------------
230    /// Named so a board or a later capture can change it: whether a pointer
231    /// at zero-page offset $FF takes its high byte from offset $00 (U8,
232    /// emulator tier: MAME 0.285 h6280.cpp `program_read16z`, BSD-3-Clause,
233    /// Bryan McPhail, wraps within the zero page, and the SingleStepTests
234    /// corpus's cases at $FF pass with it) or from logical $2100.
235    pub zero_page_pointer_wraps: bool,
236    /// C5: whether SBC honours T like ADC (`false`: SW and pcetech list only
237    /// ORA AND EOR ADC).
238    pub sbc_honours_t: bool,
239    /// C13: the decimal digit adjust of ADC and SBC,
240    /// [`DecimalFormula::Mednafen`] (default) or [`DecimalFormula::Mesen`]
241    /// (alu.rs).
242    pub decimal_formula: DecimalFormula,
243    /// C12: what TSB and TRB's Z reports. `false` (default): the stored
244    /// result is zero (pcetech 2.0, "Z = If result is zero"; MAME 0.285
245    /// h6280.cpp `tsb`/`trb`, BSD-3-Clause, Bryan McPhail, does the same).
246    /// `true`: the 65C02's A AND M is zero, which is what the SingleStepTests
247    /// corpus records (emulator tier, its masked cases).
248    pub tsb_z_from_test: bool,
249    /// C9: pcetech says reads of $0800-$17FF return 0 in a block transfer
250    /// (hw-verified); MAME reads the device (the rung 4 replays). `false`
251    /// reads the device like any access.
252    pub block_reads_hardware_page_as_zero: bool,
253    /// C4: pcetech tested opcode $63 as a two-cycle NOP; MAME bills four.
254    /// Emulator-tier knob for a board that wants MAME's count.
255    pub nop_63_cycles: u32,
256    /// C3: an interrupt entry takes 8 cycles: ares (ISC) and Mesen2 run as a
257    /// closed box (its bus log, control.rs); MAME 0.285 takes 7 (h6280.cpp
258    /// `do_interrupt`, BSD-3-Clause). Emulator tier; no manual states it.
259    pub interrupt_entry_cycles: u32,
260    /// C18: what an entry does when a source the poll saw has gone by the
261    /// boundary ([`VanishedInterrupt`]).
262    pub vanished_interrupt: VanishedInterrupt,
263    /// U25: when the boundary samples the interrupt lines ([`IrqPollCycle`]).
264    pub irq_poll_cycle: IrqPollCycle,
265    /// C6: TMA with several mask bits.
266    pub tma_multiple: TmaMultiple,
267}
268
269impl<B: Bus> HuC6280<B> {
270    /// A HuC6280 on `bus`.
271    pub fn new(bus: B) -> Self {
272        HuC6280 {
273            // Power-up values are random on hardware (A X Y S, MPR0-6; U2).
274            // Zero makes traces reproducible; reset sets only what HW HB-18
275            // lists.
276            a: 0,
277            x: 0,
278            y: 0,
279            s: 0xFF,
280            pc: 0,
281            p: I,
282            mpr: [0; 8],
283            bus,
284            pins: Pins::default(),
285            mpr_latch: 0,
286            t: 0,
287            cycles: 0,
288            zero_page_pointer_wraps: true,
289            sbc_honours_t: false,
290            decimal_formula: DecimalFormula::Mednafen,
291            tsb_z_from_test: false,
292            block_reads_hardware_page_as_zero: true,
293            nop_63_cycles: 2,
294            interrupt_entry_cycles: 8,
295            vanished_interrupt: VanishedInterrupt::Mesen2,
296            irq_poll_cycle: IrqPollCycle::SecondToLast,
297            tma_multiple: TmaMultiple::Or,
298        }
299    }
300
301    /// The current cycle's kind ([`Pins::kind`]).
302    pub fn kind(&self) -> Kind {
303        self.pins.kind
304    }
305
306    /// The opcode of the instruction being executed ([`Pins::opcode`]): the
307    /// public accessor the SuperGrafx uses.
308    pub fn opcode(&self) -> u8 {
309        self.pins.opcode
310    }
311
312    /// The clock switch ([`Pins::high_speed`]).
313    pub fn high_speed(&self) -> bool {
314        self.pins.high_speed
315    }
316
317    // -- the mapper -------------------------------------------------------
318
319    /// The 21-bit physical address of a 16-bit logical one (HW HB-7).
320    #[inline]
321    pub fn physical(&self, address: u16) -> u32 {
322        ((self.mpr[(address >> 13) as usize] as u32) << 13) | (address & 0x1FFF) as u32
323    }
324
325    // -- cycles ----------------------------------------------------------
326
327    /// A data or program read at a logical address.
328    #[inline]
329    pub(crate) fn cycle_read(&mut self, address: u16) -> u8 {
330        self.pins.kind = Kind::Read;
331        self.cycles += 1;
332        self.pins.access();
333        let physical = self.physical(address);
334        self.bus.read(physical, &mut self.pins)
335    }
336
337    /// A write at a logical address.
338    #[inline]
339    pub(crate) fn cycle_write(&mut self, address: u16, value: u8) {
340        self.pins.kind = Kind::Write;
341        self.cycles += 1;
342        self.pins.access();
343        let physical = self.physical(address);
344        self.bus.write(physical, value, &mut self.pins);
345    }
346
347    /// A write at a physical address, bypassing the mapper (ST0-ST2, U12).
348    pub(crate) fn cycle_write_physical(&mut self, address: u32, value: u8) {
349        self.pins.kind = Kind::Write;
350        self.cycles += 1;
351        self.pins.access();
352        self.bus.write(address, value, &mut self.pins);
353    }
354
355    /// A read the chip makes and discards, at a logical address (C8).
356    #[inline]
357    pub(crate) fn dummy(&mut self, address: u16) {
358        self.pins.kind = Kind::Dummy;
359        self.cycles += 1;
360        self.pins.access();
361        let physical = self.physical(address);
362        self.bus.idle(Some(physical), &mut self.pins);
363    }
364
365    /// An internal cycle: nothing on the bus (C8).
366    #[inline]
367    pub(crate) fn io(&mut self) {
368        self.pins.kind = Kind::Idle;
369        self.cycles += 1;
370        self.pins.access();
371        self.bus.idle(None, &mut self.pins);
372    }
373
374    /// The dummy read after an opcode that has no operand: PC, the byte after it.
375    #[inline]
376    pub(crate) fn implied(&mut self) {
377        self.dummy(self.pc);
378    }
379
380    /// One operand byte at PC.
381    #[inline]
382    pub(crate) fn fetch(&mut self) -> u8 {
383        let pc = self.pc;
384        self.pc = pc.wrapping_add(1);
385        self.cycle_read(pc)
386    }
387
388    pub(crate) fn fetch_word(&mut self) -> u16 {
389        let low = self.fetch() as u16;
390        ((self.fetch() as u16) << 8) | low
391    }
392
393    // -- operands --------------------------------------------------------
394
395    #[inline]
396    pub(crate) fn load(&mut self, address: u16) -> u8 {
397        self.cycle_read(address)
398    }
399
400    #[inline]
401    pub(crate) fn store(&mut self, address: u16, value: u8) {
402        self.cycle_write(address, value);
403    }
404
405    /// A read-modify-write: read, an internal cycle, write. No dummy write
406    /// (the reference's docs/timing.md).
407    pub(crate) fn modify(&mut self, address: u16, operation: fn(&mut Self, u8) -> u8) {
408        let value = self.cycle_read(address);
409        self.io();
410        let result = operation(self, value);
411        self.cycle_write(address, result);
412    }
413
414    #[inline]
415    pub(crate) fn set_nz(&mut self, value: u8) -> u8 {
416        self.p = (self.p & !(N | Z)) | nz(value);
417        value
418    }
419
420    // -- the stack (logical $2100 + S; S wraps in 8 bits) -----------------
421
422    pub(crate) fn push(&mut self, value: u8) {
423        let s = self.s;
424        self.cycle_write(STACK_PAGE | s as u16, value);
425        self.s = s.wrapping_sub(1);
426    }
427
428    pub(crate) fn pull(&mut self) -> u8 {
429        let s = self.s.wrapping_add(1);
430        self.s = s;
431        self.cycle_read(STACK_PAGE | s as u16)
432    }
433
434    // -- addressing modes -------------------------------------------------
435    // Each makes its addressing cycles and returns the operand's logical
436    // address. Reads, writes and read-modify-writes share one shape: there is
437    // no index cost and no page-crossing cost on this chip (pcetech 2.0, U9).
438
439    /// `#imm`: the operand is the byte at PC; the handler's load is its cycle.
440    pub(crate) fn ea_imm(&mut self) -> u16 {
441        let pc = self.pc;
442        self.pc = pc.wrapping_add(1);
443        pc
444    }
445
446    /// `zp`: logical $2000 + zp (U1), then an internal cycle.
447    pub(crate) fn ea_zp(&mut self) -> u16 {
448        let zp = self.fetch();
449        self.io();
450        ZERO_PAGE | zp as u16
451    }
452
453    /// `zp,X`: the sum wraps within the zero page.
454    pub(crate) fn ea_zpx(&mut self) -> u16 {
455        let zp = self.fetch();
456        self.io();
457        ZERO_PAGE | zp.wrapping_add(self.x) as u16
458    }
459
460    /// `zp,Y` (LDX and STX only).
461    pub(crate) fn ea_zpy(&mut self) -> u16 {
462        let zp = self.fetch();
463        self.io();
464        ZERO_PAGE | zp.wrapping_add(self.y) as u16
465    }
466
467    /// `abs`, then an internal cycle.
468    pub(crate) fn ea_abs(&mut self) -> u16 {
469        let address = self.fetch_word();
470        self.io();
471        address
472    }
473
474    /// `abs,X`: a 16-bit sum, no extra cycle for a page crossing (pcetech 2.0).
475    pub(crate) fn ea_abx(&mut self) -> u16 {
476        let address = self.fetch_word();
477        self.io();
478        address.wrapping_add(self.x as u16)
479    }
480
481    /// `abs,Y`.
482    pub(crate) fn ea_aby(&mut self) -> u16 {
483        let address = self.fetch_word();
484        self.io();
485        address.wrapping_add(self.y as u16)
486    }
487
488    /// A two-byte pointer in the zero page (U8).
489    pub(crate) fn pointer(&mut self, zp: u8) -> u16 {
490        let low = self.cycle_read(ZERO_PAGE | zp as u16) as u16;
491        let high_zp = if self.zero_page_pointer_wraps {
492            zp.wrapping_add(1) as u16
493        } else {
494            zp as u16 + 1
495        };
496        ((self.cycle_read(ZERO_PAGE + high_zp) as u16) << 8) | low
497    }
498
499    /// `(zp,X)`: the index is added before the pointer is read.
500    pub(crate) fn ea_idx(&mut self) -> u16 {
501        let zp = self.fetch();
502        self.io();
503        let pointer = self.pointer(zp.wrapping_add(self.x));
504        self.io();
505        pointer
506    }
507
508    /// `(zp),Y`: the index is added after, 16 bits.
509    pub(crate) fn ea_idy(&mut self) -> u16 {
510        let zp = self.fetch();
511        self.io();
512        let pointer = self.pointer(zp);
513        self.io();
514        pointer.wrapping_add(self.y as u16)
515    }
516
517    /// `(zp)`, the 65C02 addition.
518    pub(crate) fn ea_ind(&mut self) -> u16 {
519        let zp = self.fetch();
520        self.io();
521        let pointer = self.pointer(zp);
522        self.io();
523        pointer
524    }
525}