huc6280/
control.rs

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