rsemu 0.0.1

A multiplatform emulator in pure Rust, built bottom-up on a generic framework.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
//! The Zilog Z80 — a cycle-accurate interpreter.
//!
//! Covers the documented instruction set, all five prefix pages, and the
//! undocumented behaviour real software depends on: the `IX`/`IY` half
//! registers, `SLL`, the duplicate `ED` encodings, and the `DDCB`/`FDCB` forms
//! that write a register as well as memory. The internal `WZ` (`MEMPTR`)
//! register and flag bits 3 and 5 are modelled from the first commit rather
//! than retrofitted, because `BIT n,(HL)`, `SCF`/`CCF` and `IN r,(C)` make
//! them observable and no serious test suite passes without them.
//!
//! # What "cycle-accurate" means here
//!
//! Not "the instruction took eleven T-states". Every T-state belongs to an
//! M-cycle, and an M-cycle is a fetch, a read, a write, an I/O transfer, or an
//! internal operation that requests nothing — so `INC (HL)` is eleven
//! T-states *because* it fetches, reads, thinks and writes, not because a
//! table says so. [`Z80::last_cycles`] hands back that sequence, which is what
//! a bus-level trace and the conformance runner both compare against hardware.
//!
//! # Two address spaces
//!
//! The Z80 has a separate I/O address space, and it is not an afterthought:
//! `IN`/`OUT` drive `IORQ` instead of `MREQ`, the port address is sixteen bits
//! wide with `B` or `A` on the high half, and every access carries one
//! automatic wait state. So the core takes two
//! [`AddressSpace`]s — [`Z80::attach_space`] for memory and
//! [`Z80::attach_io_space`] for ports — and a machine that wires only the
//! first gets a floating bus on every port rather than a fault storm.
//!
//! # Assembling one
//!
//! ```
//! use std::sync::Arc;
//! use rsemu::core::space::{AddressSpace, RamStore, Region};
//! use rsemu::cpu::z80::{Config, Z80};
//!
//! // 64 KiB of RAM with `LD A,$42` at the reset address.
//! let ram = Arc::new(RamStore::new(0x1_0000));
//! ram.write_u8(0x0000, 0x3e).unwrap();
//! ram.write_u8(0x0001, 0x42).unwrap();
//!
//! let space = AddressSpace::new("cpu", 16);
//! space.topology().map(Region::ram("ram", ram), 0).unwrap();
//!
//! let cpu = Z80::new(Config::default());
//! cpu.attach_space(Arc::new(space));
//! cpu.step();              // the reset sequence
//! cpu.step();              // LD A,$42
//! assert_eq!(cpu.regs().a, 0x42);
//! assert_eq!(cpu.cycles(), 10);   // 3 T-states of reset, then 7
//! ```
//!
//! # Modules
//!
//! | Module | Holds |
//! | --- | --- |
//! | [`isa`] | the three declarative opcode tables, and the rules that derive the index pages from them |
//! | [`disasm`] | the disassembler generated from those tables |
//! | `exec` (private) | the interpreter: one bus access per M-cycle |
//!
//! # Accuracy
//!
//! Measured, not asserted (`ROADMAP.md` §0). The core passes all **1 604 000**
//! vectors of `SingleStepTests/z80` — every encoding on every page, compared
//! register by register, `WZ` and the flag latches included, against the full
//! T-state bus trace — and both `zexdoc` and `zexall` run clean, `zexall`
//! being the one that does *not* mask the undocumented flag bits. The
//! known-failures ledger in `conformance.rs` is empty.
//!
//! # Sources
//!
//! Hardware documentation only (`ROADMAP.md` §1): Zilog **UM0080**, the World
//! of Spectrum Z80 reference, Sean Young's *Undocumented Z80 Documented*
//! v0.91, and the *MEMPTR* write-up for the `WZ` rules
//! (`docs/cpu/z80-sm83.md`). A handful of undocumented flag rules — the
//! block-I/O repeat behaviour above all — were pinned down against
//! `SingleStepTests/z80` (MIT, © 2024 SingleStepTests), which is measured
//! hardware behaviour rather than anyone's implementation of it. No copyleft
//! emulator was consulted.

pub mod disasm;
mod exec;
pub mod isa;

#[cfg(test)]
mod tests;

// The conformance runner reads a downloaded corpus off the filesystem, so it
// exists only where there is one (`ROADMAP.md` §12).
#[cfg(all(test, feature = "std"))]
mod conformance;

use alloc::boxed::Box;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::fmt;

use crate::core::device::{Device, DeviceClass, Initiator, PropertySpec, RealizeCtx, ResetKind};
use crate::core::error::{Error, Result};
use crate::core::props::{Props, ValueKind};
use crate::core::registry::Registry;
use crate::core::space::{AddressSpace, MemAttrs, RequesterId};
use crate::core::state::{ChunkReader, ChunkWriter, Sink, Source};
use crate::core::sync::{self, AtomicBool, AtomicU8, LockRank, Ordering};
use crate::core::value::Width;
use crate::core::wire::{FanIn, Level, Resolve, WireId, WireSink};

use exec::{Exec, State};

