Skip to main content

rustyn64_cpu/
lib.rs

1//! `rustyn64-cpu` — NEC VR4300 (MIPS R4300i) main CPU.
2//!
3//! 64-bit MIPS III core: 32 general-purpose registers, HI/LO, the CP0
4//! system-control coprocessor (TLB + exceptions), the CP1 FPU, and the `SysAD`
5//! bus interface. This is a **skeleton** — the real interpreter/JIT, the TLB,
6//! and the FPU are major roadmap phases. Behavior is pinned against
7//! `n64-systemtest` FIRST (test-ROM-is-spec), then implemented until it passes.
8//!
9//! Part of the one-directional chip-crate graph (see `docs/architecture.md`):
10//! this crate does NOT depend on any other chip crate. It talks to the rest of
11//! the machine through the [`Bus`] trait, which `rustyn64-core` implements.
12//! `#![no_std]` + `alloc` so it cross-compiles to a bare-metal target; only the
13//! frontend carries `std` + `unsafe`.
14
15#![no_std]
16#![forbid(unsafe_code)]
17#![warn(missing_docs)]
18// Truncating / sign casts are the canonical encoding for MIPS register
19// arithmetic; we annotate once at module level rather than per line.
20#![allow(
21    clippy::cast_possible_truncation,
22    clippy::cast_lossless,
23    clippy::cast_possible_wrap,
24    clippy::cast_sign_loss
25)]
26// Skeleton `tick`/step methods are deliberately non-`const`: they will gain
27// real (non-const) bus-driven bodies as the chip is implemented. Accept the
28// pedantic const-fn suggestion at module level rather than salt every stub.
29#![allow(clippy::missing_const_for_fn)]
30
31extern crate alloc;
32
33use serde::{Deserialize, Serialize};
34
35pub mod addr;
36pub mod alu;
37pub mod cache;
38pub mod cop0;
39pub mod cop1;
40pub mod decode;
41pub mod exception;
42pub mod exec;
43pub mod fpr;
44pub mod fpu;
45pub mod mem;
46pub mod pipeline;
47pub mod regs;
48pub mod softfloat;
49pub mod sysad;
50pub mod tlb;
51
52pub use addr::{Cached, Physical, Segment, segment, translate_via};
53pub use alu::{HiLo, MulDiv};
54pub use decode::{Decoded, Op, decode};
55pub use exec::{Executed, WriteBack, execute};
56pub use mem::{LoadKind, StoreKind};
57#[cfg(feature = "work-counters")]
58pub use pipeline::commit_class;
59pub use pipeline::{Exception, Interlock, Latch, Pipeline, Stage};
60pub use regs::Regs;
61pub use sysad::{BlockOrder, Phase, Transaction, Width, block_order};
62
63/// Which half of a `SysAD` bus transaction is on the wire.
64///
65/// The VR4300 talks to the RCP over the `SysAD` bus, which multiplexes the command
66/// and the data onto the same lines; `SYSCMD` bit 4 is documented as "Command or
67/// Data" and this enum mirrors that split.
68///
69/// **This describes the bus protocol and carries no interrupt semantics.** An
70/// earlier revision paired it with a `poll_irq_at_phase(BusPhase)` hook, on the
71/// assumption that interrupts are sampled at a particular half of a transaction.
72/// No such coupling is documented anywhere — not in the User's Manual, not on the
73/// wiki. The documented rule (UM §4.7.1) is per-`PCycle` and gated on stall state:
74/// *"NMI and interrupt exception requests are accepted only if the previous
75/// `PCycle` was a run cycle."* That hook was shaped on the wrong axis and was
76/// removed rather than completed (ADR 0007).
77///
78/// `SysAD` runs at `SClock` = `MClock` = 62.5 MHz, so one bus cycle is 1.5 `PCycles` — 3
79/// master ticks against the CPU's 2 (ADR 0006). This is *not* the deferred ADR
80/// 0005 refactor, which concerns resolution finer than one `PClock`.
81///
82/// TODO(T-11-008): the transaction model that actually uses this.
83#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
84pub enum BusPhase {
85    /// The command half — the CPU drives `SYSCMD` and the address.
86    Command,
87    /// The data half — the transfer itself, and where the result commits.
88    Data,
89}
90
91/// The system-memory bus the VR4300 borrows during [`Cpu::tick`].
92///
93/// Implemented by `rustyn64-core::Bus`. Kept as a trait so the CPU can be
94/// fuzzed and benchmarked against a tiny in-crate bus without pulling in the
95/// rest of the machine.
96pub trait Bus {
97    /// Read a byte at a 32-bit physical address (post-TLB).
98    fn read_u8(&mut self, addr: u32) -> u8;
99    /// Write a byte at a 32-bit physical address (post-TLB).
100    fn write_u8(&mut self, addr: u32, val: u8);
101
102    /// Read an aligned big-endian 32-bit word. Default composes four byte
103    /// reads; `rustyn64-core` overrides with a fast RDRAM path.
104    fn read_u32(&mut self, addr: u32) -> u32 {
105        let b = [
106            self.read_u8(addr),
107            self.read_u8(addr.wrapping_add(1)),
108            self.read_u8(addr.wrapping_add(2)),
109            self.read_u8(addr.wrapping_add(3)),
110        ];
111        u32::from_be_bytes(b)
112    }
113
114    /// Write an aligned big-endian 32-bit word.
115    fn write_u32(&mut self, addr: u32, val: u32) {
116        let b = val.to_be_bytes();
117        self.write_u8(addr, b[0]);
118        self.write_u8(addr.wrapping_add(1), b[1]);
119        self.write_u8(addr.wrapping_add(2), b[2]);
120        self.write_u8(addr.wrapping_add(3), b[3]);
121    }
122
123    /// Write `value` as a `width`-byte store, **carrying the access width and
124    /// the untruncated source register to the bus**.
125    ///
126    /// The CPU cannot narrow the value itself, because whether narrowing is
127    /// correct is a property of the *target*, not of the instruction. RDRAM
128    /// honors the byte enables and stores exactly `width` bytes; every device
129    /// on the RCP's internal bus ignores the access size entirely and latches
130    /// the whole 32-bit word the VR4300 placed on `SysAD` — including the bits
131    /// of the source register that a narrow store was never meant to send
132    /// (N64brew *Memory map* §Physical Memory Map accesses).
133    ///
134    /// So the width and the full register both have to survive the call, and
135    /// the implementor decides. The default here is the RDRAM-style narrowing,
136    /// which is right for a plain memory and for the test buses; `rustyn64-core`
137    /// overrides it to model the RCP's size-blindness.
138    fn write_sized(&mut self, addr: u32, width: u64, value: u64) {
139        match width {
140            1 => self.write_u8(addr, value as u8),
141            2 => {
142                self.write_u8(addr, (value >> 8) as u8);
143                self.write_u8(addr.wrapping_add(1), value as u8);
144            }
145            4 => self.write_u32(addr, value as u32),
146            8 => {
147                self.write_u32(addr, (value >> 32) as u32);
148                self.write_u32(addr.wrapping_add(4), value as u32);
149            }
150            _ => {}
151        }
152    }
153
154    /// Does this host offer the **EMUX** emulator extensions?
155    ///
156    /// Default: **no**, and that default is the load-bearing part. Real hardware
157    /// has no EMUX — COP0 CO `funct` 0x20-0x3F retires inertly (ledger C-8), so
158    /// `xdetect` leaves its destination register untouched and the guest
159    /// concludes no extensions exist. Advertising them changes which console
160    /// path n64-systemtest takes -- it changes the instruction stream.
161    ///
162    /// ares takes exactly this position: every EMUX handler in its `emux.cpp`
163    /// opens with `if(!system.homebrewMode) return;`, off by default. A default
164    /// build of `RustyN64` must behave like hardware; a harness that wants the
165    /// faster console opts in deliberately.
166    fn emux_enabled(&self) -> bool {
167        false
168    }
169
170    /// `EMUX xlog`: the guest has asked the *emulator* to print `bytes`.
171    ///
172    /// Default: discard. `rustyn64-core` collects it. This is n64-systemtest's
173    /// out-of-band console channel — it reaches the host without any PI, SI or
174    /// `ISViewer` emulation, which is why it is worth implementing well before the
175    /// cartridge subsystem exists.
176    fn emux_log(&mut self, bytes: &[u8]) {
177        let _ = bytes;
178    }
179
180    /// `EMUX xioctl(EXIT)`: the guest has asked the emulator to terminate.
181    ///
182    /// Default: ignore. A harness that honors it gets a definite end-of-run
183    /// signal instead of a tick budget, which is the difference between "the
184    /// suite finished" and "we stopped watching".
185    fn emux_exit(&mut self) {}
186
187    /// Sample the pending-interrupt level: the MI lines masked by `MI_MASK`.
188    ///
189    /// Default: no interrupt pending. `rustyn64-core` overrides it.
190    ///
191    /// Sampling happens **once per `PClock` in the DC stage** (UM Figure 4-12 and
192    /// §4.7.6, which lists the interrupt exception among the DC-stage priorities)
193    /// and is accepted only if the previous `PCycle` was a run cycle (§4.7.1). The
194    /// run-cycle gate lives in the pipeline, not here — this hook only reports the
195    /// level. Exactly one recognition predicate exists in the tree.
196    fn poll_irq(&mut self) -> bool {
197        false
198    }
199}
200
201/// NEC VR4300 architectural state.
202///
203/// This is the **skeleton** register file only; the decode/execute pipeline,
204/// the CP0 TLB, and the CP1 FPU are roadmap phases left as marked TODOs.
205#[derive(Debug, Clone, Serialize, Deserialize)]
206pub struct Cpu {
207    /// The register file: 32 GPRs plus `HI`/`LO`. `$zero`'s hardwiring lives in
208    /// [`Regs::read`]/[`Regs::write`] so no call site can forget it.
209    pub regs: Regs,
210    /// Program counter (virtual address).
211    pub pc: u64,
212    /// The five-stage pipeline: four inter-stage latches plus control state
213    /// (ADR 0007). Advanced one `PClock` per [`Cpu::tick`].
214    pub pipeline: Pipeline,
215    /// Retired-work tally: instructions retired since power-on, for the
216    /// golden-log differ.
217    ///
218    /// This is **not** a time position and nothing schedules against it — the
219    /// scheduler derives every cycle position from its one `master_ticks` counter
220    /// (ADR 0006). A work tally is the one kind of counter that is still allowed
221    /// to be incremented; see `System::cpu_cycles()` for the CPU's *position*.
222    pub retired: u64,
223    // This struct deliberately holds no CP0/TLB/CP1/LL state. All of it exists and
224    // lives one level down, in [`Pipeline`], because it is pipelined state rather
225    // than architectural state the fetch loop owns (ADR 0007): `pipeline.cop0`,
226    // `pipeline.tlb`, `pipeline.fpr`, `pipeline.ll_bit`, and the branch-delay-slot
227    // flag as `in_delay_slot` riding in the inter-stage latch rather than a global
228    // CPU flag.
229    //
230    // Stated positively because this previously read as a `TODO` listing all five
231    // as unimplemented, long after they shipped.
232}
233
234impl Default for Cpu {
235    fn default() -> Self {
236        Self::new()
237    }
238}
239
240impl Cpu {
241    /// Construct at power-on / cold reset.
242    ///
243    /// `gpr[0]` is the architectural zero register. Any phase alignment, where
244    /// applicable, comes from the *seeded* scheduler PRNG (the determinism
245    /// contract — see `docs/adr/0004`), never the OS RNG.
246    #[must_use]
247    pub const fn new() -> Self {
248        Self {
249            regs: Regs::new(),
250            // The reset vector, as a SIGN-EXTENDED 64-bit address. In 32-bit
251            // addressing mode every valid address is one, and `0x0000_0000_BFC0_0000`
252            // is not the same address -- it is an address error. n64-systemtest
253            // asserts exactly that distinction ("LW with address not sign
254            // extended"), so the truncated form is not a harmless shorthand.
255            pc: 0xFFFF_FFFF_BFC0_0000,
256            pipeline: Pipeline::new(),
257            retired: 0,
258        }
259    }
260
261    /// Set the program counter (used by golden-log automation harnesses).
262    pub const fn set_pc(&mut self, pc: u64) {
263        self.pc = pc;
264    }
265
266    /// Advance the CPU by **one `PClock`** — not one instruction.
267    ///
268    /// The scheduler calls this on every CPU edge (every 2nd master tick, ADR
269    /// 0006). At least 5 `PCycles` are required to execute an instruction (UM
270    /// §4.1), and `DDIV` stalls the whole pipeline for 69 (UM Table 3-12), so a
271    /// tick is emphatically not an instruction.
272    ///
273    /// Hot path: keep allocation-free (no `Vec`/`Box` in `tick`). The `bus`
274    /// argument is the `&mut Bus` the scheduler hands down each step.
275    /// **Prefer [`Cpu::tick_at`] when a scheduler is present.** This path holds
276    /// the COP0 `Count` timeline still, because `Count` is derived from the
277    /// master clock (ADR 0006) and this function has no access to it — so
278    /// `Count`/`Compare` and the timer interrupt do not advance. That is
279    /// deliberate: guessing a rate here would be wrong, and `Count` runs at half
280    /// `PClock`, not one step per call.
281    pub fn tick<B: Bus>(&mut self, bus: &mut B) {
282        self.pipeline.advance(bus, &mut self.regs, &mut self.pc);
283        self.retired = self.pipeline.retired;
284    }
285
286    /// Step one `PCycle` with the scheduler's `Count` timeline supplied.
287    ///
288    /// The scheduler owns `master_ticks` and derives `count_ticks` from it
289    /// (ADR 0006); the CPU turns that into the architectural, guest-writable
290    /// `Count`. Passing it in rather than incrementing locally is what keeps
291    /// `master_ticks` the only incremented counter in the core.
292    pub fn tick_at<B: Bus>(&mut self, bus: &mut B, count_now: u64) {
293        self.pipeline
294            .advance_at(bus, &mut self.regs, &mut self.pc, count_now);
295        self.retired = self.pipeline.retired;
296    }
297
298    /// Whether the CPU is parked at a recognized self-branch idle loop.
299    #[cfg(feature = "fast-exec")]
300    #[must_use]
301    pub const fn is_parked_in_idle_loop(&self) -> bool {
302        matches!(self.pipeline.idle_pc, Some(pc) if pc == self.pc)
303    }
304
305    /// `Count` ticks the scheduler may batch before the timer could latch `IP7`.
306    /// One idle pair is exactly one `Count` tick, so this is also a pair count.
307    #[cfg(feature = "fast-exec")]
308    #[must_use]
309    pub const fn count_ticks_until_timer_match(&self) -> u64 {
310        self.pipeline.cop0.count_ticks_until_timer_match()
311    }
312
313    /// Retire `pairs` iterations of a recognized idle loop.
314    ///
315    /// The per-boundary path's state changes for the idle pair, applied `pairs`
316    /// times: two instructions retired and `Random` ticked twice. Everything the
317    /// per-boundary path does *besides* this — sampling the interrupt lines,
318    /// the NMI check, `set_now` — is what the caller has established cannot
319    /// change across the batch, and is why this is not simply a loop over
320    /// [`Cpu::step_instruction_at`].
321    ///
322    /// `Random` advances through [`Cop0::tick_random_by`], which is the closed
323    /// form of the wrap-at-`Wired` walk (UM §6.3.3) rather than `random -= 2n` —
324    /// that shortcut is wrong exactly when the batch crosses the wrap, and the
325    /// batch is long precisely when it would.
326    #[cfg(feature = "fast-exec")]
327    pub fn retire_idle_pairs(&mut self, pairs: u64) {
328        self.pipeline.retired = self.pipeline.retired.wrapping_add(pairs.wrapping_mul(2));
329        self.pipeline.cop0.tick_random_by(pairs.wrapping_mul(2));
330        self.retired = self.pipeline.retired;
331    }
332
333    /// Execute one instruction (plus its delay slot, if it branches) and return
334    /// the `PCycle`s it cost — the **instruction-granular** path (ADR 0013),
335    /// behind the default-off `fast-exec` feature.
336    ///
337    /// A **separate entry point**, not a branch inside [`Cpu::tick_at`], for the
338    /// same reason `System::run_until_fast` is one: with the feature off this
339    /// function does not exist, so ADR 0011 §1's "default builds are unchanged" is
340    /// true by construction rather than by inspection, and the accurate path
341    /// carries no branch that exists only for its sibling.
342    ///
343    /// The unit differs from every other step function in this crate, and the
344    /// signature says so: [`Cpu::tick`] and [`Cpu::tick_at`] advance **one
345    /// `PClock`** and return nothing; this one advances **one instruction** and
346    /// returns what that cost. A caller that treats the return value as a tick
347    /// count will run the machine roughly five times too fast.
348    ///
349    /// `count_now` is the scheduler's derived COP0 `Count` position, passed in for
350    /// the same reason [`Cpu::tick_at`] takes it (ADR 0006).
351    #[cfg(feature = "fast-exec")]
352    #[must_use = "the return value is the instruction's cost in PCycles; \
353                  discarding it makes the machine run at one PCycle per instruction"]
354    pub fn step_instruction_at<B: Bus>(&mut self, bus: &mut B, count_now: u64) -> u32 {
355        let cost = self
356            .pipeline
357            .step_instruction(bus, &mut self.regs, &mut self.pc, count_now);
358        self.retired = self.pipeline.retired;
359        cost
360    }
361}
362
363/// Returns the crate version string.
364#[must_use]
365pub const fn version() -> &'static str {
366    env!("CARGO_PKG_VERSION")
367}
368
369#[cfg(test)]
370mod tests {
371    use super::*;
372
373    struct NullBus;
374    impl Bus for NullBus {
375        fn read_u8(&mut self, _addr: u32) -> u8 {
376            0
377        }
378        fn write_u8(&mut self, _addr: u32, _val: u8) {}
379    }
380
381    #[test]
382    fn constructs_with_zero_register() {
383        let cpu = Cpu::new();
384        assert_eq!(cpu.regs.read(0), 0);
385        assert_eq!(cpu.pc, 0xFFFF_FFFF_BFC0_0000);
386    }
387
388    /// A tick is one `PClock`, not one instruction. The pipeline is 5 stages
389    /// deep, so nothing retires until it has filled (UM §4.1: "at least 5
390    /// `PCycle`s are required to execute an instruction").
391    #[test]
392    fn a_tick_is_a_pclock_not_an_instruction() {
393        let mut cpu = Cpu::new();
394        let mut bus = NullBus;
395        for cycle in 1..=4 {
396            cpu.tick(&mut bus);
397            assert_eq!(cpu.retired, 0, "retired on cycle {cycle}, before WB ran");
398        }
399        cpu.tick(&mut bus);
400        assert_eq!(cpu.retired, 1, "the first instruction retires on cycle 5");
401    }
402
403    #[test]
404    fn version_is_non_empty() {
405        assert!(!version().is_empty());
406    }
407}