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