/// The flag register's bits.
///
/// Bits 3 and 5 have no name in Zilog's manual and no defined meaning — they
/// are whatever the last operation left in the flag latch. That makes them
/// *observable*, and real software (and every conformance suite) depends on
/// them, so they are modelled rather than masked off.
pub mod flags {
    /// Carry.
    pub const C: u8 = 0x01;
    /// Add/subtract — set by the subtracting operations, and read by `DAA`.
    pub const N: u8 = 0x02;
    /// Parity / overflow, depending on the operation.
    pub const PV: u8 = 0x04;
    /// Undocumented bit 3, often written `F3` or `XF`.
    pub const XF: u8 = 0x08;
    /// Half carry — carry out of bit 3, which `DAA` needs.
    pub const H: u8 = 0x10;
    /// Undocumented bit 5, often written `F5` or `YF`.
    pub const YF: u8 = 0x20;
    /// Zero.
    pub const Z: u8 = 0x40;
    /// Sign — a copy of bit 7 of the result.
    pub const S: u8 = 0x80;
    /// Both undocumented bits, which almost always move together.
    pub const XY: u8 = XF | YF;
}

/// The architectural register file, shadow set and `WZ` included.
///
/// Public and `Copy` because a debugger, a tracer and a test all want to read
/// it out and put it back — this is the surface a future gdbstub serialises
/// (`ROADMAP.md` §9's debug story), and [`Reg`] enumerates it by name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Regs {
    /// Accumulator.
    pub a: u8,
    /// Flags. See [`flags`].
    pub f: u8,
    /// General purpose `B`, and the counter `DJNZ` and block I/O decrement.
    pub b: u8,
    /// General purpose `C`, and the low half of the `(C)` port address.
    pub c: u8,
    /// General purpose `D`.
    pub d: u8,
    /// General purpose `E`.
    pub e: u8,
    /// General purpose `H`.
    pub h: u8,
    /// General purpose `L`.
    pub l: u8,
    /// Index register `IX`.
    pub ix: u16,
    /// Index register `IY`.
    pub iy: u16,
    /// Stack pointer. The stack grows downwards and `PUSH` writes the high
    /// byte first.
    pub sp: u16,
    /// Program counter.
    pub pc: u16,
    /// Interrupt vector base: the high half of the mode 2 table address.
    pub i: u8,
    /// Memory refresh counter. Only the low seven bits count; bit 7 is a latch
    /// the program owns and the hardware increment never carries into it.
    pub r: u8,
    /// The internal address latch, `WZ` — usually called `MEMPTR`.
    ///
    /// Not in any Zilog document, and not optional: `BIT n,(HL)` copies bits 3
    /// and 5 of `W` into the flags, so a core that does not model this fails
    /// on real software.
    pub wz: u16,
    /// The shadow `AF'`, which only `EX AF,AF'` reaches.
    pub af_alt: u16,
    /// The shadow `BC'`.
    pub bc_alt: u16,
    /// The shadow `DE'`.
    pub de_alt: u16,
    /// The shadow `HL'`.
    pub hl_alt: u16,
}

macro_rules! pair {
    ($get:ident, $set:ident, $hi:ident, $lo:ident, $name:literal) => {
        #[doc = concat!("The ", $name, " pair.")]
        #[inline]
        #[must_use]
        pub const fn $get(&self) -> u16 {
            ((self.$hi as u16) << 8) | self.$lo as u16
        }

        #[doc = concat!("Overwrite the ", $name, " pair.")]
        #[inline]
        pub const fn $set(&mut self, value: u16) {
            self.$hi = (value >> 8) as u8;
            self.$lo = value as u8;
        }
    };
}

impl Regs {
    /// The state a cold power-on leaves behind, *before* the reset sequence.
    ///
    /// Zeroed rather than randomised: a real Z80 comes up with undefined
    /// registers, and determinism is a first-class mode (`ROADMAP.md` §0).
    #[must_use]
    pub const fn new() -> Regs {
        Regs {
            a: 0,
            f: 0,
            b: 0,
            c: 0,
            d: 0,
            e: 0,
            h: 0,
            l: 0,
            ix: 0,
            iy: 0,
            sp: 0,
            pc: 0,
            i: 0,
            r: 0,
            wz: 0,
            af_alt: 0,
            bc_alt: 0,
            de_alt: 0,
            hl_alt: 0,
        }
    }

    pair!(bc, set_bc, b, c, "`BC`");
    pair!(de, set_de, d, e, "`DE`");
    pair!(hl, set_hl, h, l, "`HL`");

    /// The `AF` pair.
    #[inline]
    #[must_use]
    pub const fn af(&self) -> u16 {
        ((self.a as u16) << 8) | self.f as u16
    }

    /// Overwrite the `AF` pair.
    #[inline]
    pub const fn set_af(&mut self, value: u16) {
        self.a = (value >> 8) as u8;
        self.f = value as u8;
    }

    /// Whether a flag is set.
    #[inline]
    #[must_use]
    pub const fn flag(&self, mask: u8) -> bool {
        self.f & mask != 0
    }
}

impl fmt::Display for Regs {
    /// The one-line form a trace log wants.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "AF:{:04x} BC:{:04x} DE:{:04x} HL:{:04x} IX:{:04x} IY:{:04x} \
             SP:{:04x} PC:{:04x} I:{:02x} R:{:02x} WZ:{:04x}",
            self.af(),
            self.bc(),
            self.de(),
            self.hl(),
            self.ix,
            self.iy,
            self.sp,
            self.pc,
            self.i,
            self.r,
            self.wz
        )
    }
}

