long/
long.rs

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