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        if self.frame.deferred.is_none() && lines != self.lines {
100            self.lines_before = self.lines; // what the poll saw if no access follows (C18)
101        }
102        self.lines = lines;
103        self.sync_irq();
104    }
105
106    /// The (IRQ1, IRQ2, TIQ) levels last set.
107    pub fn irq_lines(&self) -> (bool, bool, bool) {
108        let lines = self.lines;
109        (
110            lines & IRQ1_BIT != 0,
111            lines & IRQ2_BIT != 0,
112            lines & TIQ_BIT != 0,
113        )
114    }
115
116    /// The interrupt disable register's bits 2-0 (IRQ2, IRQ1, TIQ; 1 =
117    /// masked), as `$1402`.
118    pub fn irq_disable(&self) -> u8 {
119        self.irq_disable
120    }
121
122    /// Write the interrupt disable register (bits 2-0 are kept).
123    pub fn set_irq_disable(&mut self, value: u8) {
124        self.irq_disable = value & 7;
125        self.sync_irq();
126    }
127}
128
129impl<B: Bus> HuC6280<B> {
130    // -- branches ----------------------------------------------------------
131
132    fn branch(&mut self, taken: bool) {
133        let offset = self.fetch();
134        if !taken {
135            return;
136        }
137        // A taken branch costs 2 more cycles whatever page it lands in (SW;
138        // pcetech 2.0, U9).
139        self.dummy(self.pc);
140        self.io();
141        self.pc = self.pc.wrapping_add(offset as i8 as u16);
142    }
143
144    /// BPL -- branch if N = 0 (SW SB-28).
145    pub(crate) fn op_bpl(&mut self) {
146        self.branch(self.p & N == 0);
147    }
148
149    /// BMI -- branch if N = 1 (SW SB-26).
150    pub(crate) fn op_bmi(&mut self) {
151        self.branch(self.p & N != 0);
152    }
153
154    /// BVC -- branch if V = 0 (SW SB-32).
155    pub(crate) fn op_bvc(&mut self) {
156        self.branch(self.p & V == 0);
157    }
158
159    /// BVS -- branch if V = 1 (SW SB-33).
160    pub(crate) fn op_bvs(&mut self) {
161        self.branch(self.p & V != 0);
162    }
163
164    /// BCC -- branch if C = 0 (SW SB-22).
165    pub(crate) fn op_bcc(&mut self) {
166        self.branch(self.p & C == 0);
167    }
168
169    /// BCS -- branch if C = 1 (SW SB-23).
170    pub(crate) fn op_bcs(&mut self) {
171        self.branch(self.p & C != 0);
172    }
173
174    /// BNE -- branch if Z = 0 (SW SB-27).
175    pub(crate) fn op_bne(&mut self) {
176        self.branch(self.p & Z == 0);
177    }
178
179    /// BEQ -- branch if Z = 1 (SW SB-24).
180    pub(crate) fn op_beq(&mut self) {
181        self.branch(self.p & Z != 0);
182    }
183
184    /// BRA -- branch always, always 4 cycles (SW SB-29).
185    pub(crate) fn op_bra(&mut self) {
186        let offset = self.fetch();
187        self.io();
188        self.io();
189        self.pc = self.pc.wrapping_add(offset as i8 as u16);
190    }
191
192    // -- jumps, calls, returns ----------------------------------------------
193
194    /// JMP -- abs: AA -> PC (SW SB-51).
195    pub(crate) fn op_jmp_abs(&mut self) {
196        self.pc = self.fetch_word();
197        self.io();
198    }
199
200    fn read_pointer(&mut self, address: u16) -> u16 {
201        // U9: the high byte is at address + 1 even across a page; no NMOS bug
202        // (pcetech 2.0).
203        let low = self.cycle_read(address) as u16;
204        ((self.cycle_read(address.wrapping_add(1)) as u16) << 8) | low
205    }
206
207    /// JMP -- (abs): the pointer's address, then the word there -> PC (SW SB-51).
208    pub(crate) fn op_jmp_ind(&mut self) {
209        let pointer = self.fetch_word();
210        self.io();
211        self.pc = self.read_pointer(pointer);
212        self.io();
213    }
214
215    /// JMP -- (abs,X): the pointer is at abs + X (SW SB-51).
216    pub(crate) fn op_jmp_idx(&mut self) {
217        let pointer = self.fetch_word().wrapping_add(self.x as u16);
218        self.io();
219        self.pc = self.read_pointer(pointer);
220        self.io();
221    }
222
223    /// JSR -- push the address of the operand's last byte, then AA -> PC (SW SB-52).
224    pub(crate) fn op_jsr(&mut self) {
225        let low = self.fetch() as u16;
226        self.io();
227        let pc = self.pc; // the high byte's address, the last byte of JSR (U20)
228        self.push((pc >> 8) as u8);
229        self.push(pc as u8);
230        self.pc = ((self.fetch() as u16) << 8) | low;
231        self.io();
232    }
233
234    /// BSR -- push the address of the offset byte, then PC + offset (8 cycles)
235    /// (SW SB-31).
236    pub(crate) fn op_bsr(&mut self) {
237        let offset = self.fetch();
238        self.io();
239        let pc = self.pc.wrapping_sub(1); // U20: the last byte of BSR
240        self.push((pc >> 8) as u8);
241        self.push(pc as u8);
242        self.io();
243        self.io();
244        self.io();
245        self.pc = self.pc.wrapping_add(offset as i8 as u16);
246    }
247
248    /// RTS -- pull PC, then PC + 1 -> PC (SW SB-71).
249    pub(crate) fn op_rts(&mut self) {
250        self.implied();
251        self.io();
252        let low = self.pull() as u16;
253        let pc = ((self.pull() as u16) << 8) | low;
254        self.io();
255        self.io();
256        self.pc = pc.wrapping_add(1);
257    }
258
259    /// RTI -- pull P, then PC (SW SB-70).
260    pub(crate) fn op_rti(&mut self) {
261        self.implied();
262        self.io();
263        self.p = self.pull() & !B; // U20: P first, then PCL, PCH; B is not stored (U5)
264        let low = self.pull() as u16;
265        self.pc = ((self.pull() as u16) << 8) | low;
266        self.io();
267    }
268
269    // -- the stack ---------------------------------------------------------
270
271    /// PHA -- push A (SW SB-59).
272    pub(crate) fn op_pha(&mut self) {
273        self.implied();
274        self.push(self.a);
275    }
276
277    /// PHP -- push P with B set and T clear (SW SB-60).
278    pub(crate) fn op_php(&mut self) {
279        self.implied();
280        // U5: B reads as 1 in a pushed P. T reads as 0: the fetch cleared it (U4).
281        self.push(self.p | B);
282    }
283
284    /// PHX -- push X (SW SB-61).
285    pub(crate) fn op_phx(&mut self) {
286        self.implied();
287        self.push(self.x);
288    }
289
290    /// PHY -- push Y (SW SB-62).
291    pub(crate) fn op_phy(&mut self) {
292        self.implied();
293        self.push(self.y);
294    }
295
296    fn pull_register(&mut self) -> u8 {
297        self.implied();
298        self.io();
299        self.pull()
300    }
301
302    /// PLA -- pull A (SW SB-63).
303    pub(crate) fn op_pla(&mut self) {
304        let value = self.pull_register();
305        self.a = self.set_nz(value);
306    }
307
308    /// PLX -- pull X (SW SB-65).
309    pub(crate) fn op_plx(&mut self) {
310        let value = self.pull_register();
311        self.x = self.set_nz(value);
312    }
313
314    /// PLY -- pull Y (SW SB-66).
315    pub(crate) fn op_ply(&mut self) {
316        let value = self.pull_register();
317        self.y = self.set_nz(value);
318    }
319
320    /// PLP -- pull P; T can be set from the stack, B is not kept (SW SB-64).
321    pub(crate) fn op_plp(&mut self) {
322        let value = self.pull_register();
323        // U21: the new I counts one instruction late, as on the 6502 (the
324        // frame's polled_i).
325        self.pins.frame.polled_i = Some(self.p & I);
326        self.p = value & !B;
327    }
328
329    // -- flags and NOP -------------------------------------------------------
330
331    /// CLC -- 0 -> C (SW SB-35).
332    pub(crate) fn op_clc(&mut self) {
333        self.implied();
334        self.p &= !C;
335    }
336
337    /// SEC -- 1 -> C (SW SB-75).
338    pub(crate) fn op_sec(&mut self) {
339        self.implied();
340        self.p |= C;
341    }
342
343    /// CLD -- 0 -> D (SW SB-36).
344    pub(crate) fn op_cld(&mut self) {
345        self.implied();
346        self.p &= !D;
347    }
348
349    /// SED -- 1 -> D (SW SB-76).
350    pub(crate) fn op_sed(&mut self) {
351        self.implied();
352        self.p |= D;
353    }
354
355    /// CLV -- 0 -> V (SW SB-38).
356    pub(crate) fn op_clv(&mut self) {
357        self.implied();
358        self.p &= !V;
359    }
360
361    /// CLI -- 0 -> I, after this instruction's interrupt poll (SW SB-37).
362    pub(crate) fn op_cli(&mut self) {
363        self.implied();
364        self.pins.frame.polled_i = Some(self.p & I); // U21
365        self.p &= !I;
366    }
367
368    /// SEI -- 1 -> I, after this instruction's interrupt poll (SW SB-77).
369    pub(crate) fn op_sei(&mut self) {
370        self.implied();
371        self.pins.frame.polled_i = Some(self.p & I); // U21
372        self.p |= I;
373    }
374
375    /// NOP -- no operation; the 22 undefined opcodes are the same (U3) (SW SB-57).
376    pub(crate) fn op_nop(&mut self) {
377        self.implied();
378        if self.pins.opcode == 0x63 {
379            for _ in 2..self.nop_63_cycles {
380                self.io();
381            }
382        }
383    }
384
385    // -- BRK, interrupts, reset ------------------------------------------------
386
387    /// BRK -- push PC + 2 and P with B set, jump through the IRQ2 vector (SW SB-30).
388    pub(crate) fn op_brk(&mut self) {
389        self.fetch(); // C2: the signature byte is skipped, so BRK is two bytes
390        self.interrupt(VECTOR_IRQ2, self.p | B); // U15
391        self.io();
392    }
393
394    fn interrupt(&mut self, vector: u16, pushed_p: u8) {
395        let pc = self.pc;
396        self.push((pc >> 8) as u8);
397        self.push(pc as u8);
398        self.push(pushed_p);
399        // HW HB-14, pcetech 2.0: the entry sets I and clears D, and clears T.
400        self.p = (self.p | I) & !(D | T);
401        let low = self.cycle_read(vector) as u16;
402        self.pc = ((self.cycle_read(vector + 1) as u16) << 8) | low;
403    }
404
405    /// Take NMI or the highest-priority enabled maskable source at a boundary.
406    pub(crate) fn enter_interrupt_sequence(&mut self, kind: u8) -> u32 {
407        self.cycles = 0;
408        self.pins.frame.polled_i = None;
409        let vector;
410        if kind == NMI_LATCH {
411            vector = VECTOR_NMI;
412            self.pins.frame.requests &= !NMI_LATCH;
413        } else {
414            match self.maskable_vector() {
415                Some(taken) => vector = taken,
416                None => {
417                    // Nothing is left to enter: the instruction runs instead
418                    // (issue 0002, C18).
419                    self.pins.frame.polled = None;
420                    self.pins.frame.polled_i = None;
421                    return self.execute_sequence();
422                }
423            }
424        }
425        // Two dummy reads (the opcode and the byte after it, both discarded),
426        // the pushes, the vector, and an internal cycle (Mesen's ProcessIrq;
427        // C3, C8).
428        self.dummy(self.pc);
429        self.dummy(self.pc);
430        // U4, U5: P is pushed with B clear and T as it stands, so an
431        // interrupt between SET and its target leaves T set in the pushed
432        // byte and RTI restores it.
433        self.interrupt(vector, self.p & !B);
434        if self.interrupt_entry_cycles >= 8 {
435            self.io();
436        }
437        // An entry does not poll: the handler's first instruction runs before
438        // anything requested since is taken.
439        self.pins.frame.polled = Some(NO_POLL);
440        self.pins.frame.deferred = None;
441        self.cycles
442    }
443
444    /// The frame's boundary decision, after working out which lines the poll saw.
445    pub(crate) fn boundary_interrupt_sequence(&mut self) -> u8 {
446        let pins = &mut self.pins;
447        // Which lines the poll saw: the requests changed in the last cycle
448        // (after the poll) leave the frame's polled set, and the lines as
449        // they were before that change are lines_before.
450        let deferred = matches!(pins.frame.polled, Some(polled) if polled & NO_POLL == 0);
451        pins.poll_lines = if pins.frame.polled.is_some() {
452            pins.lines_before
453        } else {
454            pins.lines
455        };
456        let mode = self.irq_poll_cycle;
457        if mode != IrqPollCycle::SecondToLast {
458            let seen = match mode {
459                IrqPollCycle::Last => pins.lines,
460                _ => (pins.poll_lines & !TIQ_BIT) | (pins.lines & TIQ_BIT),
461            };
462            pins.poll_lines = seen;
463            if deferred {
464                // The frame kept the requests from before the last cycle; the
465                // mode counts the levels at the boundary instead.
466                let asserted = if seen & !pins.irq_disable & 7 != 0 {
467                    IRQ_LINE
468                } else {
469                    0
470                };
471                pins.frame.polled = pins
472                    .frame
473                    .polled
474                    .map(|polled| (polled & !IRQ_LINE) | asserted);
475            }
476        }
477        let p = self.p;
478        self.pins.frame.boundary_interrupt(p)
479    }
480
481    /// The vector of the highest-priority source the entry takes (HW HB-13),
482    /// or `None` to drop.
483    fn maskable_vector(&self) -> Option<u16> {
484        let pins = &self.pins;
485        let enabled = !pins.irq_disable & 7;
486        let polled = pins.poll_lines & enabled;
487        let live = pins.lines & enabled;
488        let pending = match self.vanished_interrupt {
489            VanishedInterrupt::Mesen2 => (polled & !TIQ_BIT) | (polled & live & TIQ_BIT),
490            VanishedInterrupt::Drop => {
491                if live != 0 {
492                    polled
493                } else {
494                    0
495                }
496            }
497            VanishedInterrupt::Latched => polled,
498        };
499        if pending & TIQ_BIT != 0 {
500            return Some(VECTOR_TIQ);
501        }
502        if pending & IRQ1_BIT != 0 {
503            return Some(VECTOR_IRQ1);
504        }
505        if pending & IRQ2_BIT != 0 {
506            return Some(VECTOR_IRQ2);
507        }
508        None
509    }
510
511    /// The start sequence (HW HB-18; U2): MPR7 = 0, I set, D and T clear, low speed.
512    pub(crate) fn reset_sequence(&mut self) -> u32 {
513        self.cycles = 0;
514        self.pins.frame.reset_pending = false;
515        self.pins.frame.polled_i = None;
516        self.mpr[7] = 0;
517        self.p = (self.p | I) & !(D | T | B);
518        self.pins.high_speed = false;
519        self.pins.irq_disable = 0;
520        // No source counts reset's cycles (the reference's docs/timing.md);
521        // the core makes five internal cycles and the two vector reads, an
522        // arbitrary and unobserved choice (C8).
523        for _ in 0..5 {
524            self.io();
525        }
526        let low = self.cycle_read(VECTOR_RESET) as u16;
527        self.pc = ((self.cycle_read(VECTOR_RESET + 1) as u16) << 8) | low;
528        self.pins.sync_irq();
529        self.pins.frame.polled = Some(NO_POLL);
530        self.pins.frame.deferred = None;
531        self.cycles
532    }
533
534    // -- the interrupt lines (forwarders to Pins) ---------------------------
535
536    /// Set the three maskable inputs ([`Pins::set_irq_lines`]).
537    pub fn set_irq_lines(&mut self, irq1: bool, irq2: bool, tiq: bool) {
538        self.pins.set_irq_lines(irq1, irq2, tiq);
539    }
540
541    /// The (IRQ1, IRQ2, TIQ) levels last set.
542    pub fn irq_lines(&self) -> (bool, bool, bool) {
543        self.pins.irq_lines()
544    }
545
546    /// The interrupt disable register ([`Pins::irq_disable`]).
547    pub fn irq_disable(&self) -> u8 {
548        self.pins.irq_disable
549    }
550
551    /// Write the interrupt disable register ([`Pins::set_irq_disable`]).
552    pub fn set_irq_disable(&mut self, value: u8) {
553        self.pins.set_irq_disable(value);
554    }
555}