/// One named register, for a debugger that works by name or index.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Reg {
    /// Accumulator and flags.
    Af,
    /// The `BC` pair.
    Bc,
    /// The `DE` pair.
    De,
    /// The `HL` pair.
    Hl,
    /// Index register `IX`.
    Ix,
    /// Index register `IY`.
    Iy,
    /// Stack pointer.
    Sp,
    /// Program counter.
    Pc,
    /// Interrupt vector base.
    I,
    /// Memory refresh counter.
    R,
    /// The internal address latch.
    Wz,
    /// Shadow `AF'`.
    AfAlt,
    /// Shadow `BC'`.
    BcAlt,
    /// Shadow `DE'`.
    DeAlt,
    /// Shadow `HL'`.
    HlAlt,
}

impl Reg {
    /// Every register, in the order a debugger should list them.
    pub const ALL: &'static [Reg] = &[
        Reg::Af,
        Reg::Bc,
        Reg::De,
        Reg::Hl,
        Reg::Ix,
        Reg::Iy,
        Reg::Sp,
        Reg::Pc,
        Reg::I,
        Reg::R,
        Reg::Wz,
        Reg::AfAlt,
        Reg::BcAlt,
        Reg::DeAlt,
        Reg::HlAlt,
    ];

    /// The register's name, lowercase, as gdb and the monitor spell it.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Reg::Af => "af",
            Reg::Bc => "bc",
            Reg::De => "de",
            Reg::Hl => "hl",
            Reg::Ix => "ix",
            Reg::Iy => "iy",
            Reg::Sp => "sp",
            Reg::Pc => "pc",
            Reg::I => "i",
            Reg::R => "r",
            Reg::Wz => "wz",
            Reg::AfAlt => "af'",
            Reg::BcAlt => "bc'",
            Reg::DeAlt => "de'",
            Reg::HlAlt => "hl'",
        }
    }

    /// How wide the register is.
    #[must_use]
    pub const fn width(self) -> Width {
        match self {
            Reg::I | Reg::R => Width::U8,
            _ => Width::U16,
        }
    }

    /// Read this register out of a register file.
    #[must_use]
    pub const fn get(self, regs: &Regs) -> u16 {
        match self {
            Reg::Af => regs.af(),
            Reg::Bc => regs.bc(),
            Reg::De => regs.de(),
            Reg::Hl => regs.hl(),
            Reg::Ix => regs.ix,
            Reg::Iy => regs.iy,
            Reg::Sp => regs.sp,
            Reg::Pc => regs.pc,
            Reg::I => regs.i as u16,
            Reg::R => regs.r as u16,
            Reg::Wz => regs.wz,
            Reg::AfAlt => regs.af_alt,
            Reg::BcAlt => regs.bc_alt,
            Reg::DeAlt => regs.de_alt,
            Reg::HlAlt => regs.hl_alt,
        }
    }

    /// Write this register into a register file, truncating to its width.
    pub const fn set(self, regs: &mut Regs, value: u16) {
        match self {
            Reg::Af => regs.set_af(value),
            Reg::Bc => regs.set_bc(value),
            Reg::De => regs.set_de(value),
            Reg::Hl => regs.set_hl(value),
            Reg::Ix => regs.ix = value,
            Reg::Iy => regs.iy = value,
            Reg::Sp => regs.sp = value,
            Reg::Pc => regs.pc = value,
            Reg::I => regs.i = value as u8,
            Reg::R => regs.r = value as u8,
            Reg::Wz => regs.wz = value,
            Reg::AfAlt => regs.af_alt = value,
            Reg::BcAlt => regs.bc_alt = value,
            Reg::DeAlt => regs.de_alt = value,
            Reg::HlAlt => regs.hl_alt = value,
        }
    }

    /// Look a register up by name.
    #[must_use]
    pub fn from_name(name: &str) -> Option<Reg> {
        Reg::ALL.iter().copied().find(|r| r.name() == name)
    }
}

impl fmt::Display for Reg {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

/// What one M-cycle asked of the bus.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum MCycle {
    /// An `M1` opcode fetch: a read at `PC`, then two T-states with the
    /// refresh address on the pins.
    Fetch,
    /// A memory read.
    Read,
    /// A memory write.
    Write,
    /// An I/O port read. Four T-states, because the Z80 inserts one wait
    /// state so peripherals need no `WAIT` logic of their own.
    PortRead,
    /// An I/O port write.
    PortWrite,
    /// An interrupt acknowledge: an `M1` whose byte comes from the
    /// interrupting device rather than from memory.
    Ack,
    /// An internal operation. No bus request; the address pins keep whatever
    /// the previous M-cycle left on them.
    ///
    /// The default, because a zeroed [`BusCycle`] describes nothing happening.
    #[default]
    Internal,
}

/// One M-cycle of bus activity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct BusCycle {
    /// What kind of M-cycle this was.
    pub kind: MCycle,
    /// The address driven for the request. For [`MCycle::Internal`] this is
    /// the stale address the pins were still holding.
    pub addr: u16,
    /// The byte transferred. Meaningless for [`MCycle::Internal`].
    pub value: u8,
    /// The refresh address driven during the second half of a fetch or
    /// acknowledge; zero otherwise.
    pub refresh: u16,
    /// How many T-states this M-cycle occupied.
    pub tstates: u8,
}

