huc6280/
core.rs

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