huc6280/
control.rs

1// SPDX-License-Identifier: MIT
2//! Branches, jumps, calls, returns, the stack, flags, BRK, interrupts and
3//! reset (`_control.py`).
4//!
5//! Vectors (HW HB-12 to HB-18; the reference's start-here.md): RESET `$FFFE`,
6//! NMI `$FFFC`, TIQ `$FFFA`, IRQ1 `$FFF8`, IRQ2 and BRK `$FFF6`, read through
7//! the mapper (after reset MPR7 = 0, so physical `$001FFE`).
8//!
9//! The interrupt design is the reference's docs/handoff-brief.md's: the
10//! frame's `IRQ_LINE` means "an enabled maskable source is asserted";
11//! [`Pins::set_irq_lines`] and the `irq_disable` register (the `$1402`
12//! layout, 1 = disabled) feed it, and the vector is chosen at entry from the
13//! lines in priority order TIQ, IRQ1, IRQ2. The timer and the
14//! `$1402`/`$1403` registers themselves are the board's.
15//!
16//! Differences forced by Rust: the interrupt lines and the disable register
17//! live in [`Pins`] (core.rs), so their methods are `Pins`'s, with
18//! forwarders on the CPU; the reference's `_boundary_interrupt` override
19//! that calls `super()` is `boundary_interrupt` here, called from the
20//! `Part` implementation in cpu.rs, ending in the frame's own; the
21//! reference's `ValueError` for an unknown `irq_poll_cycle` or
22//! `vanished_interrupt` has no counterpart, the modes being enums without
23//! the withdrawn values.
24//!
25//! The two switches' enums, `boundary_interrupt_sequence` and
26//! `maskable_vector` were transcribed anew from the reference's clean rewrite
27//! (huc6280-python `6ce348e`; docs/restart.md); the code they replace was
28//! moved aside unread.
29
30use sixfiveohtwo::frame::{IRQ_LINE, NMI_LATCH, NO_POLL};
31
32use crate::core::{Bus, HuC6280, Pins, B, C, D, I, N, T, V, Z};
33
34pub const VECTOR_RESET: u16 = 0xFFFE;
35pub const VECTOR_NMI: u16 = 0xFFFC;
36pub const VECTOR_TIQ: u16 = 0xFFFA;
37pub const VECTOR_IRQ1: u16 = 0xFFF8;
38pub const VECTOR_IRQ2: u16 = 0xFFF6; // also BRK (U15)
39
40// The three maskable sources, in the layout of $1402/$1403 (pcetech 2.1).
41pub const IRQ2_BIT: u8 = 0x01;
42pub const IRQ1_BIT: u8 = 0x02;
43pub const TIQ_BIT: u8 = 0x04;
44
45/// C18: what an entry does when a source the poll saw has gone by the
46/// boundary (it was acknowledged in the instruction's last cycle). When
47/// nothing is left, the instruction runs instead.
48///
49/// The reference's `vanished_interrupt` keeps `"mesen2"` and `"drop"`; its
50/// `"latched"` was withdrawn in the clean rewrite (it raises `ValueError`
51/// there) and has no variant here.
52#[derive(Clone, Copy, Debug, PartialEq, Eq)]
53pub enum VanishedInterrupt {
54    /// `"mesen2"` (default): IRQ1 and IRQ2 are taken as the poll saw them,
55    /// through their own vectors; the timer is taken only if it is still
56    /// asserted. OBSERVED, provisional: Mesen2 2.1.1 and Mednafen 1.32.1 run
57    /// as closed boxes on the reference's validation/vanish_rom.py cards (a
58    /// timer acknowledged by `STZ $1403`, a VDC interrupt by a status read,
59    /// each in the last cycle) both drop the timer and take IRQ1; no hardware
60    /// result is known. A timer that appears in the last cycle waits for the
61    /// next poll, like any other source (a choice: neither run shows it).
62    Mesen2,
63    /// `"drop"`: only sources the poll saw and that are still asserted are
64    /// taken.
65    Drop,
66}
67
68/// U25: when the boundary samples the lines. Hudson's hardware manual says
69/// only that the inputs "are sampled in the last bus cycle of one
70/// instruction" (HW HB-12), not whether a change during that cycle counts.
71///
72/// The reference's `irq_poll_cycle` keeps `"second_to_last"` and `"last"`;
73/// its `"mednafen"` was withdrawn in the clean rewrite (it raises
74/// `ValueError` there) and has no variant here.
75#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub enum IrqPollCycle {
77    /// `"second_to_last"` (default): the 6502 rule, the lines as they stood
78    /// at the end of the instruction's second-to-last cycle (the frame's
79    /// poll; NESdev for the 6502), which the MAME replays and Covell's spread
80    /// are judged with (the reference's issue 0003).
81    SecondToLast,
82    /// `"last"`: the levels at the boundary, so a line that appears in the
83    /// last cycle is taken there and one that goes is not, every source
84    /// alike. OBSERVED: srg320's HUC6280_CPU run as a closed box under GHDL
85    /// (the reference's validation/vanish_vhdl.py) does exactly this; MAME
86    /// 0.285 also decides at the boundary on the levels then (h6280.cpp,
87    /// BSD-3-Clause, Bryan McPhail: the check after each instruction reads the
88    /// lines' current state).
89    Last,
90}
91
92impl Pins {
93    /// Assert the frame's IRQ_LINE when an enabled maskable source is asserted.
94    pub(crate) fn sync_irq(&mut self) {
95        let asserted = self.lines & !self.irq_disable & 7 != 0;
96        if asserted != (self.frame.requests & IRQ_LINE != 0) {
97            if asserted {
98                self.frame.request_maskable_interrupt();
99            } else {
100                self.frame.clear_maskable_interrupt();
101            }
102        }
103    }
104
105    /// Set the three maskable inputs (levels: they stay until the device
106    /// lets go).
107    ///
108    /// IRQ1 is the VDC's, IRQ2 the HuCard connector's and the CD-ROM's, TIQ
109    /// the timer's (pcetech 2.1). A source masked by `irq_disable` is
110    /// remembered, not taken.
111    pub fn set_irq_lines(&mut self, irq1: bool, irq2: bool, tiq: bool) {
112        let lines = (if irq2 { IRQ2_BIT } else { 0 })
113            | (if irq1 { IRQ1_BIT } else { 0 })
114            | (if tiq { TIQ_BIT } else { 0 });
115        let changed = lines ^ self.lines;
116        if changed == 0 {
117            return;
118        }
119        if let Some(polled_lines) = self.polled_lines {
120            // Between steps after a change the poll missed: what the host
121            // changes now counts for the next boundary, as the frame's request
122            // methods treat polled.
123            self.polled_lines = Some((polled_lines & !changed) | (lines & changed));
124        }
125        self.lines = lines;
126        self.sync_irq();
127        if self.frame.deferred.is_none() {
128            // Learn whether a bus access follows, even when the frame's
129            // IRQ_LINE is unchanged (a source swapped for another): no access
130            // means the change came after the poll.
131            let requests = self.frame.requests;
132            self.frame.request(requests);
133        }
134    }
135
136    /// The (IRQ1, IRQ2, TIQ) levels last set.
137    pub fn irq_lines(&self) -> (bool, bool, bool) {
138        let lines = self.lines;
139        (
140            lines & IRQ1_BIT != 0,
141            lines & IRQ2_BIT != 0,
142            lines & TIQ_BIT != 0,
143        )
144    }
145
146    /// The interrupt disable register's bits 2-0 (IRQ2, IRQ1, TIQ; 1 =
147    /// masked), as `$1402`.
148    pub fn irq_disable(&self) -> u8 {
149        self.irq_disable
150    }
151
152    /// Write the interrupt disable register (bits 2-0 are kept).
153    pub fn set_irq_disable(&mut self, value: u8) {
154        self.irq_disable = value & 7;
155        self.sync_irq();
156    }
157}
158
159impl<B: Bus> HuC6280<B> {
160    // -- branches ----------------------------------------------------------
161
162    fn branch(&mut self, taken: bool) {
163        let offset = self.fetch();
164        if !taken {
165            return;
166        }
167        // A taken branch costs 2 more cycles whatever page it lands in (SW;
168        // pcetech 2.0, U9).
169        self.dummy(self.pc);
170        self.io();
171        self.pc = self.pc.wrapping_add(offset as i8 as u16);
172    }
173
174    /// BPL -- branch if N = 0 (SW SB-28).
175    pub(crate) fn op_bpl(&mut self) {
176        self.branch(self.p & N == 0);
177    }
178
179    /// BMI -- branch if N = 1 (SW SB-26).
180    pub(crate) fn op_bmi(&mut self) {
181        self.branch(self.p & N != 0);
182    }
183
184    /// BVC -- branch if V = 0 (SW SB-32).
185    pub(crate) fn op_bvc(&mut self) {
186        self.branch(self.p & V == 0);
187    }
188
189    /// BVS -- branch if V = 1 (SW SB-33).
190    pub(crate) fn op_bvs(&mut self) {
191        self.branch(self.p & V != 0);
192    }
193
194    /// BCC -- branch if C = 0 (SW SB-22).
195    pub(crate) fn op_bcc(&mut self) {
196        self.branch(self.p & C == 0);
197    }
198
199    /// BCS -- branch if C = 1 (SW SB-23).
200    pub(crate) fn op_bcs(&mut self) {
201        self.branch(self.p & C != 0);
202    }
203
204    /// BNE -- branch if Z = 0 (SW SB-27).
205    pub(crate) fn op_bne(&mut self) {
206        self.branch(self.p & Z == 0);
207    }
208
209    /// BEQ -- branch if Z = 1 (SW SB-24).
210    pub(crate) fn op_beq(&mut self) {
211        self.branch(self.p & Z != 0);
212    }
213
214    /// BRA -- branch always, always 4 cycles (SW SB-29).
215    pub(crate) fn op_bra(&mut self) {
216        let offset = self.fetch();
217        self.io();
218        self.io();
219        self.pc = self.pc.wrapping_add(offset as i8 as u16);
220    }
221
222    // -- jumps, calls, returns ----------------------------------------------
223
224    /// JMP -- abs: AA -> PC (SW SB-51).
225    pub(crate) fn op_jmp_abs(&mut self) {
226        self.pc = self.fetch_word();
227        self.io();
228    }
229
230    fn read_pointer(&mut self, address: u16) -> u16 {
231        // U9: the high byte is at address + 1 even across a page; no NMOS bug
232        // (pcetech 2.0).
233        let low = self.cycle_read(address) as u16;
234        ((self.cycle_read(address.wrapping_add(1)) as u16) << 8) | low
235    }
236
237    /// JMP -- (abs): the pointer's address, then the word there -> PC (SW SB-51).
238    pub(crate) fn op_jmp_ind(&mut self) {
239        let pointer = self.fetch_word();
240        self.io();
241        self.pc = self.read_pointer(pointer);
242        self.io();
243    }
244
245    /// JMP -- (abs,X): the pointer is at abs + X (SW SB-51).
246    pub(crate) fn op_jmp_idx(&mut self) {
247        let pointer = self.fetch_word().wrapping_add(self.x as u16);
248        self.io();
249        self.pc = self.read_pointer(pointer);
250        self.io();
251    }
252
253    /// JSR -- push the address of the operand's last byte, then AA -> PC (SW SB-52).
254    pub(crate) fn op_jsr(&mut self) {
255        let low = self.fetch() as u16;
256        self.io();
257        let pc = self.pc; // the high byte's address, the last byte of JSR (U20)
258        self.push((pc >> 8) as u8);
259        self.push(pc as u8);
260        self.pc = ((self.fetch() as u16) << 8) | low;
261        self.io();
262    }
263
264    /// BSR -- push the address of the offset byte, then PC + offset (8 cycles)
265    /// (SW SB-31).
266    pub(crate) fn op_bsr(&mut self) {
267        let offset = self.fetch();
268        self.io();
269        let pc = self.pc.wrapping_sub(1); // U20: the last byte of BSR
270        self.push((pc >> 8) as u8);
271        self.push(pc as u8);
272        self.io();
273        self.io();
274        self.io();
275        self.pc = self.pc.wrapping_add(offset as i8 as u16);
276    }
277
278    /// RTS -- pull PC, then PC + 1 -> PC (SW SB-71).
279    pub(crate) fn op_rts(&mut self) {
280        self.implied();
281        self.io();
282        let low = self.pull() as u16;
283        let pc = ((self.pull() as u16) << 8) | low;
284        self.io();
285        self.io();
286        self.pc = pc.wrapping_add(1);
287    }
288
289    /// RTI -- pull P, then PC (SW SB-70).
290    pub(crate) fn op_rti(&mut self) {
291        self.implied();
292        self.io();
293        self.p = self.pull() & !B; // U20: P first, then PCL, PCH; B is not stored (U5)
294        let low = self.pull() as u16;
295        self.pc = ((self.pull() as u16) << 8) | low;
296        self.io();
297    }
298
299    // -- the stack ---------------------------------------------------------
300
301    /// PHA -- push A (SW SB-59).
302    pub(crate) fn op_pha(&mut self) {
303        self.implied();
304        self.push(self.a);
305    }
306
307    /// PHP -- push P with B set and T clear (SW SB-60).
308    pub(crate) fn op_php(&mut self) {
309        self.implied();
310        // U5: B reads as 1 in a pushed P. T reads as 0: the fetch cleared it (U4).
311        self.push(self.p | B);
312    }
313
314    /// PHX -- push X (SW SB-61).
315    pub(crate) fn op_phx(&mut self) {
316        self.implied();
317        self.push(self.x);
318    }
319
320    /// PHY -- push Y (SW SB-62).
321    pub(crate) fn op_phy(&mut self) {
322        self.implied();
323        self.push(self.y);
324    }
325
326    fn pull_register(&mut self) -> u8 {
327        self.implied();
328        self.io();
329        self.pull()
330    }
331
332    /// PLA -- pull A (SW SB-63).
333    pub(crate) fn op_pla(&mut self) {
334        let value = self.pull_register();
335        self.a = self.set_nz(value);
336    }
337
338    /// PLX -- pull X (SW SB-65).
339    pub(crate) fn op_plx(&mut self) {
340        let value = self.pull_register();
341        self.x = self.set_nz(value);
342    }
343
344    /// PLY -- pull Y (SW SB-66).
345    pub(crate) fn op_ply(&mut self) {
346        let value = self.pull_register();
347        self.y = self.set_nz(value);
348    }
349
350    /// PLP -- pull P; T can be set from the stack, B is not kept (SW SB-64).
351    pub(crate) fn op_plp(&mut self) {
352        let value = self.pull_register();
353        // U21: the new I counts one instruction late, as on the 6502 (the
354        // frame's polled_i).
355        self.pins.frame.polled_i = Some(self.p & I);
356        self.p = value & !B;
357    }
358
359    // -- flags and NOP -------------------------------------------------------
360
361    /// CLC -- 0 -> C (SW SB-35).
362    pub(crate) fn op_clc(&mut self) {
363        self.implied();
364        self.p &= !C;
365    }
366
367    /// SEC -- 1 -> C (SW SB-75).
368    pub(crate) fn op_sec(&mut self) {
369        self.implied();
370        self.p |= C;
371    }
372
373    /// CLD -- 0 -> D (SW SB-36).
374    pub(crate) fn op_cld(&mut self) {
375        self.implied();
376        self.p &= !D;
377    }
378
379    /// SED -- 1 -> D (SW SB-76).
380    pub(crate) fn op_sed(&mut self) {
381        self.implied();
382        self.p |= D;
383    }
384
385    /// CLV -- 0 -> V (SW SB-38).
386    pub(crate) fn op_clv(&mut self) {
387        self.implied();
388        self.p &= !V;
389    }
390
391    /// CLI -- 0 -> I, after this instruction's interrupt poll (SW SB-37).
392    pub(crate) fn op_cli(&mut self) {
393        self.implied();
394        self.pins.frame.polled_i = Some(self.p & I); // U21
395        self.p &= !I;
396    }
397
398    /// SEI -- 1 -> I, after this instruction's interrupt poll (SW SB-77).
399    pub(crate) fn op_sei(&mut self) {
400        self.implied();
401        self.pins.frame.polled_i = Some(self.p & I); // U21
402        self.p |= I;
403    }
404
405    /// NOP -- no operation; the 22 undefined opcodes are the same (U3) (SW SB-57).
406    pub(crate) fn op_nop(&mut self) {
407        self.implied();
408        if self.pins.opcode == 0x63 {
409            for _ in 2..self.nop_63_cycles {
410                self.io();
411            }
412        }
413    }
414
415    // -- BRK, interrupts, reset ------------------------------------------------
416
417    /// BRK -- push PC + 2 and P with B set, jump through the IRQ2 vector (SW SB-30).
418    pub(crate) fn op_brk(&mut self) {
419        self.fetch(); // C2: the signature byte is skipped, so BRK is two bytes
420        self.interrupt(VECTOR_IRQ2, self.p | B); // U15
421        self.io();
422        // BRK's cycles are those SingleStepTests huc6280 records (emulator
423        // tier); an entry makes the same pushes and vector reads (C3, C8).
424        // Like an entry, BRK does not poll: the handler's first instruction
425        // runs first (the 6502 frame's rule; issue 0005). step() moves this
426        // to polled.
427        self.pins.frame.deferred = Some(NO_POLL);
428    }
429
430    fn interrupt(&mut self, vector: u16, pushed_p: u8) {
431        let pc = self.pc;
432        self.push((pc >> 8) as u8);
433        self.push(pc as u8);
434        self.push(pushed_p);
435        // HW HB-14, pcetech 2.0: the entry sets I and clears D. C16: it also
436        // clears T, so the handler's first instruction runs normally while the
437        // pushed P keeps T (pcetech 2.3). OBSERVED, provisional: Mesen2 and
438        // Mednafen run as closed boxes on a timer taken between SET and its
439        // target (the reference's validation/vanish_rom.py `build_t_entry`)
440        // run the handler's ORA on A; ares (ISC) clears T at entry too.
441        // srg320's VHDL under GHDL dissents: its handler's first ORA works on
442        // zero page (validation/vanish_vhdl.py --t-entry).
443        self.p = (self.p | I) & !(D | T);
444        let low = self.cycle_read(vector) as u16;
445        self.pc = ((self.cycle_read(vector + 1) as u16) << 8) | low;
446    }
447
448    /// Take NMI or the highest-priority enabled maskable source at a boundary.
449    pub(crate) fn enter_interrupt_sequence(&mut self, kind: u8) -> u32 {
450        self.cycles = 0;
451        self.pins.frame.polled_i = None;
452        let vector;
453        if kind == NMI_LATCH {
454            vector = VECTOR_NMI;
455            self.pins.frame.requests &= !NMI_LATCH;
456        } else {
457            match self.maskable_vector() {
458                Some(taken) => vector = taken,
459                None => {
460                    // Nothing is left to enter: the instruction runs instead
461                    // (issue 0002, C18), with the bookkeeping step() does
462                    // after any instruction, so a request changed in its last
463                    // cycle waits for the next poll as it would anywhere else
464                    // (issue 0005).
465                    self.pins.frame.polled = None;
466                    let cycles = self.execute_sequence();
467                    let frame = &mut self.pins.frame;
468                    if let Some(deferred) = frame.deferred.take() {
469                        frame.polled = Some(deferred);
470                    }
471                    return cycles;
472                }
473            }
474        }
475        // Two dummy reads (the opcode and the byte after it, both discarded),
476        // the pushes, the vector, and an internal cycle (C3, C8). OBSERVED,
477        // provisional: Mesen2's read and write callbacks, run as a closed box,
478        // show two reads at PC, PCH, PCL and P pushed, the vector read, then a
479        // cycle with no access before the handler's first fetch. srg320's VHDL
480        // under GHDL takes 9: three reads at PC and an internal cycle before
481        // the pushes (the reference's validation/vanish_vhdl.py --dump).
482        self.dummy(self.pc);
483        self.dummy(self.pc);
484        // U4, U5: P is pushed with B clear and T as it stands, so an
485        // interrupt between SET and its target leaves T set in the pushed
486        // byte and RTI restores it.
487        self.interrupt(vector, self.p & !B);
488        if self.interrupt_entry_cycles >= 8 {
489            self.io();
490        }
491        // An entry does not poll: the handler's first instruction runs before
492        // anything requested since is taken.
493        self.pins.frame.polled = Some(NO_POLL);
494        self.pins.frame.deferred = None;
495        self.cycles
496    }
497
498    /// The interrupt this boundary takes (the frame's hook), with the lines
499    /// it counts.
500    pub(crate) fn boundary_interrupt_sequence(&mut self) -> u8 {
501        let mode = self.irq_poll_cycle;
502        let pins = &mut self.pins;
503        let polled_lines = pins.polled_lines;
504        if mode == IrqPollCycle::SecondToLast {
505            // The frame's poll; the lines it saw are the ones a change in the last cycle left.
506            // They hold until this boundary only (CpuState::polled_irq_lines).
507            pins.poll_lines = polled_lines.unwrap_or(pins.lines);
508            pins.polled_lines = None;
509            return pins.frame.boundary_interrupt(self.p);
510        }
511        // IrqPollCycle::Last (the reference raises ValueError for any other name).
512        pins.poll_lines = pins.lines;
513        pins.polled_lines = None;
514        let frame = &mut pins.frame;
515        let requests = match frame.polled.take() {
516            None => frame.requests,
517            Some(polled) => polled,
518        };
519        if requests & NMI_LATCH != 0 {
520            return NMI_LATCH;
521        }
522        let i_flag = match frame.polled_i.take() {
523            None => self.p & I,
524            // U21: CLI, SEI and PLP still count one instruction late.
525            Some(polled_i) => polled_i,
526        };
527        if pins.lines & !pins.irq_disable & 7 != 0 && i_flag == 0 {
528            return IRQ_LINE;
529        }
530        0
531    }
532
533    /// The vector of the highest-priority source this entry takes, or `None`
534    /// if none is left.
535    fn maskable_vector(&self) -> Option<u16> {
536        let enabled = !self.pins.irq_disable & 7;
537        let seen = self.pins.poll_lines & enabled;
538        let live = self.pins.lines & enabled;
539        let taking = match self.vanished_interrupt {
540            VanishedInterrupt::Mesen2 => (seen & (IRQ1_BIT | IRQ2_BIT)) | (seen & live & TIQ_BIT),
541            VanishedInterrupt::Drop => seen & live,
542        };
543        // Priority TIQ, IRQ1, IRQ2 (HW Fig. 2-4-1).
544        for (bit, vector) in [
545            (TIQ_BIT, VECTOR_TIQ),
546            (IRQ1_BIT, VECTOR_IRQ1),
547            (IRQ2_BIT, VECTOR_IRQ2),
548        ] {
549            if taking & bit != 0 {
550                return Some(vector);
551            }
552        }
553        None
554    }
555
556    /// The start sequence (HW HB-18; U2): MPR7 = 0, I set, D and T clear, low speed.
557    pub(crate) fn reset_sequence(&mut self) -> u32 {
558        self.cycles = 0;
559        self.pins.frame.reset_pending = false;
560        self.pins.frame.polled_i = None;
561        self.mpr[7] = 0;
562        self.p = (self.p | I) & !(D | T | B);
563        self.pins.high_speed = false;
564        self.pins.irq_disable = 0;
565        // No source counts reset's cycles (the reference's docs/timing.md);
566        // the core makes five internal cycles and the two vector reads, an
567        // arbitrary and unobserved choice (C8).
568        for _ in 0..5 {
569            self.io();
570        }
571        let low = self.cycle_read(VECTOR_RESET) as u16;
572        self.pc = ((self.cycle_read(VECTOR_RESET + 1) as u16) << 8) | low;
573        self.pins.sync_irq();
574        self.pins.frame.polled = Some(NO_POLL);
575        self.pins.frame.deferred = None;
576        self.pins.polled_lines = None;
577        self.cycles
578    }
579
580    // -- the interrupt lines (forwarders to Pins) ---------------------------
581
582    /// Set the three maskable inputs ([`Pins::set_irq_lines`]).
583    pub fn set_irq_lines(&mut self, irq1: bool, irq2: bool, tiq: bool) {
584        self.pins.set_irq_lines(irq1, irq2, tiq);
585    }
586
587    /// The (IRQ1, IRQ2, TIQ) levels last set.
588    pub fn irq_lines(&self) -> (bool, bool, bool) {
589        self.pins.irq_lines()
590    }
591
592    /// The interrupt disable register ([`Pins::irq_disable`]).
593    pub fn irq_disable(&self) -> u8 {
594        self.pins.irq_disable
595    }
596
597    /// Write the interrupt disable register ([`Pins::set_irq_disable`]).
598    pub fn set_irq_disable(&mut self, value: u8) {
599        self.pins.set_irq_disable(value);
600    }
601}