/// How many M-cycles [`CycleLog`] records before it gives up.
///
/// The longest single instruction is 23 T-states across eight M-cycles, so the
/// only way to overflow this is a run of redundant `$dd`/`$fd` prefixes —
/// legal, pointless, and not worth a heap allocation in the hot path.
pub const CYCLE_LOG_LEN: usize = 16;

/// The bus activity of one step.
///
/// Recorded unconditionally rather than behind a debug flag: it costs one
/// array store per M-cycle, and it is the only way to check a core's timing
/// against hardware instead of asserting it (`ROADMAP.md` §0).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CycleLog {
    cycles: [BusCycle; CYCLE_LOG_LEN],
    len: u8,
    truncated: bool,
}

impl CycleLog {
    /// An empty log.
    #[must_use]
    pub const fn new() -> CycleLog {
        CycleLog {
            cycles: [BusCycle {
                kind: MCycle::Internal,
                addr: 0,
                value: 0,
                refresh: 0,
                tstates: 0,
            }; CYCLE_LOG_LEN],
            len: 0,
            truncated: false,
        }
    }

    /// The M-cycles recorded, in the order they happened.
    #[inline]
    #[must_use]
    pub fn cycles(&self) -> &[BusCycle] {
        &self.cycles[..self.len as usize]
    }

    /// Whether the step performed more M-cycles than the log can hold.
    #[inline]
    #[must_use]
    pub const fn truncated(&self) -> bool {
        self.truncated
    }

    /// Total T-states across the recorded M-cycles.
    #[must_use]
    pub fn tstates(&self) -> u32 {
        self.cycles().iter().map(|c| u32::from(c.tstates)).sum()
    }

    #[inline]
    pub(crate) fn clear(&mut self) {
        self.len = 0;
        self.truncated = false;
    }

    #[inline]
    pub(crate) fn push(&mut self, cycle: BusCycle) {
        match self.cycles.get_mut(self.len as usize) {
            Some(slot) => {
                *slot = cycle;
                self.len += 1;
            }
            None => self.truncated = true,
        }
    }
}

impl Default for CycleLog {
    fn default() -> Self {
        CycleLog::new()
    }
}

/// Which interrupt input was taken.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Interrupt {
    /// Maskable, level-sensitive, gated by `IFF1` and vectored by the mode.
    Int,
    /// Non-maskable, edge-sensitive, always vectored through `$0066`.
    Nmi,
}

/// How this particular part and board differ from the generic Z80.
///
/// Construction properties, never `#[cfg]`: one build of rsemu has to be able
/// to run a Master System *and* a CP/M box.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Config {
    /// The byte the undocumented `OUT (C),0` writes.
    ///
    /// `$00` on the NMOS Z80, `$ff` on the CMOS parts — the one place the two
    /// families visibly disagree, and the reason this is a property rather
    /// than a constant.
    pub out_c_zero: u8,
    /// What a read of an address or port nothing answers returns.
    ///
    /// A Z80 has no bus-error input, so a refused access cannot raise an
    /// exception: the data pins float and the CPU latches whatever is there.
    /// `$ff` matches a bus with pull-ups, which is the common case.
    pub floating_bus: u8,
    /// This core's identity in `MemAttrs::requester`, for an IOMMU or a
    /// per-master filter.
    pub requester: RequesterId,
}

impl Config {
    /// A plain NMOS Z80.
    pub const NMOS: Config = Config {
        out_c_zero: 0x00,
        floating_bus: 0xff,
        requester: RequesterId::ANONYMOUS,
    };

    /// A CMOS Z80 (Z84C00 and relatives): `OUT (C),0` writes `$ff` instead.
    pub const CMOS: Config = Config {
        out_c_zero: 0xff,
        ..Config::NMOS
    };

    /// Same configuration, with a different requester id.
    #[must_use]
    pub const fn with_requester(mut self, id: RequesterId) -> Self {
        self.requester = id;
        self
    }
}

impl Default for Config {
    fn default() -> Self {
        Config::NMOS
    }
}

/// The interrupt input pins and the acknowledge data bus, kept outside the
/// execution lock.
///
/// Deliberately atomics rather than fields under the mutex: a device asserting
/// `INT` from inside a write the CPU itself issued would otherwise re-enter
/// the CPU's own critical section, which is a deadlock under `native-std` and
/// a panic under `single` (`ROADMAP.md` §4.7).
#[derive(Debug)]
pub(crate) struct Lines {
    /// `INT` is level-sensitive: it is taken whenever it is asserted, `IFF1`
    /// is set, and the previous instruction was not `EI`.
    int: AtomicBool,
    /// The last level seen on `NMI`, for edge detection.
    nmi_level: AtomicBool,
    /// `NMI` is edge-sensitive: a high-going edge sets this latch, which stays
    /// set until the interrupt is serviced, however long that takes.
    nmi_latch: AtomicBool,
    /// The byte the interrupting device puts on the data bus during the
    /// acknowledge cycle: the mode 2 vector, or the `RST` opcode in mode 0.
    vector: AtomicU8,
}

