Skip to main content

rustyn64_cpu/
cop0.rs

1//! COP0 — the VR4300 system control coprocessor (T-12-001).
2//!
3//! The register file only: widths, writable-bit masks, and the four access
4//! instructions. The *behavior* the registers drive — exception dispatch
5//! (T-12-002), interrupts (T-12-003), address translation (T-12-004) — reads
6//! this module rather than living in it.
7//!
8//! # Why this is table-driven
9//!
10//! Almost every accuracy rule here is of the form "register N is 64 bits wide"
11//! or "bits 23:16 of `Config` are hardwired to `0b00000110`". Those are *data*.
12//! Written as data they can be asserted directly against the manual, one test
13//! per table; written as `match` arms they become 32 places to forget one.
14//!
15//! Two rules in particular cannot be derived and must simply be right:
16//!
17//! - **Which eight registers are 64 bits wide** ([`WIDE`]). There is no pattern.
18//!   Getting one wrong is invisible until 64-bit software runs, and then
19//!   presents as a truncated address rather than as a register bug.
20//! - **Which bits accept writes** ([`WRITE_MASK`]). Hardware silently discards
21//!   the rest; software reads back what it wrote *minus those bits*, and a
22//!   too-permissive mask makes an emulator pass tests real hardware fails.
23//!
24//! # Reset state
25//!
26//! UM §6.4.4 (p. 183) defines only a handful of fields at cold reset and calls
27//! the rest **undefined**: `Index`, `EntryHi`/`EntryLo*`/`PageMask`, `LLAddr`,
28//! `TagLo`/`TagHi`, `WatchLo`/`WatchHi`, and most of `Status`. Undefined is not
29//! license to be non-deterministic — ADR 0004 requires a reproducible machine —
30//! so undefined fields are a documented zero, not entropy.
31
32use crate::decode::Decoded;
33use serde::{Deserialize, Serialize};
34
35/// COP0 register numbers, by name.
36///
37/// Named constants rather than an enum: the encoding carries a raw 5-bit field
38/// and every value 0..=31 is expressible, so an enum would need a fallible
39/// conversion on the hot path for no benefit.
40pub mod reg {
41    /// TLB entry index for `TLBR`/`TLBWI`.
42    pub const INDEX: u8 = 0;
43    /// Free-running TLB replacement counter.
44    pub const RANDOM: u8 = 1;
45    /// Even-page TLB entry.
46    pub const ENTRY_LO0: u8 = 2;
47    /// Odd-page TLB entry.
48    pub const ENTRY_LO1: u8 = 3;
49    /// Page-table base plus the faulting VPN2 (32-bit refill).
50    pub const CONTEXT: u8 = 4;
51    /// TLB page-size mask.
52    pub const PAGE_MASK: u8 = 5;
53    /// Number of wired (unreplaceable) TLB entries.
54    pub const WIRED: u8 = 6;
55    /// Faulting virtual address.
56    pub const BAD_VADDR: u8 = 8;
57    /// Free-running cycle counter, incrementing at half `PClock`.
58    pub const COUNT: u8 = 9;
59    /// TLB VPN2 + ASID.
60    pub const ENTRY_HI: u8 = 10;
61    /// Timer-interrupt comparand.
62    pub const COMPARE: u8 = 11;
63    /// Processor status and mode.
64    pub const STATUS: u8 = 12;
65    /// Exception cause.
66    pub const CAUSE: u8 = 13;
67    /// Exception program counter.
68    pub const EPC: u8 = 14;
69    /// Processor revision identifier.
70    pub const PRID: u8 = 15;
71    /// Cache and endianness configuration.
72    pub const CONFIG: u8 = 16;
73    /// Physical address of the last `LL` (diagnostic only).
74    pub const LL_ADDR: u8 = 17;
75    /// Watchpoint address, low.
76    pub const WATCH_LO: u8 = 18;
77    /// Watchpoint address, high.
78    pub const WATCH_HI: u8 = 19;
79    /// Page-table base plus the faulting VPN2 (64-bit refill).
80    pub const XCONTEXT: u8 = 20;
81    /// Parity error (VR4200 compatibility; unused by VR4300 hardware).
82    pub const PERR: u8 = 26;
83    /// Cache error (VR4200 compatibility; unused by VR4300 hardware).
84    pub const CACHE_ERR: u8 = 27;
85    /// Primary cache tag, low.
86    pub const TAG_LO: u8 = 28;
87    /// Primary cache tag, high.
88    pub const TAG_HI: u8 = 29;
89    /// Error exception program counter.
90    pub const ERROR_EPC: u8 = 30;
91}
92
93/// The eight registers that are **64 bits wide**; the other 24 are 32-bit.
94///
95/// A bitmask indexed by register number. From UM Table 1-2 (p. 46) and the
96/// individual register figures in §5.4 and §6.3:
97/// `EntryLo0`, `EntryLo1`, `Context`, `BadVAddr`, `EntryHi`, `EPC`, `XContext`,
98/// `ErrorEPC`.
99///
100/// There is no rule generating this list — it is exactly the registers that hold
101/// an address or a TLB entry. Pinned by `the_eight_wide_registers_are_exactly_these`.
102pub const WIDE: u32 = (1 << reg::ENTRY_LO0)
103    | (1 << reg::ENTRY_LO1)
104    | (1 << reg::CONTEXT)
105    | (1 << reg::BAD_VADDR)
106    | (1 << reg::ENTRY_HI)
107    | (1 << reg::EPC)
108    | (1 << reg::XCONTEXT)
109    | (1 << reg::ERROR_EPC);
110
111/// Is register `n` 64 bits wide?
112#[must_use]
113pub const fn is_wide(n: u8) -> bool {
114    WIDE & (1 << (n & 31)) != 0
115}
116
117/// `Config` bits 23:16, hardwired to `0b00000110` (UM Fig. 5-16, p. 152).
118const CONFIG_HARDWIRED_HI: u64 = 0b0000_0110 << 16;
119/// `Config` bits 14:4, hardwired to `0b110_0100_0110` (UM Fig. 5-16, p. 152).
120const CONFIG_HARDWIRED_LO: u64 = 0b110_0100_0110 << 4;
121
122/// Per-register writable-bit masks. A `0` bit is hardwired, reserved, or
123/// hardware-owned, and a write to it is discarded.
124///
125/// Every entry is a direct transcription of a register figure. Where a register
126/// is entirely read-only the mask is `0`, which makes "read-only" the same
127/// mechanism as "reserved bit" rather than a separate code path.
128pub const WRITE_MASK: [u64; 32] = {
129    let mut m = [0u64; 32];
130    // Index: P (31) + Index (5:0). Bit 5 is writable but ignored by a 32-entry
131    // TLB -- the manual keeps it, so we keep it (UM Fig. 5-11, p. 146).
132    m[reg::INDEX as usize] = 0x8000_003F;
133    // Random is READ-ONLY (UM §5.4.2, p. 147).
134    m[reg::RANDOM as usize] = 0;
135    // EntryLo0/1: PFN (25:6) | C (5:3) | D (2) | V (1) | G (0) accounts for
136    // bits 25:0 — but the register is writable up to bit **29**, and the top
137    // four bits read back exactly as written.
138    //
139    // Measured, not derived: n64-systemtest writes `0x0F000000` and expects it
140    // back verbatim, and its expectation for every value is `v & 0x3FFF_FFFF`
141    // (`tests/tlb/mod.rs`). Masking at the architectural field width instead
142    // silently dropped bits 29:26 on write-back.
143    m[reg::ENTRY_LO0 as usize] = 0x3FFF_FFFF;
144    m[reg::ENTRY_LO1 as usize] = 0x3FFF_FFFF;
145    // Context: only PTEBase (63:23) is software-writable; BadVPN2 (22:4) is
146    // written by hardware on a TLB exception and 3:0 are always zero.
147    m[reg::CONTEXT as usize] = 0xFFFF_FFFF_FF80_0000;
148    // PageMask: MASK (24:13).
149    m[reg::PAGE_MASK as usize] = 0x01FF_E000;
150    m[reg::WIRED as usize] = 0x3F;
151    // BadVAddr is READ-ONLY (UM §6.3.2, p. 164).
152    m[reg::BAD_VADDR as usize] = 0;
153    m[reg::COUNT as usize] = 0xFFFF_FFFF;
154    // EntryHi: R (63:62) | VPN2 (39:13) | ASID (7:0). Fill (61:40) is
155    // write-ignored and reads zero (UM Fig. 5-10, p. 144).
156    m[reg::ENTRY_HI as usize] = 0xC000_00FF_FFFF_E0FF;
157    m[reg::COMPARE as usize] = 0xFFFF_FFFF;
158    // Status: everything except DS.TS (21), which is read-only, and bits 23 and
159    // 19, which are hardwired zero (UM Fig. 6-6, p. 167).
160    m[reg::STATUS as usize] = 0xFFFF_FFFF & !(1 << 21) & !(1 << 23) & !(1 << 19);
161    // Cause: READ-ONLY except the two software interrupt bits IP1:IP0 (9:8)
162    // (UM §6.3.6, p. 171). This is the mask that is most tempting to widen.
163    m[reg::CAUSE as usize] = 0x0000_0300;
164    m[reg::EPC as usize] = u64::MAX;
165    // PRId is READ-ONLY.
166    m[reg::PRID as usize] = 0;
167    // Config: EP (27:24) | BE (15) | CU (3) | K0 (2:0). EC (30:28) is read-only,
168    // sampled from the `DivMode` pins.
169    m[reg::CONFIG as usize] = 0x0F00_0000 | (1 << 15) | (1 << 3) | 0b111;
170    m[reg::LL_ADDR as usize] = 0xFFFF_FFFF;
171    // WatchLo: PAddr0 (31:3) | R (1) | W (0). Bit 2 is zero.
172    m[reg::WATCH_LO as usize] = 0xFFFF_FFFB;
173    // WatchHi: PAddr1 (3:0). Readable, but "the value in this area is invalid"
174    // on the VR4300, whose physical addresses are only 32 bits.
175    m[reg::WATCH_HI as usize] = 0xF;
176    // XContext: only PTEBase (63:33). R (32:31) and BadVPN2 (30:4) are
177    // hardware-written.
178    m[reg::XCONTEXT as usize] = 0xFFFF_FFFE_0000_0000;
179    // PErr: Diagnostic (7:0). Defined for VR4200 compatibility; the VR4300's
180    // hardware never uses it.
181    m[reg::PERR as usize] = 0xFF;
182    // CacheErr is READ-ONLY and reads as zero -- same compatibility story.
183    m[reg::CACHE_ERR as usize] = 0;
184    // TagLo: PTagLo (27:8) | PState (7:6).
185    m[reg::TAG_LO as usize] = 0x0FFF_FFC0;
186    // TagHi is 32 bits of reserved zero.
187    m[reg::TAG_HI as usize] = 0;
188    m[reg::ERROR_EPC as usize] = u64::MAX;
189    // Registers 7, 21..=25 and 31 are "Reserved for future use" (UM Table 1-2,
190    // p. 46) and stay 0 -- see `Cop0::write` for why that is a guess, not a fact.
191    m
192};
193
194/// Per-register **architecturally-defined** bits — everything a read can ever
195/// return non-zero.
196///
197/// Distinct from [`WRITE_MASK`], and the difference is the point: a read-only
198/// register like `BadVAddr` has a write mask of `0` and an arch mask of all-ones,
199/// while `Cause` has a two-bit write mask and a wide arch mask. Reserved bits and
200/// bits above a 32-bit register's width appear in neither.
201///
202/// Applied on **both** read and [`Cop0::set_hardware`], so a value that is not
203/// architecturally representable cannot enter the file in the first place, let
204/// alone leave it. Enforcing only on read would leave the stored state carrying
205/// bits no hardware register can hold, which the next reader of `regs` would
206/// have to know about.
207///
208/// `Config` is absent from this table: its readable value is *composed* rather
209/// than masked, and [`Cop0::read`] handles it separately.
210pub const ARCH_MASK: [u64; 32] = {
211    let mut m = [0u64; 32];
212    m[reg::INDEX as usize] = 0x8000_003F;
213    m[reg::RANDOM as usize] = 0x3F;
214    m[reg::ENTRY_LO0 as usize] = 0x3FFF_FFFF;
215    m[reg::ENTRY_LO1 as usize] = 0x3FFF_FFFF;
216    // PTEBase (63:23) | BadVPN2 (22:4); bits 3:0 are always zero.
217    m[reg::CONTEXT as usize] = 0xFFFF_FFFF_FFFF_FFF0;
218    m[reg::PAGE_MASK as usize] = 0x01FF_E000;
219    m[reg::WIRED as usize] = 0x3F;
220    // A full 64-bit virtual address.
221    m[reg::BAD_VADDR as usize] = u64::MAX;
222    m[reg::COUNT as usize] = 0xFFFF_FFFF;
223    // R (63:62) | VPN2 (39:13) | ASID (7:0). Fill (61:40) reads ZERO, which is
224    // why it is absent here rather than merely unwritable.
225    m[reg::ENTRY_HI as usize] = 0xC000_00FF_FFFF_E0FF;
226    m[reg::COMPARE as usize] = 0xFFFF_FFFF;
227    m[reg::STATUS as usize] = 0xFFFF_FFFF & !(1 << 23) & !(1 << 19);
228    // BD (31) | CE (29:28) | IP (15:8) | ExcCode (6:2). Far wider than the
229    // two-bit WRITE_MASK, because hardware writes most of it.
230    m[reg::CAUSE as usize] = 0xB000_FF7C;
231    m[reg::EPC as usize] = u64::MAX;
232    // Imp (15:8) | Rev (7:0); bits 31:16 read zero.
233    m[reg::PRID as usize] = 0xFFFF;
234    m[reg::LL_ADDR as usize] = 0xFFFF_FFFF;
235    m[reg::WATCH_LO as usize] = 0xFFFF_FFFB;
236    m[reg::WATCH_HI as usize] = 0xF;
237    // PTEBase (63:33) | R (32:31) | BadVPN2 (30:4); bits 3:0 always zero.
238    m[reg::XCONTEXT as usize] = 0xFFFF_FFFF_FFFF_FFF0;
239    // Config's READ value is composed rather than masked (see `Cop0::read`), but
240    // it still needs an entry: without one, `set_hardware` would mask it to zero.
241    // These are its non-hardwired bits: EP (27:24) | BE (15) | CU (3) | K0 (2:0).
242    m[reg::CONFIG as usize] = 0x0F00_800F;
243    m[reg::PERR as usize] = 0xFF;
244    // CacheErr, TagHi and the reserved registers read as zero.
245    m[reg::TAG_LO as usize] = 0x0FFF_FFC0;
246    m[reg::ERROR_EPC as usize] = u64::MAX;
247    m
248};
249
250/// The VR4300 system control coprocessor register file.
251#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
252pub struct Cop0 {
253    /// Raw register storage. Prefer [`Cop0::read`] / [`Cop0::write`]: they apply
254    /// the width and writable-bit rules that make the values architectural.
255    ///
256    /// `Config`'s hardwired fields are **not** stored here — they are merged in
257    /// on read, so no write path can erase them.
258    regs: [u64; 32],
259    /// The current `Count` timeline position, supplied by the scheduler.
260    ///
261    /// ADR 0006: `master_ticks` is the only incremented counter, and every other
262    /// cycle position is **derived** from it. `Count` is therefore not stored
263    /// and not incremented here — it is computed from this timeline plus an
264    /// epoch, so that a `+= 1` on `Count` never exists to drift.
265    now: u64,
266    /// `Count`'s value at its epoch, set by the last `MTC0 Count`.
267    count_epoch_value: u32,
268    /// The timeline position at that epoch.
269    ///
270    /// Together these make `Count` **affine**: guest-writable (so it needs an
271    /// offset) while still derived (so it cannot drift from the master clock).
272    count_epoch_tick: u64,
273    /// The `Count` value seen at the previous [`Cop0::timer_edge`] poll, so the
274    /// timer can fire on the transition into `Count == Compare` rather than
275    /// whenever the equality happens to hold. See `timer_edge`.
276    last_count: u32,
277
278    /// `Config.EC`, the PClock:MasterClock ratio, sampled from the `DivMode` pins
279    /// at reset and read-only thereafter.
280    ///
281    /// Held apart from `regs` precisely because it is not writable: keeping it
282    /// in the array would need a mask exception that a later edit could relax.
283    ec: u8,
284
285    /// The value of the most recent write to **any** COP0 register.
286    ///
287    /// The seven unused register numbers (7, 21..=25, 31) are not storage: they
288    /// read back this shared latch. So writing reg 7 and reading it returns
289    /// what was written — until *any other* COP0 write intervenes, after which
290    /// reg 7 reads that value instead. See [`Cop0::UNUSED`].
291    write_latch: u64,
292}
293
294impl Default for Cop0 {
295    fn default() -> Self {
296        Self::new()
297    }
298}
299
300impl Cop0 {
301    /// Cold-reset state (UM §6.4.4, p. 183; Fig. 6-16, p. 205).
302    ///
303    /// Defined by the manual: `Status.ERL` and `Status.BEV` set, `Status.TS`/
304    /// `SR`/`RP` clear, `Config.BE` set, `Config.EP` clear, `Random` = 31,
305    /// `Wired` = 0. Everything else the manual calls **undefined**, and is a
306    /// deterministic zero here (ADR 0004).
307    #[must_use]
308    pub const fn new() -> Self {
309        let mut regs = [0u64; 32];
310        // ERL (2) and BEV (22) set; TS/SR/RP already clear.
311        regs[reg::STATUS as usize] = (1 << 2) | (1 << 22);
312        // "Random is set to 31 on Cold Reset" (UM §5.4.2, p. 147).
313        regs[reg::RANDOM as usize] = 31;
314        // BE (15) set: the N64 is big-endian. K0 defaults to 0 (uncached); IPL3
315        // writes 3 during boot, which is where 0x0006E463 comes from.
316        regs[reg::CONFIG as usize] = 1 << 15;
317        // Imp = 0x0B for the VR4300 series (UM §5.4.5, p. 151), Rev = 0x22.
318        //
319        // This comment previously said the Rev field was "NOT documented for any
320        // specific part" and left it zero. That was true of the User's Manual and
321        // false of the N64brew wiki, which this project mirrors and treats as a
322        // primary hardware reference: *"retail N64 units have so far been found
323        // to report either 0x10 (1.0, early units) or 0x22 (2.2, later units),
324        // and the iQue Player reports 0x40"* (`n64brew_wiki/markdown/VR4300.md`).
325        // Ledger U-3 is superseded by C-22 -- "undocumented" is a claim about a
326        // document, and it decays.
327        //
328        // 0x22 is the later stepping, which is what `fpu::Stepping::Fixed` (the
329        // default) denotes. The two want to be selected together by a future
330        // console-revision constructor; wiring that now, with nothing able to
331        // choose `Early`, would be inert API.
332        regs[reg::PRID as usize] = 0x0B22;
333        Self {
334            regs,
335            now: 0,
336            count_epoch_value: 0,
337            count_epoch_tick: 0,
338            // Equal to the reset `Count`, so power-on is not a transition into
339            // `Count == Compare` even though both reset to zero. See
340            // `Cop0::timer_edge`.
341            last_count: 0,
342            // 0b111 = 1:1.5, which matches the N64's 62.5 MHz : 93.75 MHz and is
343            // "allowed with the 100 MHz model only" (UM Appendix A note 1,
344            // p. 628). The manual never names the N64, so this is an INFERENCE
345            // -- accuracy ledger U-6, not a documented fact.
346            ec: 0b111,
347            // Power-on value of the shared unused-register latch. The manual
348            // does not define one; ADR 0004 requires reproducibility, so it is
349            // a documented zero.
350            write_latch: 0,
351        }
352    }
353
354    /// Advance the `Count` timeline to `now` (the scheduler's `count_ticks`).
355    ///
356    /// Called once per CPU step. Note this **sets** rather than increments: the
357    /// position is derived, so a dropped or repeated call cannot desynchronize
358    /// it from the master clock the way an increment would.
359    pub const fn set_now(&mut self, now: u64) {
360        self.now = now;
361    }
362
363    /// The current `Count` timeline position.
364    #[must_use]
365    pub const fn count_now(&self) -> u64 {
366        self.now
367    }
368
369    /// `Count`, computed rather than stored.
370    #[must_use]
371    pub const fn count(&self) -> u32 {
372        self.count_epoch_value
373            .wrapping_add((self.now.wrapping_sub(self.count_epoch_tick)) as u32)
374    }
375
376    /// Has the timer fired — `Count == Compare`?
377    ///
378    /// UM §6.3.4 (p. 165). The comparison is on the *computed* `Count`, so it
379    /// stays true regardless of how the timeline was reached.
380    #[must_use]
381    pub const fn timer_matches(&self) -> bool {
382        self.count() == self.regs[reg::COMPARE as usize] as u32
383    }
384
385    /// Has the timer *just* reached `Compare` — the rising edge of the match?
386    ///
387    /// # Why the edge and not the equality
388    ///
389    /// Both `Count` and `Compare` reset to **zero**, so a plain
390    /// [`Cop0::timer_matches`] is true on the very first step and latches `IP7`
391    /// before a single instruction retires. n64-systemtest catches this exactly:
392    /// it reads `Cause` during an `AdEL` exception and expects `0x10`, while a
393    /// spuriously-latched `IP7` (bit 15) makes it `0x8010`.
394    ///
395    /// The timer fires when `Count` *becomes* equal to `Compare`, which is once
396    /// per wrap of the 32-bit counter, not continuously while they happen to be
397    /// equal. Tracking the previous value is what distinguishes the two, and at
398    /// power-on there is no transition into equality — the two simply start
399    /// there.
400    ///
401    /// # Why this asks whether `Compare` was *crossed*, not whether it is *hit*
402    ///
403    /// `Count` is derived from the master clock, so it keeps advancing while the
404    /// pipeline is stalled — this poll is not guaranteed to land on every value
405    /// the counter takes. An instantaneous `now == Compare` test therefore misses
406    /// the match whenever the gap between two polls steps over it, and a
407    /// 69-PCycle multiply interlock (UM Table 3-12) steps over it comfortably.
408    /// The failure that produces is not a *late* interrupt but a **lost** one:
409    /// `IP7` never latches, and software waiting on the timer hangs forever.
410    ///
411    /// So the question is whether `Compare` lies in the half-open interval
412    /// `(last_count, now]`, in wrapping arithmetic so a counter wrap is just
413    /// another interval. Excluding `last_count` itself preserves the edge
414    /// semantics above: sitting *on* `Compare` is not a transition into it.
415    pub const fn timer_edge(&mut self) -> bool {
416        let now = self.count();
417        let compare = self.regs[reg::COMPARE as usize] as u32;
418        // Distance traveled since the last poll, and the distance to `Compare`,
419        // both measured forward from `last_count`. `Compare` was crossed iff it
420        // is no further away than we traveled — and is not where we started.
421        let traveled = now.wrapping_sub(self.last_count);
422        let to_compare = compare.wrapping_sub(self.last_count);
423        let edge = traveled != 0 && to_compare != 0 && to_compare <= traveled;
424        self.last_count = now;
425        edge
426    }
427
428    /// Advance `Random` by `n` ticks in constant time.
429    ///
430    /// Equivalent to calling [`Cop0::tick_random`] `n` times, and pinned to it
431    /// exhaustively by `tick_random_by_matches_the_loop_everywhere`. The scheduler's
432    /// idle batch needs this: `n` there is a whole stretch of idle pairs, and a
433    /// loop over it put the per-pair cost back that the batch exists to remove.
434    ///
435    /// **The wrap is at `Wired`, not at zero** (UM §6.3.3), so `random - n` is
436    /// wrong — and wrong precisely when `n` is large enough for the batch to be
437    /// worth having. `Random` walks down to `Wired` and then jumps to 31, so the
438    /// sequence is a *transient* followed by a cycle:
439    ///
440    /// * `d` ticks to walk from `cur` down to `Wired`, then
441    /// * a cycle of `31 ..= Wired` re-entered from 31, of length `(31 - Wired) + 1`.
442    ///
443    /// Both distances are taken modulo 64 rather than assumed in range, because
444    /// `Wired` and `Random` are masked to 6 bits on write: `Wired > 31` and
445    /// `cur < Wired` are both reachable from guest code, and each produces a
446    /// longer walk rather than an error. Assuming `Wired <= 31` here would be a
447    /// closed form that is right for every value software sensibly writes and
448    /// wrong for the ones a test ROM checks.
449    pub const fn tick_random_by(&mut self, n: u64) {
450        let wired = (self.regs[reg::WIRED as usize] & 0x3F) as u32;
451        let cur = (self.regs[reg::RANDOM as usize] & 0x3F) as u32;
452        // Ticks until the walk reaches `Wired`. Zero means it is already there,
453        // and the *next* tick is the one that jumps to 31.
454        let d = cur.wrapping_sub(wired) & 0x3F;
455        let value = if n <= d as u64 {
456            cur.wrapping_sub(n as u32) & 0x3F
457        } else {
458            let cycle = (31u32.wrapping_sub(wired) & 0x3F) + 1;
459            // `n - d - 1` is how far into the cycle we are, counting the jump to
460            // 31 as position zero.
461            let into = (n - d as u64 - 1) % cycle as u64;
462            31u32.wrapping_sub(into as u32) & 0x3F
463        };
464        self.regs[reg::RANDOM as usize] = value as u64;
465    }
466
467    /// How many `Count` ticks may pass before [`Cop0::timer_edge`] could latch
468    /// `IP7`, measured from the last poll.
469    ///
470    /// `timer_edge` is a *delta* against `last_count`, not a per-tick equality,
471    /// so skipping calls does not lose an edge — it widens the window and the
472    /// next call still reports the crossing. That is what makes an idle batch
473    /// possible at all, and it is also the trap: a skipped edge would be reported
474    /// **late**, at whatever boundary polls next. Bounding a batch by this value
475    /// keeps the crossing on the boundary the per-instruction path would have
476    /// found it, because `n == to_compare` makes the very next poll see
477    /// `traveled == to_compare` and fire.
478    ///
479    /// `0` means `Compare` sits exactly on `last_count`, which `timer_edge`
480    /// treats as *not* an edge; the next match is then a full `u32` away, so this
481    /// reports that rather than a zero that would stall a caller's batch forever.
482    #[must_use]
483    pub const fn count_ticks_until_timer_match(&self) -> u64 {
484        let compare = self.regs[reg::COMPARE as usize] as u32;
485        let to_compare = compare.wrapping_sub(self.last_count);
486        if to_compare == 0 {
487            u32::MAX as u64
488        } else {
489            to_compare as u64
490        }
491    }
492
493    /// Set or clear a `Cause.IP` bit.
494    ///
495    /// `bit` is 0..=7. `IP1:IP0` are software interrupts and are written through
496    /// `MTC0` instead; this is the hardware path for `IP2` (RCP) and `IP7`
497    /// (timer).
498    pub const fn set_ip(&mut self, bit: u8, on: bool) {
499        let m = 1u64 << (8 + (bit & 7));
500        let cause = self.regs[reg::CAUSE as usize];
501        self.regs[reg::CAUSE as usize] = if on { cause | m } else { cause & !m };
502    }
503
504    /// Is an interrupt currently *recognized*?
505    ///
506    /// All four conditions, and each one matters (UM §6.1 p. 160, §6.3.5 p. 168,
507    /// Fig. 14-4 p. 357):
508    ///
509    /// - `Status.IE` — the global enable.
510    /// - **`Status.EXL` clear** — a handler is not interrupted by the thing it
511    ///   is handling. This is why `EXL` implies interrupts-off without `IE`
512    ///   being touched.
513    /// - **`Status.ERL` clear** — likewise for the error path.
514    /// - `Cause.IP & Status.IM` — at least one pending *and* unmasked.
515    ///
516    /// Dropping the `EXL`/`ERL` terms is the classic version of this bug: it
517    /// works until the first interrupt arrives inside a handler, and then
518    /// re-enters it forever.
519    #[must_use]
520    pub const fn interrupt_pending(&self) -> bool {
521        let status = self.regs[reg::STATUS as usize];
522        if status & 1 == 0 {
523            return false; // IE clear
524        }
525        if status & (1 << 1) != 0 || status & (1 << 2) != 0 {
526            return false; // EXL or ERL set
527        }
528        let ip = (self.regs[reg::CAUSE as usize] >> 8) & 0xFF;
529        let im = (status >> 8) & 0xFF;
530        ip & im != 0
531    }
532
533    /// Read a register's architectural value.
534    ///
535    /// [`ARCH_MASK`] is applied here as well as on the way in, so a 32-bit
536    /// register can never return non-zero upper bits and `EntryHi.Fill` always
537    /// reads zero — regardless of how the stored value arrived. That matters
538    /// because [`Cop0::set_hardware`] exists precisely to bypass the *write*
539    /// masks, and exception dispatch will feed it raw faulting addresses.
540    #[must_use]
541    pub const fn read(&self, n: u8) -> u64 {
542        let n = n & 31;
543        // The unused registers are a single shared latch, not storage. This is
544        // checked FIRST: they have no `ARCH_MASK` entry, so falling through
545        // would return a masked zero and look like a well-behaved read-only
546        // register rather than the quirk it is.
547        if Self::is_unused(n) {
548            return self.write_latch;
549        }
550        let raw = self.regs[n as usize];
551        if n == reg::COUNT {
552            // Derived, never stored -- see `count`.
553            return self.count() as u64;
554        }
555        if n == reg::CONFIG {
556            // Composed, not masked: the hardwired fields are merged on READ
557            // rather than seeded at construction, because seeded they could be
558            // erased by a wide-enough write mask and every later read would be
559            // wrong. Merged, that is structurally impossible.
560            //
561            // The writable bits are EP (27:24) | BE (15) | CU (3) | K0 (2:0).
562            return (raw & ARCH_MASK[reg::CONFIG as usize])
563                | ((self.ec as u64) << 28)
564                | CONFIG_HARDWIRED_HI
565                | CONFIG_HARDWIRED_LO;
566        }
567        raw & ARCH_MASK[n as usize]
568    }
569
570    /// The COP0 register numbers that are *"Reserved for future use"*
571    /// (UM Table 1-2, p. 46) and behave as a **single shared write latch**
572    /// rather than as storage.
573    ///
574    /// Writing one goes nowhere. Reading one returns the value of the most
575    /// recent `MTC0`/`DMTC0` to **any** COP0 register — so a write-then-read of
576    /// register 7 returns what was written, and the same sequence with any
577    /// other COP0 write in between returns *that* value instead.
578    ///
579    /// **Measured, replacing a guess.** The manual says nothing about these, so
580    /// this implementation previously discarded writes and read zero, recorded
581    /// as accuracy-ledger **U-1**. n64-systemtest documents and exercises the
582    /// real behavior, sweeping five written values against three interposed
583    /// ones specifically so an emulator cannot pass by echoing the first.
584    pub const UNUSED: [u8; 7] = [7, 21, 22, 23, 24, 25, 31];
585
586    /// Is this one of the [`Cop0::UNUSED`] register numbers?
587    #[must_use]
588    pub const fn is_unused(n: u8) -> bool {
589        matches!(n & 31, 7 | 21..=25 | 31)
590    }
591
592    /// Write a register, applying its writable-bit mask.
593    ///
594    /// Bits outside [`WRITE_MASK`] keep their previous value, which is what
595    /// hardware does and is *not* the same as writing zero to them.
596    ///
597    /// Registers 7, 21..=25 and 31 are *"Reserved for future use"* (UM Table 1-2,
598    /// p. 46) and are **not storage** — see [`Cop0::UNUSED`]. Writes to them go
599    /// nowhere; reads return the shared write latch.
600    pub const fn write(&mut self, n: u8, value: u64) {
601        let n = n & 31;
602        let mask = WRITE_MASK[n as usize];
603        self.regs[n as usize] = (self.regs[n as usize] & !mask) | (value & mask);
604        // "If the timer interrupt request is generated, either clear the IP7 bit
605        // of the Cause register or change the contents of the Compare register,
606        // to clear this interrupt" (UM §6.4.18, p. 200).
607        //
608        // IP7 is LATCHED, not a level. The existence of a documented clear is
609        // itself the evidence: a level tied to `Count == Compare` would
610        // self-clear on the next tick and would need no clearing mechanism at
611        // all. It would also LOSE a timer interrupt raised while `EXL` was set,
612        // because the handler would never see the one-tick pulse.
613        //
614        // Note the manual's first option -- writing `Cause.IP7` -- is not
615        // actually available on this part: `Cause` is read-only to software
616        // except `IP1:IP0`. Writing `Compare` is the usable path, and the one
617        // libdragon takes.
618        if n == reg::COMPARE {
619            self.set_ip(7, false);
620        }
621        // Writing Count re-bases the affine mapping rather than storing a value,
622        // so the register stays derived from the master clock (ADR 0006).
623        if n == reg::COUNT {
624            self.count_epoch_value = value as u32;
625            self.count_epoch_tick = self.now;
626        }
627        // Re-base the edge detector on either write.
628        //
629        // `timer_edge` asks whether `Compare` lies in the interval since the
630        // last poll. Both of these writes move an endpoint of that interval
631        // underneath it: an `MTC0 Count` that jumps *over* `Compare` would
632        // otherwise look like a crossing, and a new `Compare` behind the current
633        // `Count` would look like one that already happened. Neither fires on
634        // hardware — the timer fires when `Count` *counts up to* `Compare`, not
635        // when software rearranges the two. Starting the next interval here is
636        // what stops a write from manufacturing an edge.
637        if n == reg::COUNT || n == reg::COMPARE {
638            self.last_count = self.count();
639        }
640        // "Random is set to 31 whenever the Wired register is written"
641        // (UM §5.4.2, p. 147) -- a side effect, not a rule about Random itself,
642        // and easy to lose because it belongs to neither register alone.
643        if n == reg::WIRED {
644            self.regs[reg::RANDOM as usize] = 31;
645        }
646    }
647
648    /// Force a value past the writable-bit mask, for hardware-owned fields.
649    ///
650    /// Exception dispatch writes `Cause.ExcCode`, `EPC` and `BadVAddr`, all of
651    /// which are read-only or partly read-only *to software*. Routing those
652    /// through [`Cop0::write`] would require widening the masks, which would
653    /// also let `MTC0` write them — the exact bug the masks exist to prevent.
654    pub const fn set_hardware(&mut self, n: u8, value: u64) {
655        let n = n & 31;
656        // Bypasses WRITE_MASK, NOT ARCH_MASK. Hardware may write bits software
657        // cannot; it cannot write bits the register does not have. Without this,
658        // dispatch storing a raw 64-bit faulting address into `EntryHi` would
659        // put non-zero bits in `Fill`, which architecturally reads zero.
660        self.regs[n as usize] = value & ARCH_MASK[n as usize];
661    }
662
663    /// `MFC0 rt, rd` — read the low 32 bits, sign-extended into the 64-bit GPR.
664    ///
665    /// Sign-extension applies even to a register that is architecturally 64 bits
666    /// wide: `MFC0` is defined as a 32-bit move, so `MFC0` of an `EPC` whose bit
667    /// 31 is set yields a sign-extended value, not a truncated one.
668    #[must_use]
669    pub const fn mfc0(&self, n: u8) -> u64 {
670        self.read(n) as u32 as i32 as i64 as u64
671    }
672
673    /// `DMFC0 rt, rd` — read the full 64 bits.
674    ///
675    /// On a 32-bit-wide register this is the same as [`Cop0::mfc0`] except for
676    /// sign-extension: the upper half is zero rather than a copy of bit 31.
677    #[must_use]
678    pub const fn dmfc0(&self, n: u8) -> u64 {
679        self.read(n)
680    }
681
682    /// `MTC0 rd, rt` — write the low 32 bits.
683    ///
684    /// For a 64-bit register the upper half is **cleared**, not preserved: the
685    /// value written is the sign-extended 32-bit operand, which is how software
686    /// legitimately writes a KSEG0 address into a 64-bit register.
687    pub const fn mtc0(&mut self, n: u8, value: u64) {
688        let v = if is_wide(n) {
689            value as u32 as i32 as i64 as u64
690        } else {
691            value & 0xFFFF_FFFF
692        };
693        self.write_latch = v;
694        self.write(n, v);
695    }
696
697    /// `DMTC0 rd, rt` — write the full 64 bits.
698    pub const fn dmtc0(&mut self, n: u8, value: u64) {
699        self.write_latch = value;
700        self.write(n, value);
701    }
702
703    /// Advance `Random` by one instruction (UM §5.4.2, p. 147).
704    ///
705    /// *"decrements as each instruction executes"*, reloading 31 when it reaches
706    /// the `Wired` floor.
707    ///
708    /// # It is a plain 6-bit down-counter, and that matters when `Wired > 31`
709    ///
710    /// The reload fires on `cur == wired`, **not** `cur <= wired`, and the
711    /// decrement wraps 0 → 63. For the ordinary case (`Wired <= 31`) the two
712    /// readings agree: the counter walks 31 down to `Wired` either way.
713    ///
714    /// They diverge once `Wired` exceeds 31, which software can arrange because
715    /// `Wired` is six bits wide. Under `<=` the counter is immediately at or
716    /// below the floor and pins at 31 forever; under `==` it walks 31 → 0 → 63 →
717    /// `Wired`, covering the **whole** range. n64-systemtest checks exactly that,
718    /// and sampling a pinned register cannot be distinguished from sampling a
719    /// slow one without it.
720    pub const fn tick_random(&mut self) {
721        let wired = (self.regs[reg::WIRED as usize] & 0x3F) as u32;
722        let cur = (self.regs[reg::RANDOM as usize] & 0x3F) as u32;
723        self.regs[reg::RANDOM as usize] = if cur == wired {
724            31
725        } else {
726            cur.wrapping_sub(1) as u64 & 0x3F
727        };
728    }
729}
730
731/// The COP0 access forms, decoded from the `rs` field of a `COP0` instruction.
732///
733/// Split out so the decoder names them rather than the executor re-deriving them
734/// from raw bits.
735#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
736pub enum Cop0Op {
737    /// `MFC0 rt, rd` — 32-bit read, sign-extended.
738    Mfc0,
739    /// `DMFC0 rt, rd` — 64-bit read.
740    Dmfc0,
741    /// `MTC0 rt, rd` — 32-bit write.
742    Mtc0,
743    /// `DMTC0 rt, rd` — 64-bit write.
744    Dmtc0,
745}
746
747impl Cop0Op {
748    /// Decode the `rs` field of a `COP0` instruction, if it names an access form.
749    ///
750    /// Returns `None` for the TLB and `ERET` encodings (`rs` bit 4 set), which
751    /// are separate instructions handled by T-12-002 and T-12-004.
752    #[must_use]
753    pub const fn from_rs(rs: u8) -> Option<Self> {
754        match rs {
755            0o00 => Some(Self::Mfc0),
756            0o01 => Some(Self::Dmfc0),
757            0o04 => Some(Self::Mtc0),
758            0o05 => Some(Self::Dmtc0),
759            _ => None,
760        }
761    }
762}
763
764/// The `rd` field of a `COP0` instruction is the register number.
765#[must_use]
766pub const fn cop0_reg(d: Decoded) -> u8 {
767    d.rd
768}
769
770#[cfg(test)]
771mod tests {
772
773    /// `tick_random_by(n)` must equal `n` calls to `tick_random`, for **every**
774    /// reachable `(Wired, Random)` pair — not just the ones software sensibly
775    /// writes.
776    ///
777    /// Both fields are masked to 6 bits on write, so `Wired > 31` and
778    /// `Random < Wired` are reachable from guest code and each lengthens the
779    /// walk instead of erroring. A closed form that assumes `Wired <= 31` is
780    /// right for every ordinary value and wrong for exactly the ones a test ROM
781    /// probes, which is why this sweeps the whole space rather than sampling it.
782    ///
783    /// `n` runs past the longest possible cycle (64) so the modulo is exercised
784    /// on both sides of a wrap, and includes 0 — where the closed form must be
785    /// the identity.
786    #[test]
787    fn tick_random_by_matches_the_loop_everywhere() {
788        for wired in 0u64..64 {
789            for start in 0u64..64 {
790                for n in 0u64..=70 {
791                    let mut loops = Cop0::new();
792                    loops.write(reg::WIRED, wired);
793                    loops.write(reg::RANDOM, start);
794                    for _ in 0..n {
795                        loops.tick_random();
796                    }
797
798                    let mut closed = Cop0::new();
799                    closed.write(reg::WIRED, wired);
800                    closed.write(reg::RANDOM, start);
801                    closed.tick_random_by(n);
802
803                    assert_eq!(
804                        closed.read(reg::RANDOM),
805                        loops.read(reg::RANDOM),
806                        "wired {wired}, random {start}, {n} ticks"
807                    );
808                }
809            }
810        }
811    }
812
813    /// A batch that spans many whole cycles must land where the loop does — the
814    /// case the modulo exists for, and the one a small-`n` sweep cannot reach.
815    #[test]
816    fn tick_random_by_survives_many_whole_cycles() {
817        for wired in [0u64, 5, 31] {
818            let mut closed = Cop0::new();
819            closed.write(reg::WIRED, wired);
820            closed.write(reg::RANDOM, 31);
821            closed.tick_random_by(1_000_003);
822
823            let mut loops = Cop0::new();
824            loops.write(reg::WIRED, wired);
825            loops.write(reg::RANDOM, 31);
826            for _ in 0..1_000_003u64 {
827                loops.tick_random();
828            }
829            assert_eq!(
830                closed.read(reg::RANDOM),
831                loops.read(reg::RANDOM),
832                "wired {wired}"
833            );
834        }
835    }
836    use super::*;
837
838    /// The list of 64-bit registers has no generating rule, so it is asserted
839    /// element by element against UM Table 1-2 (p. 46). Getting one wrong is
840    /// invisible until 64-bit software runs.
841    #[test]
842    fn the_eight_wide_registers_are_exactly_these() {
843        let wide = [
844            reg::ENTRY_LO0,
845            reg::ENTRY_LO1,
846            reg::CONTEXT,
847            reg::BAD_VADDR,
848            reg::ENTRY_HI,
849            reg::EPC,
850            reg::XCONTEXT,
851            reg::ERROR_EPC,
852        ];
853        for n in 0..32u8 {
854            assert_eq!(is_wide(n), wide.contains(&n), "register {n} width is wrong");
855        }
856        assert_eq!(wide.len(), 8, "exactly eight, not seven or nine");
857    }
858
859    /// Read-only registers must reject `MTC0`. Modeled as an all-zero write
860    /// mask so "read-only" and "reserved bit" share one mechanism.
861    #[test]
862    fn read_only_registers_reject_writes() {
863        for n in [reg::RANDOM, reg::BAD_VADDR, reg::PRID, reg::CACHE_ERR] {
864            let mut c = Cop0::new();
865            let before = c.read(n);
866            c.dmtc0(n, 0xDEAD_BEEF_DEAD_BEEF);
867            assert_eq!(c.read(n), before, "register {n} is read-only");
868        }
869    }
870
871    /// `Cause` is read-only *except* `IP1:IP0` — a mask, not a whole-register
872    /// rule, and the one most likely to be widened by mistake.
873    #[test]
874    fn cause_accepts_only_the_two_software_interrupt_bits() {
875        let mut c = Cop0::new();
876        c.dmtc0(reg::CAUSE, u64::MAX);
877        assert_eq!(
878            c.read(reg::CAUSE),
879            0x0000_0300,
880            "only IP1:IP0 (bits 9:8) are software-writable"
881        );
882    }
883
884    /// `Status.DS.TS` (bit 21) is read-only; the rest of `DS` is writable.
885    #[test]
886    fn status_ts_is_read_only_but_the_rest_of_ds_is_not() {
887        let mut c = Cop0::new();
888        c.dmtc0(reg::STATUS, u64::MAX);
889        let s = c.read(reg::STATUS);
890        assert_eq!(s & (1 << 21), 0, "TS must not be software-settable");
891        assert_ne!(s & (1 << 22), 0, "BEV in the same field must be settable");
892        assert_eq!(s & (1 << 23), 0, "bit 23 is hardwired zero");
893        assert_eq!(s & (1 << 19), 0, "bit 19 is hardwired zero");
894    }
895
896    /// `Config`'s hardwired fields survive any write, because they are merged on
897    /// read rather than stored. Seeding them instead would let a wide mask erase
898    /// them permanently.
899    #[test]
900    fn config_hardwired_fields_survive_a_hostile_write() {
901        let mut c = Cop0::new();
902        c.dmtc0(reg::CONFIG, 0);
903        let v = c.read(reg::CONFIG);
904        assert_eq!(
905            (v >> 16) & 0xFF,
906            0b0000_0110,
907            "bits 23:16 are hardwired (UM Fig. 5-16)"
908        );
909        assert_eq!(
910            (v >> 4) & 0x7FF,
911            0b110_0100_0110,
912            "bits 14:4 are hardwired (UM Fig. 5-16)"
913        );
914        assert_eq!(
915            (v >> 28) & 0b111,
916            0b111,
917            "EC is read-only from `DivMode` pins"
918        );
919    }
920
921    /// Independent cross-check: the real N64 IPL boot values must decompose
922    /// exactly against these layouts. This is the cheapest evidence available
923    /// that the field positions are right, and it comes from outside the manual.
924    #[test]
925    fn the_real_ipl_boot_values_round_trip() {
926        let mut c = Cop0::new();
927        // IPL3 leaves Config = 0x0006E463: BE=1, K0=3, EP=0, CU=0, and both
928        // hardwired fields. Our EC is 0b111 rather than the 0b000 in that
929        // capture, because EC is read-only and the captured value is what IPL
930        // *wrote*, not what it read back -- so compare with EC masked out.
931        c.mtc0(reg::CONFIG, 0x0006_E463);
932        let got = c.read(reg::CONFIG) & !0x7000_0000;
933        assert_eq!(
934            got, 0x0006_E463,
935            "Config must round-trip the real IPL value outside EC"
936        );
937
938        // Status = 0x34000000 is CU1|CU0|FR.
939        c.mtc0(reg::STATUS, 0x3400_0000);
940        assert_eq!(c.read(reg::STATUS), 0x3400_0000);
941    }
942
943    /// Writing `Wired` forces `Random` to 31 — a side effect belonging to
944    /// neither register alone, and easy to lose for exactly that reason.
945    #[test]
946    fn writing_wired_reloads_random() {
947        let mut c = Cop0::new();
948        c.tick_random();
949        c.tick_random();
950        assert_ne!(c.read(reg::RANDOM), 31, "Random moved off its reset value");
951        c.mtc0(reg::WIRED, 4);
952        assert_eq!(c.read(reg::RANDOM), 31, "writing Wired reloads Random");
953    }
954
955    /// `Random` decrements per instruction and wraps at the `Wired` floor.
956    #[test]
957    fn random_decrements_and_floors_at_wired() {
958        let mut c = Cop0::new();
959        c.mtc0(reg::WIRED, 28);
960        assert_eq!(c.read(reg::RANDOM), 31);
961        // Wired itself IS a legal value -- it is the first non-wired entry, and
962        // TLBWR must be able to select it. The range is [Wired, 31] inclusive,
963        // so the wrap happens after 28, not after 29.
964        for expect in [30, 29, 28, 31, 30, 29] {
965            c.tick_random();
966            assert_eq!(c.read(reg::RANDOM), expect, "range is [Wired, 31]");
967        }
968    }
969
970    /// `EntryHi.Fill` (61:40) is write-ignored and reads zero.
971    #[test]
972    fn entryhi_fill_is_write_ignored() {
973        let mut c = Cop0::new();
974        c.dmtc0(reg::ENTRY_HI, u64::MAX);
975        let v = c.read(reg::ENTRY_HI);
976        assert_eq!((v >> 40) & 0x3F_FFFF, 0, "Fill reads zero");
977        assert_eq!((v >> 62) & 0b11, 0b11, "R is writable");
978        assert_eq!(v & 0xFF, 0xFF, "ASID is writable");
979        assert_eq!((v >> 13) & 0x7FF_FFFF, 0x7FF_FFFF, "VPN2 is writable");
980        assert_eq!((v >> 8) & 0x1F, 0, "bits 12:8 are hardwired zero");
981    }
982
983    /// `MFC0` sign-extends; `DMFC0` does not. The difference is visible on any
984    /// register holding a KSEG0 address, which is most of the interesting ones.
985    #[test]
986    fn mfc0_sign_extends_where_dmfc0_does_not() {
987        let mut c = Cop0::new();
988        c.dmtc0(reg::EPC, 0x8000_0180);
989        assert_eq!(c.mfc0(reg::EPC), 0xFFFF_FFFF_8000_0180);
990        assert_eq!(c.dmfc0(reg::EPC), 0x8000_0180);
991    }
992
993    /// `MTC0` to a 64-bit register sign-extends rather than preserving the upper
994    /// half — that is how software writes a KSEG0 address with one instruction.
995    #[test]
996    fn mtc0_to_a_wide_register_sign_extends() {
997        let mut c = Cop0::new();
998        c.dmtc0(reg::EPC, 0x1234_5678_9ABC_DEF0);
999        c.mtc0(reg::EPC, 0x8000_0180);
1000        assert_eq!(
1001            c.read(reg::EPC),
1002            0xFFFF_FFFF_8000_0180,
1003            "the old upper half must not survive"
1004        );
1005    }
1006
1007    /// `set_hardware` bypasses the masks, because exception dispatch writes
1008    /// fields that are read-only to software. If this went through `write`, the
1009    /// masks would have to be widened and `MTC0` could reach them too.
1010    #[test]
1011    fn hardware_writes_bypass_the_software_masks() {
1012        let mut c = Cop0::new();
1013        c.dmtc0(reg::BAD_VADDR, 0x1234);
1014        assert_eq!(c.read(reg::BAD_VADDR), 0, "software cannot write BadVAddr");
1015        c.set_hardware(reg::BAD_VADDR, 0x1234);
1016        assert_eq!(c.read(reg::BAD_VADDR), 0x1234, "hardware can");
1017    }
1018
1019    /// Cold-reset state, as far as the manual defines it (UM §6.4.4, p. 183).
1020    #[test]
1021    fn cold_reset_matches_the_documented_fields() {
1022        let c = Cop0::new();
1023        let s = c.read(reg::STATUS);
1024        assert_ne!(s & (1 << 2), 0, "ERL set");
1025        assert_ne!(s & (1 << 22), 0, "BEV set");
1026        assert_eq!(s & (1 << 21), 0, "TS clear");
1027        assert_eq!(s & (1 << 20), 0, "SR clear");
1028        assert_eq!(s & (1 << 27), 0, "RP clear");
1029        assert_eq!(c.read(reg::RANDOM), 31, "Random = 31");
1030        assert_eq!(c.read(reg::WIRED), 0, "Wired = 0");
1031        assert_ne!(c.read(reg::CONFIG) & (1 << 15), 0, "Config.BE set");
1032        assert_eq!((c.read(reg::PRID) >> 8) & 0xFF, 0x0B, "PRId.Imp = 0x0B");
1033    }
1034
1035    /// **The reserved registers are a shared write latch, not storage.**
1036    ///
1037    /// This replaces a pinned *guess*: the manual documents an absence, so the
1038    /// implementation used to discard writes and read zero (ledger U-1), and
1039    /// this test pinned that choice. n64-systemtest documents and exercises the
1040    /// real behavior, so the guess is now evidence.
1041    ///
1042    /// The second half is the part a naive implementation fails: an intervening
1043    /// write to *any other* COP0 register changes what the reserved register
1044    /// reads back. Storing the value per-register passes the first assertion
1045    /// and fails this one, which is why the oracle sweeps interposed values.
1046    #[test]
1047    fn the_reserved_registers_are_a_shared_write_latch() {
1048        for n in Cop0::UNUSED {
1049            let mut c = Cop0::new();
1050            c.mtc0(n, 0x1317_1A1E);
1051            assert_eq!(
1052                c.read(n) & 0xFFFF_FFFF,
1053                0x1317_1A1E,
1054                "reg {n} reads back its own write"
1055            );
1056
1057            // Any other COP0 write takes over the latch -- `Compare` here, as
1058            // the suite uses.
1059            c.mtc0(reg::COMPARE, 0x8BAD_F00D);
1060            assert_eq!(
1061                c.read(n) & 0xFFFF_FFFF,
1062                0x8BAD_F00D,
1063                "reg {n} follows the latch, so it is not storage"
1064            );
1065            // ...and the real register still holds its own value.
1066            assert_eq!(c.read(reg::COMPARE) & 0xFFFF_FFFF, 0x8BAD_F00D);
1067        }
1068    }
1069
1070    /// The unused set is exactly 7, 21..=25 and 31 — no more and no fewer. A
1071    /// range that swept in a real register would make it read the latch instead
1072    /// of its own value.
1073    #[test]
1074    fn only_the_seven_documented_numbers_are_unused() {
1075        for n in 0..32u8 {
1076            assert_eq!(
1077                Cop0::is_unused(n),
1078                Cop0::UNUSED.contains(&n),
1079                "register {n}"
1080            );
1081        }
1082        for n in [reg::COMPARE, reg::STATUS, reg::CAUSE, reg::EPC, reg::PRID] {
1083            assert!(!Cop0::is_unused(n), "{n} is a real register");
1084        }
1085    }
1086
1087    /// The access-form decode, including that TLB/`ERET` encodings are not
1088    /// access forms and must not be silently treated as one.
1089    #[test]
1090    fn cop0_access_forms_decode_and_tlb_forms_do_not() {
1091        assert_eq!(Cop0Op::from_rs(0o00), Some(Cop0Op::Mfc0));
1092        assert_eq!(Cop0Op::from_rs(0o01), Some(Cop0Op::Dmfc0));
1093        assert_eq!(Cop0Op::from_rs(0o04), Some(Cop0Op::Mtc0));
1094        assert_eq!(Cop0Op::from_rs(0o05), Some(Cop0Op::Dmtc0));
1095        // rs bit 4 set: TLBR/TLBWI/TLBWR/TLBP/ERET -- T-12-002 and T-12-004.
1096        assert_eq!(Cop0Op::from_rs(0o20), None);
1097        assert_eq!(
1098            Cop0Op::from_rs(0o02),
1099            None,
1100            "unassigned rs is not an access"
1101        );
1102    }
1103
1104    /// Writes must preserve unmasked bits rather than zeroing them -- hardware
1105    /// discards the write to those bits, which is not the same thing.
1106    #[test]
1107    fn masked_off_bits_keep_their_previous_value() {
1108        let mut c = Cop0::new();
1109        // set_hardware itself applies ARCH_MASK, so this stores Cause's
1110        // architectural bits (BD | CE | IP | ExcCode), not all 32.
1111        c.set_hardware(reg::CAUSE, 0xFFFF_FFFF);
1112        assert_eq!(c.read(reg::CAUSE), ARCH_MASK[reg::CAUSE as usize]);
1113        c.dmtc0(reg::CAUSE, 0);
1114        assert_eq!(
1115            c.read(reg::CAUSE),
1116            ARCH_MASK[reg::CAUSE as usize] & !0x300,
1117            "only IP1:IP0 were cleared; every other architectural bit survived"
1118        );
1119    }
1120
1121    /// `set_hardware` must mask on the way **in**, so the stored state never
1122    /// holds bits no hardware register has.
1123    ///
1124    /// Asserted against `regs` directly rather than through `read`, because
1125    /// `read` masks too — a read-back test passes with either enforcement point
1126    /// alone and so pins neither. Found by mutation testing: removing either one
1127    /// individually was invisible until these two tests existed.
1128    #[test]
1129    fn set_hardware_masks_on_the_way_in_not_only_on_the_way_out() {
1130        let mut c = Cop0::new();
1131        c.set_hardware(reg::CAUSE, u64::MAX);
1132        assert_eq!(
1133            c.regs[reg::CAUSE as usize],
1134            ARCH_MASK[reg::CAUSE as usize],
1135            "stored state must already be architectural"
1136        );
1137        c.set_hardware(reg::ENTRY_HI, u64::MAX);
1138        assert_eq!(
1139            (c.regs[reg::ENTRY_HI as usize] >> 40) & 0x3F_FFFF,
1140            0,
1141            "EntryHi.Fill is not even stored"
1142        );
1143    }
1144
1145    /// `read` must mask on the way **out**, independently of how the value was
1146    /// stored. Poked straight into `regs` for the same reason as above: going
1147    /// through `set_hardware` would let that mask do the work instead.
1148    #[test]
1149    fn read_masks_on_the_way_out_even_if_storage_is_corrupt() {
1150        let mut c = Cop0::new();
1151        // Not `Count`: that one is derived rather than stored, so poking its
1152        // backing slot proves nothing.
1153        c.regs[reg::COMPARE as usize] = u64::MAX;
1154        assert_eq!(c.read(reg::COMPARE), 0xFFFF_FFFF, "32 bits, not 64");
1155        c.regs[reg::ENTRY_HI as usize] = u64::MAX;
1156        assert_eq!(
1157            (c.read(reg::ENTRY_HI) >> 40) & 0x3F_FFFF,
1158            0,
1159            "Fill reads zero even from corrupt storage"
1160        );
1161    }
1162
1163    /// `set_hardware` on `Config` must not erase it. `Config`'s read value is
1164    /// composed rather than masked, so it is the one register whose `ARCH_MASK`
1165    /// entry is easy to leave at zero — which would silently wipe it.
1166    #[test]
1167    fn set_hardware_does_not_wipe_config() {
1168        let mut c = Cop0::new();
1169        c.set_hardware(reg::CONFIG, 0x0006_E463);
1170        let v = c.read(reg::CONFIG);
1171        assert_ne!(v & (1 << 15), 0, "BE survived");
1172        assert_eq!(v & 0b111, 3, "K0 survived");
1173        assert_eq!((v >> 16) & 0xFF, 0b0000_0110, "hardwired field still there");
1174    }
1175
1176    /// A 32-bit register must never return non-zero upper bits, no matter how
1177    /// the value got in. `set_hardware` deliberately bypasses the *write* masks,
1178    /// so without an architectural mask it would be a hole straight into the
1179    /// stored state — and exception dispatch (T-12-002) feeds it raw addresses.
1180    #[test]
1181    fn a_32_bit_register_cannot_hold_upper_bits_even_via_set_hardware() {
1182        for n in [
1183            reg::COUNT,
1184            reg::COMPARE,
1185            reg::STATUS,
1186            reg::CAUSE,
1187            reg::LL_ADDR,
1188        ] {
1189            let mut c = Cop0::new();
1190            c.set_hardware(n, u64::MAX);
1191            assert_eq!(
1192                c.read(n) >> 32,
1193                0,
1194                "register {n} is 32 bits wide; its upper half must read zero"
1195            );
1196            assert_eq!(c.dmfc0(n) >> 32, 0, "and DMFC0 must not expose them either");
1197        }
1198    }
1199
1200    /// `EntryHi.Fill` reads zero architecturally, not merely "is unwritable by
1201    /// MTC0". Dispatch storing a raw 64-bit faulting address is exactly the path
1202    /// that would otherwise put bits there.
1203    #[test]
1204    fn entryhi_fill_reads_zero_even_when_hardware_writes_a_raw_address() {
1205        let mut c = Cop0::new();
1206        c.set_hardware(reg::ENTRY_HI, 0xFFFF_FFFF_FFFF_FFFF);
1207        assert_eq!(
1208            (c.read(reg::ENTRY_HI) >> 40) & 0x3F_FFFF,
1209            0,
1210            "Fill (61:40) reads zero regardless of the writer"
1211        );
1212        assert_eq!((c.read(reg::ENTRY_HI) >> 62) & 0b11, 0b11, "R survives");
1213    }
1214
1215    /// The two masks are different things and the difference is load-bearing:
1216    /// a writable bit that is not architecturally present would be storable and
1217    /// unreadable, and a read-only register needs a wide arch mask with a zero
1218    /// write mask.
1219    #[test]
1220    fn every_writable_bit_is_also_an_architectural_bit() {
1221        for n in 0..32u8 {
1222            let w = WRITE_MASK[n as usize];
1223            let a = ARCH_MASK[n as usize];
1224            assert_eq!(
1225                w & !a,
1226                0,
1227                "register {n} has writable bits that are not architectural"
1228            );
1229        }
1230        // And the converse must NOT hold, or the two tables would be redundant.
1231        assert_ne!(
1232            ARCH_MASK[reg::CAUSE as usize],
1233            WRITE_MASK[reg::CAUSE as usize],
1234            "Cause is mostly hardware-written"
1235        );
1236        assert_eq!(WRITE_MASK[reg::BAD_VADDR as usize], 0);
1237        assert_ne!(ARCH_MASK[reg::BAD_VADDR as usize], 0);
1238    }
1239
1240    /// `Count` is **derived**, not stored: ADR 0006 permits exactly one
1241    /// incremented counter in the core, and it is `master_ticks`.
1242    #[test]
1243    fn count_is_derived_from_the_timeline_not_incremented() {
1244        let mut c = Cop0::new();
1245        c.set_now(0);
1246        assert_eq!(c.read(reg::COUNT), 0);
1247        c.set_now(100);
1248        assert_eq!(c.read(reg::COUNT), 100, "follows the timeline with no += 1");
1249        // Skipping the timeline forward must not lose anything -- an increment
1250        // would, which is the whole reason this is derived.
1251        c.set_now(1_000_000);
1252        assert_eq!(c.read(reg::COUNT), 1_000_000);
1253    }
1254
1255    /// ...and still guest-writable, which is what makes it *affine* rather than
1256    /// simply derived. A write re-bases the epoch; it does not store a value
1257    /// that then drifts.
1258    #[test]
1259    fn writing_count_rebases_the_epoch_rather_than_storing() {
1260        let mut c = Cop0::new();
1261        c.set_now(500);
1262        c.mtc0(reg::COUNT, 42);
1263        assert_eq!(c.read(reg::COUNT), 42, "reads back what was written");
1264        c.set_now(510);
1265        assert_eq!(
1266            c.read(reg::COUNT),
1267            52,
1268            "and then advances with the timeline from there"
1269        );
1270    }
1271
1272    /// The timer fires on `Count == Compare` (UM §6.3.4, p. 165).
1273    #[test]
1274    fn the_timer_matches_when_count_reaches_compare() {
1275        let mut c = Cop0::new();
1276        c.set_now(0);
1277        c.mtc0(reg::COMPARE, 5);
1278        assert!(!c.timer_matches());
1279        c.set_now(5);
1280        assert!(c.timer_matches());
1281        c.set_now(6);
1282        assert!(!c.timer_matches(), "it is an equality, not a threshold");
1283    }
1284
1285    /// **The timer must not fire at power-on.** `Count` and `Compare` both reset
1286    /// to zero, so an equality test latches `IP7` before a single instruction
1287    /// retires -- which n64-systemtest catches as `Cause = 0x8010` instead of
1288    /// `0x10` during an `AdEL` exception.
1289    #[test]
1290    fn the_timer_does_not_fire_at_power_on_despite_count_equalling_compare() {
1291        let mut c = Cop0::new();
1292        assert_eq!(c.count(), 0);
1293        assert_eq!(c.read(reg::COMPARE), 0, "both reset to zero");
1294        assert!(
1295            c.timer_matches(),
1296            "the equality genuinely holds -- that is the trap"
1297        );
1298        assert!(
1299            !c.timer_edge(),
1300            "but there is no TRANSITION into it, so the timer must not fire"
1301        );
1302    }
1303
1304    /// The timer fires on the transition into `Count == Compare`, once, and not
1305    /// again while the equality merely persists.
1306    #[test]
1307    fn the_timer_fires_on_the_edge_and_only_once() {
1308        let mut c = Cop0::new();
1309        c.mtc0(reg::COMPARE, 3);
1310        assert!(!c.timer_edge(), "Count = 0, Compare = 3");
1311        c.set_now(3);
1312        assert!(c.timer_edge(), "Count reached Compare");
1313        assert!(
1314            !c.timer_edge(),
1315            "the equality still holds, but the edge has passed"
1316        );
1317    }
1318
1319    /// **A poll that steps over `Compare` still sees the crossing.**
1320    ///
1321    /// `Count` is derived from the master clock, so the gap between two polls is
1322    /// whatever the pipeline did in between — a stall makes it dozens of cycles.
1323    /// Asking "is `Count == Compare` now?" loses the match entirely; asking "was
1324    /// `Compare` crossed since the last poll?" does not.
1325    #[test]
1326    fn the_timer_edge_is_detected_even_when_the_poll_steps_over_compare() {
1327        let mut c = Cop0::new();
1328        c.mtc0(reg::COMPARE, 40);
1329        assert!(!c.timer_edge());
1330        // One poll, jumping clean over 40.
1331        c.set_now(80);
1332        assert!(
1333            c.timer_edge(),
1334            "Compare lies inside the interval the poll skipped"
1335        );
1336        c.set_now(120);
1337        assert!(!c.timer_edge(), "and it does not fire again afterwards");
1338    }
1339
1340    /// **Software cannot manufacture a timer edge by writing `Count`.**
1341    ///
1342    /// The timer fires when `Count` counts up to `Compare`. An `MTC0 Count` that
1343    /// jumps straight over `Compare` moves an endpoint of the detector's
1344    /// interval, and looks exactly like a crossing to an implementation that
1345    /// does not re-base on the write.
1346    #[test]
1347    fn writing_count_over_compare_does_not_fire_the_timer() {
1348        let mut c = Cop0::new();
1349        c.mtc0(reg::COMPARE, 40);
1350        assert!(!c.timer_edge());
1351        c.mtc0(reg::COUNT, 80); // jumped past Compare without counting to it
1352        assert!(
1353            !c.timer_edge(),
1354            "a write is not a count — no edge was crossed"
1355        );
1356        // Counting up to the next match still works.
1357        c.mtc0(reg::COMPARE, 100);
1358        c.set_now(c.count_now() + 20); // Count 80 -> 100
1359        assert!(c.timer_edge(), "counting up to Compare still fires");
1360    }
1361
1362    /// The same for `Compare`: setting it *behind* the current `Count` must not
1363    /// look like a crossing that already happened.
1364    ///
1365    /// The gap before the write is deliberate and load-bearing. If `Count` were
1366    /// polled immediately beforehand the detector's interval would already be
1367    /// empty, and the test would pass whether or not the write re-bases —
1368    /// converging success and failure paths onto the same behavior and proving
1369    /// nothing.
1370    #[test]
1371    fn writing_compare_behind_count_does_not_fire_the_timer() {
1372        let mut c = Cop0::new();
1373        // Count advances to 100 with NO intervening poll, so the pending
1374        // interval is (0, 100] when the write lands.
1375        c.set_now(100);
1376        c.mtc0(reg::COMPARE, 50);
1377        assert!(
1378            !c.timer_edge(),
1379            "Compare was placed behind Count; nothing ever counted up to it"
1380        );
1381    }
1382}