long/
long.rs

1// SPDX-License-Identifier: MIT
2//! Rung 5 without MAME traces: a long synthetic program on a seeded bus.
3//!
4//!     long SEED STEPS [--alternate]
5//!
6//! Every read is answered from a 64-bit linear congruential generator, so the
7//! core runs a random instruction stream with random operands, through every
8//! opcode, T and D both ways, with the mapper changing under it. Every 1,024
9//! cycles the bus takes one more value from the generator and drives the
10//! interrupt inputs with it (the three lines, now and then the disable
11//! register, an NMI, rarely a reset). Every cycle is folded into a digest
12//! (address, value, and what the callback sees in the pins: the cycle's kind,
13//! the clock switch, the opcode) and so is the whole `CpuState` after every
14//! step;
15//! the digest is printed every 250,000 steps and at the end.
16//! `scripts/reference_long.py` does the same on the reference core, and the
17//! two outputs are compared line for line.
18//!
19//! Block transfers would swallow the run (65,536 bytes each, on average half
20//! that): a read that returns one of the five block opcodes is changed to the
21//! opcode before it 63 times in 64, on both sides alike.
22
23use huc6280::state::CpuState;
24use huc6280::{
25    Bus, DecimalFormula, HuC6280, IrqPollCycle, Kind, Pins, TmaMultiple, VanishedInterrupt,
26};
27
28const PRIME: u64 = 0x100000001B3;
29
30struct Noise {
31    state: u64,
32    count: u64,
33    digest: u64,
34}
35
36impl Noise {
37    fn draw(&mut self) -> u64 {
38        self.state = self
39            .state
40            .wrapping_mul(6364136223846793005)
41            .wrapping_add(1442695040888963407);
42        self.state
43    }
44
45    fn fold(&mut self, value: u64) {
46        self.digest = (self.digest ^ value).wrapping_mul(PRIME);
47    }
48
49    /// Every cycle: count it, and every 1,024th drive the interrupt inputs.
50    fn tick(&mut self, pins: &mut Pins) {
51        self.count += 1;
52        if self.count & 0x3FF == 0 {
53            let roll = self.draw() >> 32;
54            pins.set_irq_lines(roll & 2 != 0, roll & 1 != 0, roll & 4 != 0);
55            if (roll >> 3) & 7 == 0 {
56                pins.set_irq_disable((roll >> 6) as u8 & 7);
57            }
58            if (roll >> 9) & 0x1F == 0 {
59                pins.frame.request_non_maskable_interrupt();
60            }
61            if (roll >> 14) & 0x3FF == 0 {
62                pins.frame.request_reset();
63            }
64        }
65    }
66}
67
68/// What a callback can see of the CPU, for the digest: the cycle's kind as
69/// `Pins::kind` gives it, the clock switch and the opcode.
70fn seen(pins: &Pins) -> u64 {
71    let kind = match pins.kind() {
72        Kind::Read => 1,
73        Kind::Write => 2,
74        Kind::Dummy => 3,
75        Kind::Idle => 4,
76    };
77    (kind << 32) | ((pins.high_speed as u64) << 36) | ((pins.opcode() as u64) << 40)
78}
79
80impl Bus for Noise {
81    fn read(&mut self, address: u32, pins: &mut Pins) -> u8 {
82        self.tick(pins);
83        let state = self.draw();
84        let mut value = (state >> 56) as u8;
85        if matches!(value, 0x73 | 0xC3 | 0xD3 | 0xE3 | 0xF3) && (state >> 48) & 0x3F != 0 {
86            value ^= 0x01;
87        }
88        self.fold(seen(pins) | ((address as u64) << 8) | value as u64);
89        value
90    }
91
92    fn write(&mut self, address: u32, value: u8, pins: &mut Pins) {
93        self.tick(pins);
94        self.fold(seen(pins) | ((address as u64) << 8) | value as u64);
95    }
96
97    fn idle(&mut self, address: Option<u32>, pins: &mut Pins) {
98        self.tick(pins);
99        self.fold(seen(pins) | ((address.unwrap_or(0) as u64) << 8));
100    }
101}
102
103fn tri(value: Option<bool>) -> u64 {
104    match value {
105        None => 2,
106        Some(value) => value as u64,
107    }
108}
109
110/// Every field of the state, in the order the reference's script folds them.
111fn fold_state(bus: &mut Noise, state: &CpuState, cycles: u32) {
112    bus.fold(cycles as u64);
113    for value in [state.a, state.x, state.y, state.s] {
114        bus.fold(value as u64);
115    }
116    bus.fold(state.pc as u64);
117    bus.fold(state.p as u64);
118    for value in state.mpr {
119        bus.fold(value as u64);
120    }
121    for value in [
122        state.high_speed as u64,
123        state.mpr_latch as u64,
124        state.irq1 as u64,
125        state.irq2 as u64,
126        state.tiq as u64,
127        state.irq_disable as u64,
128        state.halted as u64,
129        state.reset_pending as u64,
130        state.maskable_interrupt_pending as u64,
131        state.non_maskable_interrupt_pending as u64,
132        tri(state.polled_i),
133        tri(state.polled_maskable_interrupt),
134        tri(state.polled_non_maskable_interrupt),
135        state.skipped_poll as u64,
136        state.polled_irq_lines.map_or(8, u64::from),
137    ] {
138        bus.fold(value);
139    }
140}
141
142fn main() {
143    let args: Vec<String> = std::env::args().skip(1).collect();
144    if args.len() < 2 {
145        eprintln!("usage: long SEED STEPS [--alternate]");
146        std::process::exit(2);
147    }
148    let seed: u64 = args[0].parse().expect("SEED");
149    let steps: u64 = args[1].parse().expect("STEPS");
150    let mut cpu = HuC6280::new(Noise {
151        state: seed,
152        count: 0,
153        digest: 0xCBF29CE484222325,
154    });
155    if args.get(2).map(String::as_str) == Some("--alternate") {
156        cpu.decimal_formula = DecimalFormula::Mesen;
157        cpu.sbc_honours_t = true;
158        cpu.tsb_z_from_test = true;
159        cpu.tma_multiple = TmaMultiple::Highest;
160        cpu.zero_page_pointer_wraps = false;
161        cpu.block_reads_hardware_page_as_zero = false;
162        cpu.nop_63_cycles = 4;
163        cpu.interrupt_entry_cycles = 7;
164        cpu.irq_poll_cycle = IrqPollCycle::Last;
165        // Drop since the reference's clean rewrite withdrew "latched" (6ce348e). Under
166        // poll Last the poll lines are the live lines, so "latched" and "drop" took the
167        // same sources: the run is the one it was.
168        cpu.vanished_interrupt = VanishedInterrupt::Drop;
169    }
170    cpu.request_reset();
171    let began = std::time::Instant::now();
172    let mut total = 0u64;
173    for step in 1..=steps {
174        let cycles = cpu.step();
175        total += cycles as u64;
176        let state = cpu.capture_state();
177        fold_state(&mut cpu.bus, &state, cycles);
178        if step % 250_000 == 0 || step == steps {
179            println!("step {step} cycles {total} digest {:016x}", cpu.bus.digest);
180        }
181    }
182    eprintln!("{:.3} s", began.elapsed().as_secs_f64());
183}