impl Default for Lines {
    fn default() -> Self {
        Lines {
            int: AtomicBool::new(false),
            nmi_level: AtomicBool::new(false),
            nmi_latch: AtomicBool::new(false),
            // An idle bus with pull-ups reads as $ff, which in mode 0 is
            // `RST 38` — the historical default a machine gets for free.
            vector: AtomicU8::new(0xff),
        }
    }
}

impl Lines {
    fn set_int(&self, asserted: bool) {
        self.int.store(asserted, Ordering::Release);
    }

    fn irq_asserted(&self) -> bool {
        self.int.load(Ordering::Acquire)
    }

    /// Drive the `NMI` pin, latching a high-going edge.
    fn set_nmi(&self, asserted: bool) {
        let previous = self.nmi_level.swap(asserted, Ordering::AcqRel);
        if asserted && !previous {
            self.nmi_latch.store(true, Ordering::Release);
        }
    }

    fn nmi_pending(&self) -> bool {
        self.nmi_latch.load(Ordering::Acquire)
    }

    /// Consume the `NMI` latch, reporting whether it was set.
    fn take_nmi_pending(&self) -> bool {
        self.nmi_latch.swap(false, Ordering::AcqRel)
    }

    fn clear_nmi_latch(&self) {
        self.nmi_latch.store(false, Ordering::Release);
    }

    fn vector(&self) -> u8 {
        self.vector.load(Ordering::Acquire)
    }

    fn set_vector(&self, value: u8) {
        self.vector.store(value, Ordering::Release);
    }

    fn snapshot(&self) -> (bool, bool, bool, u8) {
        (
            self.irq_asserted(),
            self.nmi_level.load(Ordering::Acquire),
            self.nmi_pending(),
            self.vector(),
        )
    }

    fn restore(&self, (int, level, latch, vector): (bool, bool, bool, u8)) {
        self.int.store(int, Ordering::Release);
        self.nmi_level.store(level, Ordering::Release);
        self.nmi_latch.store(latch, Ordering::Release);
        self.vector.store(vector, Ordering::Release);
    }
}

/// Everything the interpreter needs to mutate, behind one lock.
#[derive(Debug)]
struct Session {
    state: State,
    space: Option<Arc<AddressSpace>>,
    io: Option<Arc<AddressSpace>>,
}

/// A Zilog Z80 core.
///
/// # Locking
///
/// Execution state sits behind one [`sync::Mutex`] at [`LockRank::BUS`]. That
/// rank, rather than `DEVICE`, because a CPU is a bus master: it holds this
/// lock while calling into device models, which take their own `DEVICE`-ranked
/// locks, which drive `WIRE`-ranked lines. The ladder runs in the direction
/// calls travel.
///
/// The interrupt pins are *not* under that lock: they are atomics, so a device
/// asserting `INT` from inside a write the CPU itself issued cannot re-enter
/// the CPU's own critical section.
#[derive(Debug)]
pub struct Z80 {
    cfg: Config,
    lines: Lines,
    session: sync::Mutex<Session>,
}

impl Z80 {
    /// A core in its power-on state, with no address space yet.
    ///
    /// Two-phase construction (`ROADMAP.md` §4.4): nothing observable happens
    /// until [`attach_space`](Z80::attach_space) and [`Device::realize`]. The
    /// first [`step`](Z80::step) runs the reset sequence.
    #[must_use]
    pub fn new(cfg: Config) -> Z80 {
        Z80 {
            cfg,
            lines: Lines::default(),
            session: sync::Mutex::with_rank(
                LockRank::BUS,
                Session {
                    state: State::new(),
                    space: None,
                    io: None,
                },
            ),
        }
    }

    /// Build one from machine-description properties.
    ///
    /// # Errors
    ///
    /// If a property has the wrong type or is out of range, or a property
    /// nothing here accepts was given — a typo'd property that was silently
    /// ignored is an afternoon lost.
    pub fn from_props(props: &Props) -> Result<Z80> {
        let mut r = props.reader();
        let cmos = r.or("cmos", false)?;
        let default = if cmos { Config::CMOS } else { Config::NMOS };
        let out_c_zero = r.or_range("out-c-zero", u64::from(default.out_c_zero), 0..=0xff)?;
        let floating = r.or_range("floating-bus", u64::from(default.floating_bus), 0..=0xff)?;
        r.finish()?;
        Ok(Z80::new(Config {
            out_c_zero: out_c_zero as u8,
            floating_bus: floating as u8,
            requester: RequesterId::ANONYMOUS,
        }))
    }

    /// This core's configuration.
    #[must_use]
    pub fn config(&self) -> Config {
        self.cfg
    }

    /// Give the core the memory address space it executes from.
    pub fn attach_space(&self, space: Arc<AddressSpace>) {
        self.session.lock().space = Some(space);
    }

    /// Give the core its **I/O** address space, which `IN` and `OUT` reach and
    /// nothing else does.
    ///
    /// Optional: a machine with no ports simply never calls this, and reads
    /// return [`Config::floating_bus`] rather than faulting.
    pub fn attach_io_space(&self, space: Arc<AddressSpace>) {
        self.session.lock().io = Some(space);
    }

    /// The memory address space this core executes from, if one is attached.
    #[must_use]
    pub fn space(&self) -> Option<Arc<AddressSpace>> {
        self.session.lock().space.clone()
    }

    /// The I/O address space, if one is attached.
    #[must_use]
    pub fn io_space(&self) -> Option<Arc<AddressSpace>> {
        self.session.lock().io.clone()
    }

    /// The register file.
    #[must_use]
    pub fn regs(&self) -> Regs {
        self.session.lock().state.regs
    }

    /// Overwrite the register file — a debugger, a test vector, a snapshot.
    pub fn set_regs(&self, regs: Regs) {
        self.session.lock().state.regs = regs;
    }

    /// Read one register by name.
    #[must_use]
    pub fn reg(&self, reg: Reg) -> u16 {
        reg.get(&self.session.lock().state.regs)
    }

    /// Write one register by name.
    pub fn set_reg(&self, reg: Reg, value: u16) {
        reg.set(&mut self.session.lock().state.regs, value);
    }

    /// T-states executed since power-on.
    #[must_use]
    pub fn cycles(&self) -> u64 {
        self.session.lock().state.cycles
    }

    /// The bus activity of the most recent [`step`](Z80::step).
    ///
    /// One entry per M-cycle, in order. This is what a bus-level trace, a
    /// logic-analyser view and the conformance runner all read; it is also the
    /// only honest way to check the core's timing rather than assert it.
    #[must_use]
    pub fn last_cycles(&self) -> CycleLog {
        self.session.lock().state.trace
    }

    /// Whether `HALT` has suspended the core.
    ///
    /// A halted Z80 is not stopped: it keeps issuing `M1` cycles so dynamic
    /// RAM stays refreshed, and [`step`](Z80::step) charges four T-states for
    /// each of them. Only an interrupt or a reset ends it.
    #[must_use]
    pub fn is_halted(&self) -> bool {
        self.session.lock().state.halted
    }

    /// Whether a reset sequence is still owed.
    #[must_use]
    pub fn reset_pending(&self) -> bool {
        self.session.lock().state.reset_pending
    }

    /// The two interrupt enable flip-flops, `IFF1` first.
    ///
    /// `IFF2` is `IFF1`'s backup across an `NMI`, and it is what `LD A,I`
    /// copies into the parity flag — which is the only way a program can read
    /// either of them.
    #[must_use]
    pub fn iff(&self) -> (bool, bool) {
        let s = self.session.lock();
        (s.state.iff1, s.state.iff2)
    }

    /// Set both interrupt enable flip-flops.
    pub fn set_iff(&self, iff1: bool, iff2: bool) {
        let mut s = self.session.lock();
        s.state.iff1 = iff1;
        s.state.iff2 = iff2;
    }

    /// The selected interrupt mode, 0 to 2.
    #[must_use]
    pub fn interrupt_mode(&self) -> u8 {
        self.session.lock().state.im
    }

    /// Select the interrupt mode, as `IM n` would.
    ///
    /// # Errors
    ///
    /// If `mode` is not 0, 1 or 2.
    pub fn set_interrupt_mode(&self, mode: u8) -> Result<()> {
        if mode > 2 {
            return Err(Error::Property(alloc::format!(
                "interrupt mode {mode} does not exist; the Z80 has modes 0, 1 and 2"
            )));
        }
        self.session.lock().state.im = mode;
        Ok(())
    }

    /// How many accesses the address spaces refused, and where the last one
    /// was.
    ///
    /// A Z80 has no bus-error input, so a refused access cannot raise an
    /// exception: the read returns [`Config::floating_bus`], which is what a
    /// bus with pull-ups does. This counter is how that becomes visible
    /// instead of silent.
    #[must_use]
    pub fn bus_faults(&self) -> (u64, u16) {
        let s = self.session.lock();
        (s.state.faults, s.state.last_fault)
    }

    /// Drive the `INT` pin. Level-sensitive: it is taken while asserted,
    /// `IFF1` is set, and the previous instruction was not `EI`.
    ///
    /// `asserted` is the logical level, not the pin's: a real `/INT` is
    /// active-low, and inverting it belongs to whatever models the wire.
    pub fn set_int(&self, asserted: bool) {
        self.lines.set_int(asserted);
    }

    /// Whether `INT` is currently asserted.
    #[must_use]
    pub fn int_asserted(&self) -> bool {
        self.lines.irq_asserted()
    }

    /// Drive the `NMI` pin. Edge-sensitive: a high-going edge latches, and the
    /// latch survives until the interrupt is taken.
    pub fn set_nmi(&self, asserted: bool) {
        self.lines.set_nmi(asserted);
    }

    /// A complete `NMI` pulse, for a caller that does not model the pin's
    /// level.
    pub fn pulse_nmi(&self) {
        self.lines.set_nmi(true);
        self.lines.set_nmi(false);
    }

    /// Whether an `NMI` edge is latched and not yet serviced.
    #[must_use]
    pub fn nmi_pending(&self) -> bool {
        self.lines.nmi_pending()
    }

    /// Set the byte the interrupting device puts on the data bus during the
    /// acknowledge cycle.
    ///
    /// In mode 2 this is the low half of the vector-table address; in mode 0
    /// it is an opcode, conventionally an `RST`. Defaults to `$ff`, which is
    /// what an undriven bus with pull-ups reads as — and `RST 38` in mode 0.
    pub fn set_interrupt_vector(&self, vector: u8) {
        self.lines.set_vector(vector);
    }

    /// The byte the acknowledge cycle will read.
    #[must_use]
    pub fn interrupt_vector(&self) -> u8 {
        self.lines.vector()
    }

    /// Request a reset sequence without changing any register.
    ///
    /// The sequence runs on the next [`step`](Z80::step), because a reset is a
    /// signal rather than a method call.
    pub fn request_reset(&self) {
        self.session.lock().state.reset_pending = true;
    }

    /// Execute one reset sequence, interrupt sequence, halt cycle or
    /// instruction.
    ///
    /// Returns the T-states charged: zero only if no address space is
    /// attached, which the caller must treat as "stop", not "retry". A halted
    /// core still returns four, because it is still refreshing.
    pub fn step(&self) -> u64 {
        let mut session = self.session.lock();
        // Destructured so the two spaces can be borrowed while `state` is
        // borrowed mutably: they are different fields. Cloning the `Arc`s
        // instead would put two atomic refcount updates on the path of every
        // instruction, for a lifetime the lock already guarantees.
        let Session { state, space, io } = &mut *session;
        let io = io.as_deref();
        let Some(space) = space.as_deref() else {
            return 0;
        };
        Exec::new(state, space, io, &self.cfg, &self.lines).step()
    }

    /// Execute until at least `budget` T-states have been charged.
    ///
    /// Returns the T-states actually used, which overshoots by at most one
    /// instruction — a Z80 cannot be stopped mid-instruction, and pretending
    /// otherwise is how a scheduler ends up with a CPU in an impossible state.
    pub fn run(&self, budget: u64) -> u64 {
        let mut used = 0;
        while used < budget {
            let n = self.step();
            if n == 0 {
                break;
            }
            used += n;
        }
        used
    }

    /// Disassemble `count` instructions starting at `pc`, reading guest memory
    /// with debug attributes.
    ///
    /// Debug attributes are the point: a monitor listing the code around PC
    /// must not pop a FIFO or clear a status bit on the way (`ROADMAP.md`
    /// §15, invariant 5).
    #[must_use]
    pub fn disassemble(&self, pc: u16, count: usize) -> Vec<disasm::Disassembled> {
        let Some(space) = self.space() else {
            return Vec::new();
        };
        disasm::disassemble_run(pc, count, |addr| {
            space
                .read(u64::from(addr), Width::U8, MemAttrs::DEBUG)
                .ok()
                .map(|v| v as u8)
        })
    }
}

/// The `cpu.z80` device class.
pub static CLASS: DeviceClass = DeviceClass {
    name: "cpu.z80",
    version: 1,
    summary: "Zilog Z80 8-bit CPU core, cycle-accurate interpreter",
    properties: &[
        PropertySpec {
            name: "cmos",
            kind: ValueKind::Bool,
            required: false,
            summary: "select the CMOS part, whose OUT (C),0 writes $ff instead of $00",
        },
        PropertySpec {
            name: "out-c-zero",
            kind: ValueKind::Uint,
            required: false,
            summary: "the byte the undocumented OUT (C),0 writes, overriding the part default",
        },
        PropertySpec {
            name: "floating-bus",
            kind: ValueKind::Uint,
            required: false,
            summary: "what a read nothing answers returns; $ff is a bus with pull-ups",
        },
    ],
    construct: |props| Ok(Box::new(Z80::from_props(props)?)),
};

/// Add this core's class to a registry.
///
/// Registration is explicit per feature rather than link-time magic
/// (`ROADMAP.md` §4.4), so the machine assembly layer calls this from its own
/// `#[cfg(feature = "cpu-z80")]` arm.
///
/// # Errors
///
/// If something already claimed the name.
pub fn register(reg: &mut Registry) -> Result<()> {
    reg.add(&CLASS)
}

impl Device for Z80 {
    fn class(&self) -> &'static DeviceClass {
        &CLASS
    }

    fn realize(&self, ctx: &mut RealizeCtx<'_>) -> Result<()> {
        // A CPU with no address space cannot fetch, and failing here is the
        // difference between a config error and a machine that runs zero
        // instructions and says nothing.
        if self.session.lock().space.is_none() {
            return Err(ctx.error("no address space attached to this core"));
        }
        Ok(())
    }

    fn reset(&self, kind: ResetKind) {
        let mut session = self.session.lock();
        if kind == ResetKind::Cold {
            session.state = State::new();
        } else {
            // A warm reset is a pulse on the RESET pin: the sequence itself
            // clears PC, I, R and both flip-flops, and everything else keeps
            // its value.
            session.state.reset_pending = true;
            session.state.halted = false;
        }
        drop(session);
        if kind == ResetKind::Cold {
            self.lines.restore((false, false, false, 0xff));
        } else {
            // The input *levels* belong to whatever drives them, not to the
            // CPU — clearing them here would make a reset lie about the
            // machine. The edge latch is internal, so it goes.
            self.lines.clear_nmi_latch();
        }
    }

    fn save(&self, w: &mut ChunkWriter<'_>) -> Result<()> {
        let state = self.session.lock().state;
        let r = state.regs;
        for value in [
            r.af(),
            r.bc(),
            r.de(),
            r.hl(),
            r.ix,
            r.iy,
            r.sp,
            r.pc,
            r.wz,
            r.af_alt,
            r.bc_alt,
            r.de_alt,
            r.hl_alt,
        ] {
            w.write_u16(value)?;
        }
        w.write_u8(r.i)?;
        w.write_u8(r.r)?;
        w.write_bool(state.iff1)?;
        w.write_bool(state.iff2)?;
        w.write_u8(state.im)?;
        w.write_bool(state.halted)?;
        w.write_bool(state.ei_pending)?;
        w.write_bool(state.after_ld_ir)?;
        w.write_u8(state.q)?;
        w.write_u64(state.cycles)?;
        w.write_bool(state.reset_pending)?;
        w.write_u64(state.faults)?;
        w.write_u16(state.last_fault)?;
        let (int, nmi_level, nmi_latch, vector) = self.lines.snapshot();
        w.write_bool(int)?;
        w.write_bool(nmi_level)?;
        w.write_bool(nmi_latch)?;
        w.write_u8(vector)?;
        Ok(())
    }

    fn load(&self, r: &mut ChunkReader<'_>) -> Result<()> {
        // Derived state is never serialized (invariant 3): the cycle log
        // describes the step that is already over.
        let mut state = State::new();
        let regs = &mut state.regs;
        regs.set_af(r.read_u16()?);
        regs.set_bc(r.read_u16()?);
        regs.set_de(r.read_u16()?);
        regs.set_hl(r.read_u16()?);
        regs.ix = r.read_u16()?;
        regs.iy = r.read_u16()?;
        regs.sp = r.read_u16()?;
        regs.pc = r.read_u16()?;
        regs.wz = r.read_u16()?;
        regs.af_alt = r.read_u16()?;
        regs.bc_alt = r.read_u16()?;
        regs.de_alt = r.read_u16()?;
        regs.hl_alt = r.read_u16()?;
        regs.i = r.read_u8()?;
        regs.r = r.read_u8()?;
        state.iff1 = r.read_bool()?;
        state.iff2 = r.read_bool()?;
        state.im = r.read_u8()?;
        if state.im > 2 {
            return Err(Error::State(alloc::format!(
                "snapshot names interrupt mode {}, which does not exist",
                state.im
            )));
        }
        state.halted = r.read_bool()?;
        state.ei_pending = r.read_bool()?;
        state.after_ld_ir = r.read_bool()?;
        state.q = r.read_u8()?;
        state.cycles = r.read_u64()?;
        state.reset_pending = r.read_bool()?;
        state.faults = r.read_u64()?;
        state.last_fault = r.read_u16()?;
        let int = r.read_bool()?;
        let nmi_level = r.read_bool()?;
        let nmi_latch = r.read_bool()?;
        let vector = r.read_u8()?;
        self.session.lock().state = state;
        self.lines.restore((int, nmi_level, nmi_latch, vector));
        Ok(())
    }
}

impl Initiator for Z80 {
    fn requester(&self) -> RequesterId {
        self.cfg.requester
    }
}

/// One of the CPU's two interrupt inputs, as something a [`Wire`] can drive.
///
/// A wire hands each sink the level of the *driver that changed*, not the
/// resolved level of the net, because a net with several drivers is resolved
/// by whoever cares. A Z80 machine's `/INT` line typically has several, so
/// this keeps a [`FanIn`] and wire-ORs them — which is what the
/// open-collector line does in hardware.
///
/// [`Wire`]: crate::core::wire::Wire
#[derive(Debug)]
pub struct InterruptPin {
    cpu: Arc<Z80>,
    which: Interrupt,
    inputs: FanIn,
    resolve: Resolve,
}

impl InterruptPin {
    /// Connect `which` pin of `cpu` to a net driven by `sources`.
    ///
    /// Wire-OR by default: any source asserting asserts the pin, which is how
    /// an open-collector interrupt line behaves.
    #[must_use]
    pub fn new(cpu: Arc<Z80>, which: Interrupt, sources: &[WireId]) -> InterruptPin {
        InterruptPin {
            cpu,
            which,
            inputs: FanIn::new(sources),
            resolve: Resolve::Or,
        }
    }

    /// The same pin with an explicit resolution rule.
    #[must_use]
    pub fn with_resolve(mut self, resolve: Resolve) -> Self {
        self.resolve = resolve;
        self
    }

    /// Which pin this is.
    #[must_use]
    pub fn which(&self) -> Interrupt {
        self.which
    }

    /// The per-source levels currently seen.
    #[must_use]
    pub fn inputs(&self) -> &FanIn {
        &self.inputs
    }
}

impl WireSink for InterruptPin {
    fn set_level(&self, src: WireId, _line: u32, level: Level) {
        self.inputs.set(src, level);
        let asserted = self.inputs.resolve(self.resolve).is_high();
        match self.which {
            Interrupt::Int => self.cpu.set_int(asserted),
            Interrupt::Nmi => self.cpu.set_nmi(asserted),
        }
    }
}

/// A description of this core's base page for `rsemu describe cpu.z80`.
///
/// Built from [`isa::BASE`], so it cannot drift from what the interpreter
/// implements.
#[must_use]
pub fn describe_isa() -> String {
    use core::fmt::Write as _;
    let mut out = String::new();
    for opcode in 0..=255u8 {
        let insn = isa::decode(opcode);
        let mark = if insn.class.is_documented() { ' ' } else { '*' };
        let _ = writeln!(
            out,
            "{opcode:02x} {mark}{:<10} {}",
            disasm::mnemonic_and_operands(insn),
            insn.op.summary()
        );
    }
    out
}