m68k 0.7.2

A safe Rust M68000 family CPU emulator
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
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
//! Architectural CPU state, configuration, and memory-access helpers.

use super::execute::RUN_MODE_BERR_AERR_RESET;
use super::memory::{AddressBus, BusFaultKind};
use super::op_cache::CachedOp;
use super::types::CpuType;
use crate::fpu::FloatX80;

#[cfg(feature = "serde")]
fn precise_bus_default() -> bool {
    true
}

/// Flag constants for SR bits.
pub const XFLAG_SET: u32 = 0x100;
/// Internal representation of a set negative (N) flag.
pub const NFLAG_SET: u32 = 0x80;
/// Internal representation of a set overflow (V) flag.
pub const VFLAG_SET: u32 = 0x80;
/// Internal representation of a set carry (C) flag.
pub const CFLAG_SET: u32 = 0x100;
/// Internal representation of supervisor mode.
pub const SFLAG_SET: u32 = 4;
/// Internal representation of the 68020+ master-stack bit.
pub const MFLAG_SET: u32 = 2;

/// Function codes for memory access.
pub const FC_USER_DATA: u32 = 1;
/// User-program function code.
pub const FC_USER_PROGRAM: u32 = 2;
/// Supervisor-data function code.
pub const FC_SUPERVISOR_DATA: u32 = 5;
/// Supervisor-program function code.
pub const FC_SUPERVISOR_PROGRAM: u32 = 6;

/// The main CPU state structure.
///
/// Public fields expose architectural registers and host-visible
/// configuration. With the `serde` feature, state that affects subsequent
/// architectural behavior and timing is serialized; runtime-only decode
/// tables, FastMem pointers, fault-delivery scratch state, and trace caches
/// are skipped and reconstructed when execution resumes.
#[derive(Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CpuCore {
    // ========== Registers ==========
    /// Data and Address registers (D0-D7, A0-A7)
    pub dar: [u32; 16],
    /// Saved registers for bus/address error recovery
    pub dar_save: [u32; 16],
    /// Saved SR for bus/address error recovery (captured at start of instruction).
    pub sr_save: u16,
    /// Previous program counter
    pub ppc: u32,
    /// Program counter
    pub pc: u32,
    /// Stack pointers: [USP, _, _, _, ISP, _, MSP, _]
    /// Index: s_flag | ((s_flag >> 1) & m_flag)
    pub sp: [u32; 8],
    /// Vector Base Register (68010+)
    pub vbr: u32,
    /// Source Function Code (68010+)
    pub sfc: u32,
    /// Destination Function Code (68010+)
    pub dfc: u32,
    /// Cache Control Register (68020+). Only the persistent control bits
    /// are stored; the write-only clear strobes land in
    /// `cacr_pending_ops` for the host to act on.
    pub cacr: u32,
    /// Cache Address Register (68020+)
    pub caar: u32,
    /// CACR clear strobes (CI/CEI, and CD/CED on the 68030) accumulated
    /// since the host last drained them. These bits trigger a cache
    /// invalidation when written and always read back as zero, so they
    /// are latched here instead of in `cacr`.
    pub cacr_pending_ops: u32,
    /// Instruction Transparent Translation 0 (68040)
    pub itt0: u32,
    /// Instruction Transparent Translation 1 (68040)
    pub itt1: u32,
    /// Data Transparent Translation 0 (68040)
    pub dtt0: u32,
    /// Data Transparent Translation 1 (68040)
    pub dtt1: u32,
    /// Instruction Register (current opcode)
    pub ir: u32,
    // ========== FPU Registers (68881/68882/68040) ==========
    /// FPU Data Registers (FP0-FP7) - 80-bit extended precision.
    pub fpr: [FloatX80; 8],
    /// FPU Instruction Address Register
    pub fpiar: u32,
    /// FPU Status Register
    pub fpsr: u32,
    /// FPU Control Register
    pub fpcr: u32,

    // ========== Flags (stored separately for speed) ==========
    /// Trace 1 flag (T1 bit of SR)
    pub t1_flag: u32,
    /// Trace 0 flag (T0 bit of SR, 68020+)
    pub t0_flag: u32,
    /// Supervisor flag (0 or SFLAG_SET=4)
    pub s_flag: u32,
    /// Master/Interrupt state (0 or MFLAG_SET=2, 68020+)
    pub m_flag: u32,
    /// Extend flag (X)
    pub x_flag: u32,
    /// Negative flag (N)
    pub n_flag: u32,
    /// Zero flag (inverted: 0 = Z set, non-zero = Z clear)
    pub not_z_flag: u32,
    /// Overflow flag (V)
    pub v_flag: u32,
    /// Carry flag (C)
    pub c_flag: u32,
    /// Interrupt mask (I0-I2)
    pub int_mask: u32,

    // ========== Interrupt State ==========
    /// Current interrupt level
    pub int_level: u32,
    /// Stopped state (STOP instruction)
    pub stopped: u32,
    /// Change-of-flow flag for T0 trace (set by BRA, JMP, JSR, RTS, etc.)
    pub change_of_flow: bool,

    // ========== 68010 loop mode ==========
    /// A DBcc that branches -4 to a loopable one-word instruction holds the
    /// pair in the prefetch queue and re-executes without instruction
    /// fetches (68010 loop mode). While set, the queue is reseeded from the
    /// held words each iteration and the end-of-instruction top-up is
    /// suppressed; any exception or interrupt (jump_vector) drops the mode.
    #[cfg_attr(feature = "serde", serde(default))]
    pub loop_mode: bool,
    /// The looped one-word body instruction (queue word 0 at entry).
    #[cfg_attr(feature = "serde", serde(default))]
    pub loop_body_word: u16,
    /// The looping DBcc opcode (queue word 1 at entry).
    #[cfg_attr(feature = "serde", serde(default))]
    pub loop_dbcc_word: u16,

    // ========== Prefetch (Part E.1, 68000 only) ==========
    /// The 68000's two-word instruction prefetch queue (IRD/IRC model).
    ///
    /// `prefetch_queue[0..prefetch_count]` hold the words at `pc`,
    /// `pc + 2`. Consuming a word (see `read_imm_16`) takes from the queue
    /// without a bus access; when the queue is empty the word is fetched
    /// directly. At the end of every instruction the queue is topped back up
    /// to two words (`top_up_prefetch`) -- the prefetch bus reads real
    /// hardware performs during instruction execution. Flow-change
    /// instructions skip the top-up: they discard the queue and refill it
    /// from the branch target instead (`full_prefetch`), which is why taken
    /// branches cost two bus reads at the target and why words prefetched
    /// past a taken branch are discarded.
    pub prefetch_queue: [u16; 2],
    /// Number of valid words in `prefetch_queue` (0..=2), starting at `pc`.
    pub prefetch_count: u8,
    /// Microcode mode: when set, instruction-stream consumes skip their
    /// accompanying prefetch ("np") bus read. Flow-change instructions set
    /// this while consuming displacement/address words on paths that will
    /// discard the queue and refill from the branch target -- real hardware
    /// never prefetches ahead of a stream it is about to abandon.
    pub consume_without_prefetch: bool,
    /// Internal (non-bus) CPU clocks accumulated since the last bus access
    /// (Part E.2 precise timing). Reported to the host via
    /// `AddressBus::sync` immediately before the next access.
    pub pending_sync_clocks: u32,
    /// Whether instruction execution must preserve transaction-level bus
    /// ordering and timing. Precise entry points keep this enabled; the
    /// explicitly optimized `run_batch` path disables it for the batch.
    #[cfg_attr(feature = "serde", serde(skip, default = "precise_bus_default"))]
    pub(crate) precise_bus: bool,

    // ========== CPU Configuration ==========
    /// CPU type
    pub cpu_type: CpuType,
    /// Address mask (24-bit for 68000, 32-bit for 68020+)
    pub address_mask: u32,
    /// SR mask (implemented bits)
    pub sr_mask: u32,
    /// Instruction mode
    pub instr_mode: u32,
    /// Run mode (normal, bus error, address error)
    pub run_mode: u32,
    /// True while processing an exception (for double-fault detection)
    pub exception_processing: bool,
    /// Vector taken by the instruction currently being timed. Unlike the
    /// debugger field below, this is cleared before every opcode fetch.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub(crate) instruction_exception_vector: Option<u32>,
    /// True when the bit-field instruction currently being timed spanned a
    /// five-byte memory window (MC68020UM 8.2.14 bills those one operand
    /// cycle higher than fields within four bytes). Set by the memory-form
    /// bit-field executor, consumed by the 020 timing model on retirement.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub(crate) bitfield_mem_wide_span: bool,
    /// Vector number of the most recent exception entry (trap, fault, or
    /// interrupt -- everything routed through `jump_vector`), for the
    /// host debugger's exception catchpoints. Polled and cleared by the
    /// host wrapper; transient debug state, never serialized.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub last_exception_vector: Option<u32>,

    // ========== MMU State ==========
    /// Has PMMU
    pub has_pmmu: bool,
    /// PMMU enabled
    pub pmmu_enabled: bool,
    /// Cached `cpu_type` is pre-68020. Updated in `set_cpu_type`.
    pub is_pre_68020: bool,
    /// FPU just reset
    pub fpu_just_reset: bool,
    /// Whether a floating-point coprocessor is attached (68020/030 with an
    /// external 68881/68882). When false, cpID-1 F-line operations raise
    /// Line-F. The 040/060 model FPU absence separately (EC/LC types and
    /// PCR.DFP), so this stays true for them.
    pub fpu_present: bool,
    /// Reset cycles counter
    pub reset_cycles: u32,

    // ========== Cycle Timing ==========
    /// Cycles for Bcc not taken (byte)
    pub cyc_bcc_notake_b: i32,
    /// Cycles for Bcc not taken (word)
    pub cyc_bcc_notake_w: i32,
    /// Cycles for DBcc false, no expiration
    pub cyc_dbcc_f_noexp: i32,
    /// Cycles for DBcc false, expiration
    pub cyc_dbcc_f_exp: i32,
    /// Cycles for Scc register true
    pub cyc_scc_r_true: i32,
    /// Cycles per word for MOVEM
    pub cyc_movem_w: i32,
    /// Cycles per long for MOVEM
    pub cyc_movem_l: i32,
    /// Cycles per shift count
    pub cyc_shift: i32,
    /// Cycles for RESET instruction
    pub cyc_reset: i32,

    // ========== Virtual IRQ ==========
    /// Reserved virtual-interrupt state retained for host compatibility.
    ///
    /// Normal interrupt delivery uses [`CpuCore::set_irq`].
    pub virq_state: u32,
    /// Reserved pending-NMI latch retained for host compatibility.
    ///
    /// Level-7 interrupt delivery uses [`CpuCore::set_irq`].
    pub nmi_pending: u32,

    // ========== MMU Registers ==========
    // One canonical register set is shared by the 68030 and 68040 paths so the
    // page-table walker and the register writes can never desync. The 68040
    // root pointers (URP/SRP) overload the CRP/SRP address slots: `mmu_crp_aptr`
    // is the CRP on the 030 and the URP on the 040, `mmu_srp_aptr` is the SRP on
    // both. The two formats never coexist (the walker dispatches on `cpu_type`),
    // and the 040 root pointers carry no limit longword, so the 040 ignores the
    // `*_limit` fields.
    /// 68030 CRP address pointer, or the 68040/68060 user root pointer.
    pub mmu_crp_aptr: u32,
    /// 68030 CRP limit and descriptor-mode longword.
    pub mmu_crp_limit: u32,
    /// Supervisor root-pointer address for the 68030, 68040, and 68060.
    pub mmu_srp_aptr: u32,
    /// 68030 SRP limit and descriptor-mode longword.
    pub mmu_srp_limit: u32,
    /// Translation Control register (68030 PMOVE; 68040/68060 MOVEC).
    pub mmu_tc: u32,
    /// MMU Status Register; its bit layout follows [`CpuCore::cpu_type`].
    pub mmu_sr: u32,
    // 68030 Transparent Translation Registers
    /// 68030 Transparent Translation Register 0.
    pub mmu_tt0: u32,
    /// 68030 Transparent Translation Register 1.
    pub mmu_tt1: u32,
    // 68040-specific MMU registers
    /// 68040 Data Access Control Register 0 (MOVEC selector `0x008`).
    pub dacr0: u32,
    /// 68040 Data Access Control Register 1 (MOVEC selector `0x009`).
    pub dacr1: u32,
    /// 68040 Instruction Access Control Register 0 (MOVEC selector `0x00A`).
    pub iacr0: u32,
    /// 68040 Instruction Access Control Register 1 (MOVEC selector `0x00B`).
    pub iacr1: u32,
    // 68060-specific control registers
    /// Processor Configuration Register (MOVEC 0x808): identification and
    /// revision in the high half (read-only), EDEBUG/DFP/ESS in the low bits.
    pub pcr: u32,
    /// Bus Control Register (MOVEC 0x008 on the 060 only; the same code is
    /// DACR0 on the 68040). Stored, not behaviorally modeled.
    pub buscr: u32,
    /// Address Translation Cache: a pure cache of recent page-table walks, so it
    /// is not serialized (restored empty) and is flushed on any mapping change.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub atc: crate::mmu::Atc,
    /// Cause of the MMU fault currently being delivered (set by
    /// handle_mmu_fault, consumed while composing the 68060 FSLW); plain
    /// physical bus errors leave it None. Transient within one exception.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub(crate) pending_fault_cause: Option<crate::mmu::MmuFaultCause>,
    /// Function code forced for the current data access: MOVES reads and
    /// writes carry SFC/DFC instead of the CPU-state-derived code, and the
    /// MMU translates in that address space (the 68030 FCL table level and
    /// TTR matching see the alternate code; on the 040 it selects URP vs
    /// SRP). None for ordinary accesses; transient within one instruction.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub(crate) mmu_fc_override: Option<u8>,
    /// One-shot faulted-read completion, from an RTE of a 68030 bus-fault
    /// frame whose handler cleared the SSW DF bit and supplied the result
    /// in the data input buffer: (logical address, value). Real silicon
    /// continues the instruction using that value instead of rerunning the
    /// data cycle (mmu.library emulates lazily-zeroed pages this way); this
    /// restart-model core re-executes the instruction and substitutes the
    /// value on its matching data read.
    pub(crate) mmu_read_override: Option<(u32, u32)>,
    /// One-shot suppressed data write: the DF-cleared write-fault analogue
    /// of `mmu_read_override` -- the re-executed instruction's write to
    /// this logical address is discarded (the handler already completed or
    /// absorbed it).
    pub(crate) mmu_write_suppress: Option<u32>,
    /// Data value of the most recent data write, captured so a write fault
    /// can stack it in the 030 frame's data output buffer (the handler
    /// completes the write from there).
    pub(crate) pending_fault_wdata: u32,
    /// Handler-entry state captured when a mid-instruction fault dispatch
    /// completes: (PC, SR, D0-D7/A0-A7). The aborted instruction's
    /// remaining execution is suppressed via `faulted()` on the bus side,
    /// but its register updates still land -- a JSR/RTS assigns `pc` on
    /// the way out and a `movem -(a7)` keeps stepping the (now
    /// supervisor) stack pointer -- which would corrupt the handler's
    /// entry state. The run loop re-asserts this snapshot when it clears
    /// the fault state. Transient within one instruction boundary.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub(crate) fault_resume: Option<(u32, u16, [u32; 16])>,

    // ========== Execution State ==========
    /// Remaining cycles in current timeslice
    pub cycles_remaining: i32,
    /// Initial cycles for timeslice
    pub initial_cycles: i32,
    /// Opcode-indexed decode table (lazily allocated, one entry per
    /// possible opcode word). Dropped when `cpu_type` changes; immune to
    /// self-modifying code since the fetched opcode itself is the index.
    /// Fixed-size array so `u16` indexing needs no bounds check.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub(crate) decode_table: Option<Box<[CachedOp; super::op_cache::DECODE_TABLE_SIZE]>>,

    // ========== Fastmem window (batch execution only) ==========
    // Captured from `AddressBus::fast_mem` on entry to `run_batch` and
    // cleared on exit; zero `fm_len` disables all fastmem paths. Stored
    // as a usize (not a pointer) so `CpuCore` stays `Send`.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub(crate) fm_ptr: usize,
    #[cfg_attr(feature = "serde", serde(skip))]
    pub(crate) fm_base: u32,
    #[cfg_attr(feature = "serde", serde(skip))]
    pub(crate) fm_len: u32,

    // ========== Trace-JIT hot-loop filters ==========
    // Small PC sets (entries hold a PC or `TRACE_PC_NONE`). They keep
    // tight loops — including ones with several backward branches, like
    // call/return pairs — from paying a thread-local + cache-slot probe
    // on every backward branch: `trace_record_skip` holds recently
    // recorded trace targets (re-recording is a no-op), and
    // `trace_probe_skip` holds targets the JIT has rejected (probing them
    // can't succeed). The trace JIT resets them when it invalidates a
    // trace, so eviction can't wedge them.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub(crate) trace_record_skip: [u32; 4],
    #[cfg_attr(feature = "serde", serde(skip))]
    pub(crate) trace_probe_skip: [u32; 4],
    #[cfg_attr(feature = "serde", serde(skip))]
    pub(crate) trace_record_skip_at: u8,
    #[cfg_attr(feature = "serde", serde(skip))]
    pub(crate) trace_probe_skip_at: u8,
    /// True while the trace JIT is recording an executed multi-block path.
    /// Kept on the CPU so the normal instruction loop avoids a TLS lookup
    /// when no recording is active.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub(crate) trace_recording: bool,

    /// 68060 pipeline timing state: the branch cache (and, with pairing,
    /// the pending pOEP head). Serialized - it changes cycle counts.
    pub oep060: crate::core::timing_060::Oep060Timing,

    /// 68060 escape hatch: execute the instructions the 060 removed from
    /// silicon (MOVEP, CHK2/CMP2, CAS2, misaligned CAS, 64-bit MUL/DIV, and
    /// the unimplemented FPU subset) natively instead of trapping for the
    /// OS-side 68060 software package. False = faithful traps.
    pub emulate_unimplemented_060: bool,

    /// When enabled, use SingleStepTests/MAME-derived semantics for a few edge cases where
    /// Musashi and MAME fixtures intentionally differ (notably BCD "invalid digit" behavior and
    pub sst_m68000_compat: bool,
}

// CACR bit assignments (68020/68030). The 68040 redefines CACR (IE/DE
// enables only, with CINV/CPUSH instructions doing invalidation); its bits
// are below (CACR_040_*).
/// Enable instruction cache.
pub const CACR_EI: u32 = 1 << 0;
/// Freeze instruction cache (hits served, misses do not allocate).
pub const CACR_FI: u32 = 1 << 1;
/// Clear instruction cache entry indexed by CAAR (write-only strobe).
pub const CACR_CEI: u32 = 1 << 2;
/// Clear instruction cache (write-only strobe).
pub const CACR_CI: u32 = 1 << 3;
/// Instruction burst enable (68030; stored, no timing effect here).
pub const CACR_IBE: u32 = 1 << 4;
/// Enable data cache (68030).
pub const CACR_ED: u32 = 1 << 8;
/// Freeze data cache (68030).
pub const CACR_FD: u32 = 1 << 9;
/// Clear data cache entry indexed by CAAR (68030; write-only strobe).
pub const CACR_CED: u32 = 1 << 10;
/// Clear data cache (68030; write-only strobe).
pub const CACR_CD: u32 = 1 << 11;
/// Data burst enable (68030; stored, no timing effect here).
pub const CACR_DBE: u32 = 1 << 12;
/// Write allocate (68030; stored, the host model is write-through).
pub const CACR_WA: u32 = 1 << 13;

// CACR bit assignments (68040). The 68040 CACR has only two defined bits -
// the cache enables - and no freeze/clear strobes: invalidation is done with
// the CINV/CPUSH instructions instead (see decode.rs). All other bits are
// reserved and read back as zero.
/// Enable instruction cache (68040).
pub const CACR_040_IE: u32 = 1 << 15;
/// Enable data cache (68040).
pub const CACR_040_DE: u32 = 1 << 31;

// CACR bit assignments (68060). The cache enables sit at the 68040
// positions; the 060 adds branch-cache and store-buffer controls. The
// branch-cache clears (CABC/CUBC) are write-only strobes.
/// Enable data cache (68060).
pub const CACR_060_EDC: u32 = 1 << 31;
/// No allocate mode, data cache (68060; stored only).
pub const CACR_060_NAD: u32 = 1 << 30;
/// Enable store buffer (68060; stored only - the host bills writes at bus rate).
pub const CACR_060_ESB: u32 = 1 << 29;
/// Disable CPUSH invalidation, data (68060; stored only).
pub const CACR_060_DPI: u32 = 1 << 28;
/// Half-cache operation mode, data (68060; stored only).
pub const CACR_060_FOC: u32 = 1 << 27;
/// Enable branch cache (68060).
pub const CACR_060_EBC: u32 = 1 << 23;
/// Clear all entries in the branch cache (68060, write-only strobe).
pub const CACR_060_CABC: u32 = 1 << 22;
/// Clear all user entries in the branch cache (68060, write-only strobe).
pub const CACR_060_CUBC: u32 = 1 << 21;
/// Enable instruction cache (68060).
pub const CACR_060_EIC: u32 = 1 << 15;
/// No allocate mode, instruction cache (68060; stored only).
pub const CACR_060_NAI: u32 = 1 << 14;
/// Half-cache operation mode, instruction (68060; stored only).
pub const CACR_060_FIC: u32 = 1 << 13;

// PCR (68060 MOVEC 0x808) bit assignments.
/// Enable superscalar dispatch.
pub const PCR_ESS: u32 = 1 << 0;
/// Disable the on-chip FPU: FP instructions raise Line-F.
pub const PCR_DFP: u32 = 1 << 1;
/// Enable debug features (stored only).
pub const PCR_EDEBUG: u32 = 1 << 7;
/// Reset value: identification 0x0430 (full MC68060), revision 1, ESS and
/// DFP clear (superscalar dispatch off until system software enables it).
pub const PCR_060_RESET: u32 = 0x0430_0100;

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

impl CpuCore {
    /// Legacy 68030/040 approximation from the handlers' corrected 68000
    /// counts. The 68020/68EC020 is routed through its MC68020UM section-8
    /// timing model before this function; the 68060 has a separate pipeline
    /// engine. The 68000/68010 paths remain untouched.
    #[inline]
    pub(crate) fn scale_cycles_for_cpu_type(&self, cycles: i32) -> i32 {
        use crate::core::types::CpuType;
        match self.cpu_type {
            CpuType::M68000 | CpuType::M68010 | CpuType::Invalid => cycles,
            _ => ((cycles * 5 + 7) / 8).max(2),
        }
    }

    /// Create a new CPU with M68000 defaults.
    pub fn new() -> Self {
        let mut cpu = Self {
            dar: [0; 16],
            dar_save: [0; 16],
            sr_save: 0,
            ppc: 0,
            pc: 0,
            sp: [0; 8],
            vbr: 0,
            sfc: 0,
            dfc: 0,
            cacr: 0,
            caar: 0,
            cacr_pending_ops: 0,
            itt0: 0,
            itt1: 0,
            dtt0: 0,
            dtt1: 0,
            ir: 0,
            fpr: [FloatX80::default(); 8],
            fpiar: 0,
            fpsr: 0,
            fpcr: 0,
            t1_flag: 0,
            t0_flag: 0,
            s_flag: SFLAG_SET, // Start in supervisor mode
            m_flag: 0,
            x_flag: 0,
            n_flag: 0,
            not_z_flag: 1, // Z = 0 (not set)
            v_flag: 0,
            c_flag: 0,
            int_mask: 0x0700, // Mask all interrupts
            int_level: 0,
            stopped: 0,
            fm_ptr: 0,
            fm_base: 0,
            fm_len: 0,
            trace_record_skip: [super::trace_jit::TRACE_PC_NONE; 4],
            trace_probe_skip: [super::trace_jit::TRACE_PC_NONE; 4],
            trace_record_skip_at: 0,
            trace_probe_skip_at: 0,
            trace_recording: false,
            change_of_flow: false,
            loop_mode: false,
            loop_body_word: 0,
            loop_dbcc_word: 0,
            prefetch_queue: [0; 2],
            prefetch_count: 0,
            consume_without_prefetch: false,
            pending_sync_clocks: 0,
            precise_bus: true,
            cpu_type: CpuType::M68000,
            address_mask: 0x00FFFFFF, // 24-bit for 68000
            sr_mask: 0xA71F,          // T1 -- S -- -- I2 I1 I0 -- -- -- X N Z V C
            instr_mode: 0,
            run_mode: 0,
            exception_processing: false,
            instruction_exception_vector: None,
            bitfield_mem_wide_span: false,
            last_exception_vector: None,
            has_pmmu: false,
            pmmu_enabled: false,
            is_pre_68020: true,
            // A real 6888x comes out of reset in the NULL state: FSAVE
            // writes a NULL frame until the first FPU instruction runs.
            fpu_just_reset: true,
            reset_cycles: 0,
            cyc_bcc_notake_b: -2,
            cyc_bcc_notake_w: 2,
            cyc_dbcc_f_noexp: -2,
            cyc_dbcc_f_exp: 2,
            cyc_scc_r_true: 2,
            cyc_movem_w: 2,
            cyc_movem_l: 3,
            cyc_shift: 1,
            cyc_reset: 132,
            virq_state: 0,
            nmi_pending: 0,
            mmu_crp_aptr: 0,
            mmu_crp_limit: 0,
            mmu_srp_aptr: 0,
            mmu_srp_limit: 0,
            mmu_tc: 0,
            mmu_sr: 0,
            mmu_tt0: 0,
            mmu_tt1: 0,
            dacr0: 0,
            dacr1: 0,
            iacr0: 0,
            iacr1: 0,
            pcr: PCR_060_RESET,
            buscr: 0,
            atc: crate::mmu::Atc::default(),
            pending_fault_cause: None,
            mmu_fc_override: None,
            mmu_read_override: None,
            mmu_write_suppress: None,
            pending_fault_wdata: 0,
            fault_resume: None,
            cycles_remaining: 0,
            initial_cycles: 0,
            decode_table: None,
            oep060: Default::default(),
            emulate_unimplemented_060: false,
            sst_m68000_compat: false,
            fpu_present: true,
        };
        cpu.set_cpu_type(CpuType::M68000);
        cpu
    }

    /// Enable/disable SingleStepTests (MAME) fixture compatibility behavior.
    #[inline]
    pub fn set_sst_m68000_compat(&mut self, on: bool) {
        self.sst_m68000_compat = on;
    }

    /// Set CPU type and configure appropriate masks/timing.
    pub fn set_cpu_type(&mut self, cpu_type: CpuType) {
        self.clear_execution_pipeline_state();
        self.cpu_type = cpu_type;
        self.is_pre_68020 = matches!(
            cpu_type,
            CpuType::M68000 | CpuType::M68010 | CpuType::SCC68070
        );
        self.clear_decoded_op_cache();
        match cpu_type {
            CpuType::M68000 => {
                self.address_mask = 0x00FFFFFF;
                self.sr_mask = 0xA71F;
                self.has_pmmu = false;
            }
            CpuType::M68010 => {
                self.address_mask = 0x00FFFFFF;
                self.sr_mask = 0xA71F;
                self.has_pmmu = false;
            }
            CpuType::SCC68070 => {
                // SCC68070 is a 68010 with a 32-bit data bus.
                // Instruction set is 68010-compatible, but the address bus is 32-bit.
                self.address_mask = 0xFFFFFFFF;
                self.sr_mask = 0xA71F;
                self.has_pmmu = false;
            }
            CpuType::M68EC020 | CpuType::M68020 => {
                self.address_mask = 0xFFFFFFFF;
                self.sr_mask = 0xF71F;
                self.has_pmmu = false;
            }
            CpuType::M68EC030 => {
                self.address_mask = 0xFFFFFFFF;
                self.sr_mask = 0xF71F;
                self.has_pmmu = false;
            }
            CpuType::M68030 => {
                self.address_mask = 0xFFFFFFFF;
                self.sr_mask = 0xF71F;
                self.has_pmmu = true;
            }
            CpuType::M68EC040 | CpuType::M68LC040 => {
                self.address_mask = 0xFFFFFFFF;
                self.sr_mask = 0xF71F;
                self.has_pmmu = false;
            }
            CpuType::M68040 => {
                self.address_mask = 0xFFFFFFFF;
                self.sr_mask = 0xF71F;
                self.has_pmmu = true;
            }
            CpuType::M68060 => {
                self.address_mask = 0xFFFFFFFF;
                // The 68060 drops T0 (trace on change of flow, SR bit 14) and
                // keeps the single T bit and the M bit.
                self.sr_mask = 0xB71F;
                self.has_pmmu = true;
            }
            _ => {}
        }
    }

    // ========== Stack Pointer Banking ==========
    // Musashi formula: sp[s_flag | ((s_flag >> 1) & m_flag)]
    // s_flag = 0 (user) or 4 (supervisor)
    // m_flag = 0 (interrupt) or 2 (master)
    // Results: USP=0, ISP=4, MSP=6

    /// Get the current stack pointer bank index.
    ///
    /// The 68060 implements a single supervisor stack: the SR M bit is
    /// storable (interrupts still clear it, system software may use it) but
    /// it never selects a separate master-stack bank.
    #[inline]
    fn sp_index(&self) -> usize {
        if self.cpu_type == CpuType::M68060 {
            self.s_flag as usize
        } else {
            (self.s_flag | ((self.s_flag >> 1) & self.m_flag)) as usize
        }
    }

    /// Backup current SP to banked storage.
    fn backup_sp(&mut self) {
        let idx = self.sp_index();
        self.sp[idx] = self.dar[15];
    }

    /// Restore SP from banked storage.
    fn restore_sp(&mut self) {
        let idx = self.sp_index();
        self.dar[15] = self.sp[idx];
    }

    /// Set the S flag with stack pointer banking.
    /// Value must be 0 (user) or SFLAG_SET (supervisor).
    pub fn set_s_flag(&mut self, value: u32) {
        self.backup_sp();
        self.s_flag = value;
        self.restore_sp();
    }

    /// Set both S and M flags with stack pointer banking.
    /// Value: bit 2 = S, bit 1 = M (0, 2, 4, or 6).
    pub fn set_sm_flag(&mut self, value: u32) {
        self.backup_sp();
        self.s_flag = value & SFLAG_SET;
        self.m_flag = value & MFLAG_SET;
        self.restore_sp();
    }

    /// Set S and M flags without touching the stack pointer.
    pub fn set_sm_flag_nosp(&mut self, value: u32) {
        self.s_flag = value & SFLAG_SET;
        self.m_flag = value & MFLAG_SET;
    }

    // ========== Reset ==========

    /// Pulse reset (initialize CPU state without loading vectors).
    pub fn pulse_reset(&mut self) {
        self.clear_execution_pipeline_state();
        self.stopped = 0;
        self.t1_flag = 0;
        self.t0_flag = 0;
        self.m_flag = 0;
        self.run_mode = 0;
        self.instr_mode = 0;
        self.vbr = 0;
        // Reset disables and clears the on-chip caches (68020+): CACR
        // enable/freeze bits drop and the host model must invalidate.
        self.cacr = 0;
        self.cacr_pending_ops |= CACR_CI | CACR_CD;
        // 68060 control registers: identification/revision persist, the
        // writable bits (EDEBUG/DFP/ESS) clear. Reset invalidates the
        // branch cache along with the other caches.
        self.pcr = PCR_060_RESET;
        self.buscr = 0;
        self.oep060.branch_cache.clear_all();
        // Reset disables address translation: the TC enable bit and the
        // TTR enable bits are cleared (030/040/060 alike), so the CPU
        // comes up fetching physical addresses even if an OS had the MMU
        // on when the reset hit. Root pointers are left as-is (undefined
        // at reset); with translation off they are inert until rewritten.
        self.mmu_tc = 0;
        self.pmmu_enabled = false;
        self.itt0 = 0;
        self.itt1 = 0;
        self.dtt0 = 0;
        self.dtt1 = 0;
        // The 030's PMOVE-form TT0/TT1 (stored apart from the 040 TTRs).
        self.mmu_tt0 = 0;
        self.mmu_tt1 = 0;
        self.atc.flush_all();
        self.prefetch_queue = [0; 2];
        self.prefetch_count = 0;
        self.consume_without_prefetch = false;
        self.pending_sync_clocks = 0;

        // Condition codes after reset: clear X/N/V/C, set Z (Musashi-compatible default).
        self.x_flag = 0;
        self.n_flag = 0;
        self.v_flag = 0;
        self.c_flag = 0;
        self.not_z_flag = 0; // Z set

        // Enter supervisor mode
        self.set_s_flag(SFLAG_SET);
        self.int_mask = 0x0700; // Mask all interrupts
    }

    // ========== Prefetch queue (Part E.1, 68000 only) ==========

    /// Whether the two-word prefetch queue models instruction fetching.
    /// The 68000 and 68010 share the two-word IRD/IRC queue (the 68010 adds
    /// loop mode on top of it); later CPU types keep the direct fetch-at-PC
    /// behavior with their cache models layered above.
    #[inline]
    pub fn prefetch_enabled(&self) -> bool {
        self.precise_bus && matches!(self.cpu_type, CpuType::M68000 | CpuType::M68010)
    }

    /// Switch between the transaction-exact interpreter contract and the
    /// optimized batch contract. A transition invalidates transient fetch
    /// state so neither path observes words queued by the other.
    pub(crate) fn set_precise_bus(&mut self, precise: bool) {
        if self.precise_bus == precise {
            return;
        }
        self.clear_execution_pipeline_state();
        self.precise_bus = precise;
        self.prefetch_count = 0;
        self.pending_sync_clocks = 0;
        self.consume_without_prefetch = false;
        self.loop_mode = false;
    }

    /// Clear timing-model state that cannot survive a reset, exception, or
    /// transition between execution engines.
    #[inline]
    pub(crate) fn clear_execution_pipeline_state(&mut self) {
        self.break_060_pipeline();
    }

    // ========== Precise per-access timing (Part E.2, 68000 only) ==========

    /// Record `clocks` CPU clocks of internal (non-bus) processing. They are
    /// reported to the host (via `AddressBus::sync`) immediately before the
    /// next bus access, so that access lands at its hardware-exact offset.
    #[inline]
    pub fn internal_cycles(&mut self, clocks: u32) {
        if self.prefetch_enabled() {
            self.pending_sync_clocks = self.pending_sync_clocks.wrapping_add(clocks);
        }
    }

    /// Flush accumulated internal clocks to the host right before a bus
    /// access. Every bus-access helper calls this first.
    #[inline]
    pub(crate) fn flush_sync<B: AddressBus>(&mut self, bus: &mut B) {
        if self.pending_sync_clocks > 0 {
            let clocks = std::mem::take(&mut self.pending_sync_clocks);
            bus.sync(clocks);
        }
    }

    /// Mark the instruction's IPL poll point (the 68000/68010 sample their
    /// IPL pins at ONE microcode-determined point per instruction; Moira's
    /// POLL flag). Called right after the bus access that carries the
    /// poll, for instructions where that access is NOT the last one --
    /// e.g. read-modify-write instructions poll during the final prefetch
    /// and then perform their writeback. The host keeps that access's
    /// sample for the boundary interrupt decision and ignores later
    /// accesses. Applies to the prefetch-queue CPUs; call sites where the
    /// 68010 microcode polls elsewhere gate on the CPU type explicitly.
    #[inline]
    pub(crate) fn ipl_poll_point<B: AddressBus>(&mut self, bus: &mut B) {
        if self.prefetch_enabled() {
            bus.ipl_hold_sample();
        }
    }

    /// Mark the prefetch queue as stale (after an externally forced PC
    /// change). The next instruction-stream read fetches directly and the
    /// next instruction-end top-up restores the queue.
    #[inline]
    pub fn invalidate_prefetch(&mut self) {
        self.prefetch_count = 0;
    }

    /// Read one program-space word for the prefetch queue. Returns None when
    /// the read faulted (bus error already triggered).
    fn prefetch_read<B: AddressBus>(&mut self, bus: &mut B, addr: u32) -> Option<u16> {
        // Part E.2: report internal clocks elapsed before this bus access.
        self.flush_sync(bus);
        let addr = self.address(addr);
        match bus.try_read_word(addr) {
            Ok(v) => Some(v),
            Err(_) => {
                self.trigger_bus_error(bus, addr, false, true, 2);
                None
            }
        }
    }

    /// Refill the prefetch queue from the current PC: two program-space word
    /// reads at `pc` and `pc + 2`, discarding whatever was queued. This is
    /// what the 68000 does after every change of instruction flow (taken
    /// branches, jumps, returns, exception entry), which is why those
    /// instructions cost two extra bus reads at the target and why words
    /// prefetched past a taken branch never appear on the bus as re-reads.
    ///
    /// An odd PC leaves the queue empty; the address error fires at the next
    /// instruction-stream read (same point as the non-prefetch path).
    pub fn full_prefetch<B: AddressBus>(&mut self, bus: &mut B) {
        self.prefetch_first(bus);
        self.prefetch_second(bus);
    }

    /// First half of a flow-change prefetch: read the word at the new PC into
    /// the front of the queue. Some instructions (JSR/BSR) interleave other
    /// bus accesses between the two refill reads; they call this, do their
    /// accesses, then call `prefetch_second`.
    pub fn prefetch_first<B: AddressBus>(&mut self, bus: &mut B) {
        if !self.prefetch_enabled() {
            return;
        }
        self.prefetch_count = 0;
        if self.pc & 1 != 0 {
            return;
        }
        if let Some(w) = self.prefetch_read(bus, self.pc) {
            self.prefetch_queue[0] = w;
            self.prefetch_count = 1;
        }
    }

    /// Second half of a flow-change prefetch: read the word at PC + 2 into the
    /// back of the queue.
    pub fn prefetch_second<B: AddressBus>(&mut self, bus: &mut B) {
        if !self.prefetch_enabled() || self.prefetch_count != 1 {
            return;
        }
        if self.pc & 1 != 0 || self.run_mode == super::execute::RUN_MODE_BERR_AERR_RESET {
            return;
        }
        if let Some(w) = self.prefetch_read(bus, self.pc.wrapping_add(2)) {
            self.prefetch_queue[1] = w;
            self.prefetch_count = 2;
        }
    }

    /// Fetch one word into the back of the prefetch queue (the "np" prefetch
    /// micro-operation). The fetch address is the first instruction-stream
    /// word the queue does not yet hold.
    pub fn top_up_prefetch_one<B: AddressBus>(&mut self, bus: &mut B) {
        if self.loop_mode {
            return;
        }
        if !self.prefetch_enabled() || self.pc & 1 != 0 || self.prefetch_count >= 2 {
            return;
        }
        if self.run_mode == super::execute::RUN_MODE_BERR_AERR_RESET {
            return;
        }
        let slot = self.prefetch_count as usize;
        let addr = self.pc.wrapping_add(2 * slot as u32);
        if let Some(w) = self.prefetch_read(bus, addr) {
            self.prefetch_queue[slot] = w;
            self.prefetch_count += 1;
        }
    }

    /// Top the prefetch queue back up to two words at the end of an
    /// instruction -- the final prefetch the 68000 performs after its
    /// writes. A no-op after flow-change instructions (their refill
    /// already filled the queue), on a stopped CPU (STOP performs no
    /// further bus activity), and on non-prefetch CPU types.
    pub fn top_up_prefetch<B: AddressBus>(&mut self, bus: &mut B) {
        if self.loop_mode {
            return;
        }
        if !self.prefetch_enabled() || self.pc & 1 != 0 || self.stopped != 0 {
            return;
        }
        if self.run_mode == super::execute::RUN_MODE_BERR_AERR_RESET {
            return;
        }
        while self.prefetch_count < 2 {
            let before = self.prefetch_count;
            self.top_up_prefetch_one(bus);
            if self.prefetch_count == before {
                return;
            }
        }
    }

    /// 68000 -(An) long operand read: the two predecrement micro-steps read
    /// the LOW word first (at addr + 2), then the HIGH word (at addr).
    pub fn read_long_predec_68000<B: AddressBus>(&mut self, bus: &mut B, addr: u32) -> u32 {
        let lo = self.read_16(bus, addr.wrapping_add(2)) as u32;
        let hi = self.read_16(bus, addr) as u32;
        (hi << 16) | lo
    }

    /// 68000 long writeback for the -(Ax),-(Ay) extended-arithmetic forms
    /// (ADDX.L/SUBX.L memory-to-memory): write the low word, perform the
    /// final prefetch, then write the high word. The IPL poll rides the
    /// low-word write (Moira `writeM<Word, POLL>` on the first write).
    pub fn write_long_mm_interleaved_68000<B: AddressBus>(
        &mut self,
        bus: &mut B,
        addr: u32,
        value: u32,
    ) {
        self.write_16(bus, addr.wrapping_add(2), (value & 0xFFFF) as u16);
        self.ipl_poll_point(bus);
        self.top_up_prefetch(bus);
        self.write_16(bus, addr, (value >> 16) as u16);
    }

    /// Consume the next instruction-stream word from the prefetch queue
    /// WITHOUT a prefetch refill. Used for the opcode itself (its refill was
    /// the previous instruction's final prefetch) and for words consumed on
    /// flow-change paths (the microcode goes straight to the jump refill
    /// instead of prefetching ahead of a discarded stream).
    ///
    /// Falls back to a direct fetch when the queue is empty.
    pub fn consume_imm_16_no_prefetch<B: AddressBus>(&mut self, bus: &mut B) -> u16 {
        if self.prefetch_count > 0 {
            let word = self.prefetch_queue[0];
            self.prefetch_queue[0] = self.prefetch_queue[1];
            self.prefetch_count -= 1;
            self.pc = self.pc.wrapping_add(2);
            return word;
        }
        match self.prefetch_read(bus, self.pc) {
            Some(w) => {
                self.pc = self.pc.wrapping_add(2);
                w
            }
            None => 0,
        }
    }

    /// Full reset: pulse reset + load SP and PC from vectors.
    pub fn reset<B: AddressBus>(&mut self, bus: &mut B) {
        self.pulse_reset();

        // Read initial SSP from vector 0
        let ssp = bus.read_long(0);
        self.dar[15] = ssp;
        self.sp[SFLAG_SET as usize] = ssp; // ISP bank
        // Initialize MSP too (for 68020+ MSP/ISP banking). Harmless on 68000.
        self.sp[(SFLAG_SET | MFLAG_SET) as usize] = ssp;

        // Read initial PC from vector 1
        self.pc = bus.read_long(4);

        // The queue holds nothing valid for the new PC; the first instruction
        // fetch refills it (matching the 68000's post-reset double prefetch).
        self.invalidate_prefetch();

        // Use reset cycles
        self.cycles_remaining -= self.cyc_reset;
    }

    /// Soft reset (compatible with old API - no bus access).
    pub fn reset_soft(&mut self) {
        self.pulse_reset();
    }

    // ========== Register Accessors ==========

    /// Get data register.
    #[inline]
    pub fn d(&self, reg: usize) -> u32 {
        self.dar[reg & 7]
    }

    /// Set data register.
    #[inline]
    pub fn set_d(&mut self, reg: usize, value: u32) {
        self.dar[reg & 7] = value;
    }

    /// Returns true if the CPU is stopped via STOP.
    #[inline]
    pub fn is_stopped(&self) -> bool {
        self.stopped != 0 && self.run_mode != RUN_MODE_BERR_AERR_RESET
    }

    /// Returns true if the CPU halted due to a double-fault/bus-error reset condition.
    #[inline]
    pub fn is_halted(&self) -> bool {
        self.stopped != 0 && self.run_mode == RUN_MODE_BERR_AERR_RESET
    }

    /// Get address register.
    #[inline]
    pub fn a(&self, reg: usize) -> u32 {
        self.dar[8 + (reg & 7)]
    }

    /// Set address register.
    #[inline]
    pub fn set_a(&mut self, reg: usize, value: u32) {
        self.dar[8 + (reg & 7)] = value;
    }

    /// Get stack pointer (A7).
    #[inline]
    pub fn sp(&self) -> u32 {
        self.dar[15]
    }

    /// Set stack pointer (A7).
    #[inline]
    pub fn set_sp(&mut self, value: u32) {
        self.dar[15] = value;
    }

    /// Get User Stack Pointer.
    pub fn get_usp(&self) -> u32 {
        if self.s_flag == 0 {
            self.dar[15]
        } else {
            self.sp[0]
        }
    }

    /// Set User Stack Pointer.
    pub fn set_usp(&mut self, value: u32) {
        if self.s_flag == 0 {
            self.dar[15] = value;
        } else {
            self.sp[0] = value;
        }
    }

    // ========== Control Register Access (MOVEC) ==========

    /// Read control register for MOVEC instruction.
    /// Control register codes:
    /// 0x000 = SFC, 0x001 = DFC, 0x002 = CACR, 0x003 = TC (68040)
    /// 0x004-0x007 = ITT0/ITT1/DTT0/DTT1, 0x008-0x00B = DACR0/DACR1/IACR0/IACR1
    /// 0x800 = USP, 0x801 = VBR, 0x802 = CAAR, 0x803 = MSP, 0x804 = ISP
    /// 0x805 = MMUSR, 0x806 = URP, 0x807 = SRP
    pub fn read_control_register(&self, reg: u16) -> u32 {
        match reg {
            0x000 => self.sfc,    // Source Function Code
            0x001 => self.dfc,    // Destination Function Code
            0x002 => self.cacr,   // Cache Control Register
            0x003 => self.mmu_tc, // Translation Control (68040)
            0x004 => self.itt0,   // Instruction TTR 0 (68040)
            0x005 => self.itt1,   // Instruction TTR 1 (68040)
            0x006 => self.dtt0,   // Data TTR 0 (68040)
            0x007 => self.dtt1,   // Data TTR 1 (68040)
            // 0x008 is BUSCR on the 68060 and DACR0 on the 68040.
            0x008 if self.is_060() => self.buscr,
            0x008 => self.dacr0, // Data Access Control 0 (68040)
            0x009 => self.dacr1, // Data Access Control 1 (68040)
            0x00A => self.iacr0, // Instruction Access Control 0 (68040)
            0x00B => self.iacr1, // Instruction Access Control 1 (68040)
            0x800 => {
                // USP
                if self.s_flag == 0 {
                    self.dar[15]
                } else {
                    self.sp[0]
                }
            }
            0x801 => self.vbr,  // Vector Base Register
            0x802 => self.caar, // Cache Address Register
            0x803 => {
                // MSP (Master Stack Pointer)
                if self.s_flag != 0 && self.m_flag != 0 {
                    self.dar[15]
                } else {
                    self.sp[6]
                }
            }
            0x804 => {
                // ISP (Interrupt Stack Pointer)
                if self.s_flag != 0 && self.m_flag == 0 {
                    self.dar[15]
                } else {
                    self.sp[4]
                }
            }
            0x805 => self.mmu_sr,               // MMU Status Register (68040)
            0x806 => self.mmu_crp_aptr,         // User Root Pointer (68040; URP)
            0x807 => self.mmu_srp_aptr,         // Supervisor Root Pointer (68040)
            0x808 if self.is_060() => self.pcr, // Processor Configuration (68060)
            _ => 0,                             // Unknown register
        }
    }

    /// Write control register for MOVEC instruction.
    pub fn write_control_register(&mut self, reg: u16, value: u32) {
        match reg {
            0x000 => self.sfc = value & 7, // SFC (3 bits)
            0x001 => self.dfc = value & 7, // DFC (3 bits)
            0x002 => {
                // CACR. The clear bits (CEI/CI, and CED/CD on the 68030)
                // are write-only strobes: they trigger an invalidation,
                // never store, and read back as zero. Persistent bits are
                // masked to what the CPU type implements.
                use crate::core::types::CpuType;
                let (persist, strobes) = match self.cpu_type {
                    CpuType::M68EC020 | CpuType::M68020 => (CACR_EI | CACR_FI, CACR_CEI | CACR_CI),
                    CpuType::M68EC030 | CpuType::M68030 => (
                        CACR_EI | CACR_FI | CACR_IBE | CACR_ED | CACR_FD | CACR_DBE | CACR_WA,
                        CACR_CEI | CACR_CI | CACR_CED | CACR_CD,
                    ),
                    // The 68060 keeps the cache enables at the 040 positions
                    // and adds branch-cache / store-buffer controls. CABC and
                    // CUBC are write-only branch-cache clear strobes (wired to
                    // the branch-cache model when it lands; accepted and
                    // discarded until then). Cache invalidation stays with
                    // CINV/CPUSH like the 040.
                    CpuType::M68060 => {
                        // The branch-cache clear strobes act immediately and
                        // never store; disabling EBC also clears the table so
                        // re-enabling starts cold (software is required to
                        // clear before re-enabling anyway).
                        if value & CACR_060_CABC != 0 {
                            self.oep060.branch_cache.clear_all();
                        } else if value & CACR_060_CUBC != 0 {
                            self.oep060.branch_cache.clear_user();
                        }
                        if self.cacr & CACR_060_EBC != 0 && value & CACR_060_EBC == 0 {
                            self.oep060.branch_cache.clear_all();
                        }
                        (
                            CACR_060_EDC
                                | CACR_060_NAD
                                | CACR_060_ESB
                                | CACR_060_DPI
                                | CACR_060_FOC
                                | CACR_060_EBC
                                | CACR_060_EIC
                                | CACR_060_NAI
                                | CACR_060_FIC,
                            0,
                        )
                    }
                    // 68040 CACR defines only the two cache-enable bits and
                    // has no clear strobes - invalidation is done with the
                    // CINV/CPUSH instructions (see decode.rs). Reserved bits
                    // read back as zero.
                    _ => (CACR_040_IE | CACR_040_DE, 0),
                };
                self.cacr = value & persist;
                self.cacr_pending_ops |= value & strobes;
            }
            0x003 => {
                // Translation Control (68040). MOVEC must update pmmu_enabled
                // (the 040 enable bit is TC[15], unlike the 030's TC[31]).
                // The 68040 register only implements E and P: everything else
                // reads back as zero (the 060 adds more control bits).
                self.mmu_tc = if self.is_040() {
                    value & 0xC000
                } else if self.is_060() {
                    value & 0xFFFE
                } else {
                    value
                };
                self.pmmu_enabled = self.tc_enable();
            }
            // The 040/060 TTRs implement base, mask, E, S, U, CM and W;
            // the rest reads back as zero.
            0x004 => self.itt0 = value & 0xFFFF_E364, // Instruction TTR 0
            0x005 => self.itt1 = value & 0xFFFF_E364, // Instruction TTR 1
            0x006 => self.dtt0 = value & 0xFFFF_E364, // Data TTR 0
            0x007 => self.dtt1 = value & 0xFFFF_E364, // Data TTR 1
            // 0x008 is BUSCR on the 68060 and DACR0 on the 68040.
            0x008 if self.is_060() => {
                // BUSCR: only the two lock bits are writable; they read
                // back in bits 31/29 (WinUAE hardware model).
                self.buscr = (self.buscr & 0x5000_0000) | (value & 0xA000_0000);
            }
            0x008 => self.dacr0 = value, // Data Access Control 0 (68040)
            0x009 => self.dacr1 = value, // Data Access Control 1 (68040)
            0x00A => self.iacr0 = value, // Instruction Access Control 0 (68040)
            0x00B => self.iacr1 = value, // Instruction Access Control 1 (68040)
            0x800 => {
                // USP
                if self.s_flag == 0 {
                    self.dar[15] = value;
                } else {
                    self.sp[0] = value;
                }
            }
            0x801 => self.vbr = value,  // VBR
            0x802 => self.caar = value, // CAAR
            0x803 => {
                // MSP
                if self.s_flag != 0 && self.m_flag != 0 {
                    self.dar[15] = value;
                } else {
                    self.sp[6] = value;
                }
            }
            0x804 => {
                // ISP
                if self.s_flag != 0 && self.m_flag == 0 {
                    self.dar[15] = value;
                } else {
                    self.sp[4] = value;
                }
            }
            0x805 => self.mmu_sr = value, // MMU Status Register (68040)
            0x806 => self.mmu_crp_aptr = value, // User Root Pointer (68040; URP)
            0x807 => self.mmu_srp_aptr = value, // Supervisor Root Pointer (68040)
            0x808 if self.is_060() => {
                // PCR: identification and revision are read-only; only
                // EDEBUG, DFP, and ESS are writable.
                let writable = PCR_EDEBUG | PCR_DFP | PCR_ESS;
                self.pcr = (self.pcr & !writable) | (value & writable);
            }
            _ => {} // Unknown register - ignore
        }
        // A write to TC, a root pointer, or a TTR can change every translation,
        // so drop the cached ones (the 040 walker consults the ATC).
        if matches!(reg, 0x003 | 0x004 | 0x005 | 0x006 | 0x007 | 0x806 | 0x807) {
            self.atc.flush_all();
        }
    }

    /// True for any 68040-family part (full / LC / EC). The 040 MMU differs
    /// from the 030 in register layout, TC enable bit, and table format.
    #[inline]
    pub fn is_040(&self) -> bool {
        matches!(
            self.cpu_type,
            CpuType::M68EC040 | CpuType::M68LC040 | CpuType::M68040
        )
    }

    /// Whether an instruction the 68060 dropped from silicon must take its
    /// unimplemented trap (vector 61 for integer, the FP-unimplemented
    /// family for FPU ops) rather than execute natively.
    #[inline]
    pub(crate) fn trap_unimpl_060(&self) -> bool {
        self.cpu_type == CpuType::M68060 && !self.emulate_unimplemented_060
    }

    /// True for the 68060, which shares the 68040's MMU table format and
    /// TC enable bit but drops PTEST/PMOVE and adds PLPA.
    #[inline]
    pub fn is_060(&self) -> bool {
        self.cpu_type == CpuType::M68060
    }

    /// Whether TC's translation-enable bit is set. The bit position differs by
    /// part: the 68040 and 68060 use `TC[15]`, the 68030 uses `TC[31]`.
    #[inline]
    pub fn tc_enable(&self) -> bool {
        if self.is_040() || self.is_060() {
            self.mmu_tc & 0x0000_8000 != 0
        } else {
            self.mmu_tc & 0x8000_0000 != 0
        }
    }

    // ========== Memory Access Helpers ==========

    /// Mask address according to CPU type.
    #[inline]
    pub fn address(&self, addr: u32) -> u32 {
        addr & self.address_mask
    }

    #[inline]
    pub(crate) fn faulted(&self) -> bool {
        self.run_mode == RUN_MODE_BERR_AERR_RESET
    }

    /// Close out an instruction that faulted mid-execution: re-assert the
    /// handler-entry PC/SR/registers the fault dispatch established (a flow
    /// instruction whose stack access faulted -- JSR/BSR/RTS -- still
    /// assigns `pc` on its way out, and a predecrement MOVEM keeps stepping
    /// A7, which would divert or corrupt the handler) and return to normal
    /// run mode.
    pub(crate) fn end_faulted_instruction(&mut self) {
        if let Some((handler_pc, handler_sr, handler_dar)) = self.fault_resume.take() {
            self.pc = handler_pc;
            // No bank swap: handler_dar carries the post-switch A7.
            self.set_sr_noint_nosp(handler_sr);
            self.dar = handler_dar;
        }
        // A double fault mid-dispatch has parked the CPU: keep the fault
        // run mode so `is_halted()` classifies it (a halted 68k stays dead
        // until reset, distinct from a STOP), and let the caller stop
        // executing rather than resume.
        if self.stopped != 0 {
            return;
        }
        self.run_mode = super::execute::RUN_MODE_NORMAL;
    }

    /// Trigger a 68000-style address error and mark the current instruction as faulted so that
    /// subsequent EA resolution/memory operations become no-ops.
    pub(crate) fn trigger_address_error<B: AddressBus>(
        &mut self,
        bus: &mut B,
        address: u32,
        write: bool,
        instruction: bool,
    ) {
        if self.faulted() {
            return;
        }
        if std::env::var_os("M68K_DIAG_ADDRESS_ERROR").is_some() {
            eprintln!(
                "m68k address error: addr={address:#010X} write={write} instr={instruction} \
                 pc={:#010X} ppc={:#010X} sp={:#010X} sr={:#06X}",
                self.pc,
                self.ppc,
                self.sp(),
                self.get_sr(),
            );
            let sp = self.sp();
            let mut words = Vec::new();
            for i in -8i32..8 {
                let a = sp.wrapping_add((i * 2) as u32);
                words.push(format!("{:04X}", bus.read_word(a)));
            }
            eprintln!(
                "m68k stack around sp ({:#010X}-16..+16): {}",
                sp,
                words.join(" ")
            );
            eprintln!(
                "m68k regs d0-d7={:08X?} a0-a7={:08X?} vbr={:#010X}",
                &self.dar[0..8],
                &self.dar[8..16],
                self.vbr
            );
        }

        // Roll back any partially-applied register side effects from the faulting instruction.
        // The execute loop saved a snapshot at the start of the instruction.
        self.set_sr_noint_nosp(self.sr_save);
        self.dar = self.dar_save;
        let _ = self.exception_address_error(bus, address, write, instruction);
        self.fault_resume = Some((self.pc, self.get_sr(), self.dar));
        self.run_mode = RUN_MODE_BERR_AERR_RESET;
    }

    /// Trigger an address error before the current instruction has had any side effects.
    pub(crate) fn trigger_address_error_no_rollback<B: AddressBus>(
        &mut self,
        bus: &mut B,
        address: u32,
        write: bool,
        instruction: bool,
    ) {
        if self.faulted() {
            return;
        }

        let _ = self.exception_address_error(bus, address, write, instruction);
        self.run_mode = RUN_MODE_BERR_AERR_RESET;
    }

    /// Trigger a bus error and mark the current instruction as faulted so that subsequent EA
    /// resolution/memory operations become no-ops.
    pub(crate) fn trigger_bus_error<B: AddressBus>(
        &mut self,
        bus: &mut B,
        address: u32,
        write: bool,
        instruction: bool,
        size: u32,
    ) {
        if self.faulted() {
            return;
        }
        // A fault while already delivering a fault is a double fault: halt
        // rather than recurse -- the frame writes and vector fetch below
        // translate like any other supervisor access, and a fault raised
        // from one of them lands right back here.
        if self.exception_processing {
            self.stopped = 1;
            self.run_mode = RUN_MODE_BERR_AERR_RESET;
            return;
        }

        // Roll back any partially-applied register side effects from the faulting instruction.
        self.set_sr_noint_nosp(self.sr_save);
        self.dar = self.dar_save;
        self.exception_processing = true;
        let cause = self.pending_fault_cause.take();
        let _ = self.exception_bus_error(bus, address, write, instruction, size, cause);
        self.exception_processing = false;
        self.fault_resume = Some((self.pc, self.get_sr(), self.dar));
        self.run_mode = RUN_MODE_BERR_AERR_RESET;
    }

    /// Trigger a bus error before the current instruction has modified
    /// architectural state (opcode fetch and instruction-MMU walks).
    pub(crate) fn trigger_bus_error_no_rollback<B: AddressBus>(
        &mut self,
        bus: &mut B,
        address: u32,
        write: bool,
        instruction: bool,
    ) {
        if self.faulted() {
            return;
        }
        if self.exception_processing {
            self.stopped = 1;
            self.run_mode = RUN_MODE_BERR_AERR_RESET;
            return;
        }

        self.exception_processing = true;
        let cause = self.pending_fault_cause.take();
        let _ = self.exception_bus_error(bus, address, write, instruction, 2, cause);
        self.exception_processing = false;
        self.fault_resume = Some((self.pc, self.get_sr(), self.dar));
        self.run_mode = RUN_MODE_BERR_AERR_RESET;
    }

    /// Byte mask of the active MMU page (page size - 1). A misaligned access
    /// whose bytes straddle this boundary runs as separate bus cycles on the
    /// 32-bit-bus CPUs, each cycle translated on its own: the two halves live
    /// on different virtual pages that map to unrelated physical pages.
    /// Translating only the base address would read or write the physically
    /// adjacent page instead of the mapped one.
    #[inline]
    pub(crate) fn mmu_page_mask(&self) -> u32 {
        if self.is_040() || self.is_060() {
            // 68040/68060 TC.P (bit 14): 0 = 4K pages, 1 = 8K pages.
            if self.mmu_tc & 0x0000_4000 != 0 {
                0x1FFF
            } else {
                0xFFF
            }
        } else {
            // 68030 TC.PS (bits 23:20): page size 2^PS, PS = 8..15.
            let ps = ((self.mmu_tc >> 20) & 0xF).clamp(8, 15);
            (1u32 << ps) - 1
        }
    }

    /// Read byte from memory (data space).
    #[inline]
    pub fn read_8<B: AddressBus>(&mut self, bus: &mut B, addr: u32) -> u8 {
        if self.faulted() {
            return 0;
        }
        // Part E.2: report internal clocks elapsed before this bus access.
        self.flush_sync(bus);
        let mut addr = self.address(addr);
        if let Some((a, v)) = self.mmu_read_override
            && a == addr
        {
            // RTE'd 030 bus-fault frame with DF cleared: the handler
            // supplied this read's result in the data input buffer.
            self.mmu_read_override = None;
            return v as u8;
        }
        {
            if self.has_pmmu && self.pmmu_enabled {
                match crate::mmu::translate_address(
                    self,
                    bus,
                    addr,
                    /*write=*/ false,
                    self.is_supervisor(),
                    /*instruction=*/ false,
                ) {
                    Ok(p) => addr = self.address(p),
                    Err(f) => {
                        self.handle_mmu_fault(bus, f, false, false, 1);
                        return 0;
                    }
                }
            }
        }
        match bus.try_read_byte(addr) {
            Ok(v) => v,
            Err(f) => {
                if matches!(f.kind, BusFaultKind::BusError) {
                    self.trigger_bus_error(bus, addr, false, false, 1);
                }
                0
            }
        }
    }

    /// Read word from memory (data space).
    #[inline]
    pub fn read_16<B: AddressBus>(&mut self, bus: &mut B, addr: u32) -> u16 {
        if self.faulted() {
            return 0;
        }
        // Part E.2: report internal clocks elapsed before this bus access.
        self.flush_sync(bus);
        let mut addr = self.address(addr);
        if matches!(
            self.cpu_type,
            CpuType::M68000 | CpuType::M68010 | CpuType::SCC68070
        ) && (addr & 1) != 0
        {
            self.trigger_address_error(bus, addr, false, false);
            return 0;
        }
        if self.has_pmmu && self.pmmu_enabled {
            let pm = self.mmu_page_mask();
            if addr & pm == pm {
                // Misaligned word straddling an MMU page: two byte cycles,
                // each translated on its own page.
                let hi = self.read_8(bus, addr) as u16;
                if self.faulted() {
                    return 0;
                }
                let lo = self.read_8(bus, addr.wrapping_add(1)) as u16;
                return (hi << 8) | lo;
            }
        }
        if let Some((a, v)) = self.mmu_read_override
            && a == addr
        {
            // RTE'd 030 bus-fault frame with DF cleared: the handler
            // supplied this read's result in the data input buffer.
            self.mmu_read_override = None;
            return v as u16;
        }
        {
            if self.has_pmmu && self.pmmu_enabled {
                match crate::mmu::translate_address(
                    self,
                    bus,
                    addr,
                    /*write=*/ false,
                    self.is_supervisor(),
                    /*instruction=*/ false,
                ) {
                    Ok(p) => addr = self.address(p),
                    Err(f) => {
                        self.handle_mmu_fault(bus, f, false, false, 2);
                        return 0;
                    }
                }
            }
        }
        match bus.try_read_word(addr) {
            Ok(v) => v,
            Err(f) => {
                if matches!(f.kind, BusFaultKind::BusError) {
                    self.trigger_bus_error(bus, addr, false, false, 2);
                }
                0
            }
        }
    }

    /// Read long from memory (data space).
    #[inline]
    pub fn read_32<B: AddressBus>(&mut self, bus: &mut B, addr: u32) -> u32 {
        if self.faulted() {
            return 0;
        }
        // Part E.2: report internal clocks elapsed before this bus access.
        self.flush_sync(bus);
        let mut addr = self.address(addr);
        if matches!(
            self.cpu_type,
            CpuType::M68000 | CpuType::M68010 | CpuType::SCC68070
        ) && (addr & 1) != 0
        {
            self.trigger_address_error(bus, addr, false, false);
            return 0;
        }
        if self.has_pmmu && self.pmmu_enabled {
            let pm = self.mmu_page_mask();
            if addr & pm > pm - 3 {
                // Long straddling an MMU page: two word cycles, each
                // translated on its own page (read_16 sub-splits further if
                // a half is itself misaligned across the boundary).
                let hi = self.read_16(bus, addr) as u32;
                if self.faulted() {
                    return 0;
                }
                let lo = self.read_16(bus, addr.wrapping_add(2)) as u32;
                return (hi << 16) | lo;
            }
        }
        if let Some((a, v)) = self.mmu_read_override
            && a == addr
        {
            // RTE'd 030 bus-fault frame with DF cleared: the handler
            // supplied this read's result in the data input buffer.
            self.mmu_read_override = None;
            return v;
        }
        {
            if self.has_pmmu && self.pmmu_enabled {
                match crate::mmu::translate_address(
                    self,
                    bus,
                    addr,
                    /*write=*/ false,
                    self.is_supervisor(),
                    /*instruction=*/ false,
                ) {
                    Ok(p) => addr = self.address(p),
                    Err(f) => {
                        self.handle_mmu_fault(bus, f, false, false, 4);
                        return 0;
                    }
                }
            }
        }
        match bus.try_read_long(addr) {
            Ok(v) => v,
            Err(f) => {
                if matches!(f.kind, BusFaultKind::BusError) {
                    self.trigger_bus_error(bus, addr, false, false, 4);
                }
                0
            }
        }
    }

    /// Read a three-byte operand from memory (data space), returned in the
    /// low 24 bits.
    ///
    /// The 68020/68030 transfer an operand at the size it spans - byte, word,
    /// three-byte or long (MC68020UM 5.3.1). Only the memory bit-field
    /// instructions produce a three-byte operand, so only the 68020 and later
    /// reach this path; the 68000/68010 have no three-byte transfer.
    #[inline]
    pub fn read_24<B: AddressBus>(&mut self, bus: &mut B, addr: u32) -> u32 {
        if self.faulted() {
            return 0;
        }
        // Part E.2: report internal clocks elapsed before this bus access.
        self.flush_sync(bus);
        let mut addr = self.address(addr);
        if self.has_pmmu && self.pmmu_enabled {
            let pm = self.mmu_page_mask();
            if addr & pm > pm - 2 {
                // Three-byte operand straddling an MMU page: a word cycle and
                // a byte cycle, each translated on its own page (read_16
                // sub-splits further if its half straddles the boundary).
                let hi = self.read_16(bus, addr) as u32;
                if self.faulted() {
                    return 0;
                }
                let lo = self.read_8(bus, addr.wrapping_add(2)) as u32;
                return (hi << 8) | lo;
            }
        }
        if let Some((a, v)) = self.mmu_read_override
            && a == addr
        {
            // RTE'd 030 bus-fault frame with DF cleared: the handler
            // supplied this read's result in the data input buffer.
            self.mmu_read_override = None;
            return v & 0x00FF_FFFF;
        }
        {
            if self.has_pmmu && self.pmmu_enabled {
                match crate::mmu::translate_address(
                    self,
                    bus,
                    addr,
                    /*write=*/ false,
                    self.is_supervisor(),
                    /*instruction=*/ false,
                ) {
                    Ok(p) => addr = self.address(p),
                    Err(f) => {
                        self.handle_mmu_fault(bus, f, false, false, 3);
                        return 0;
                    }
                }
            }
        }
        match bus.try_read_three_bytes(addr) {
            Ok(v) => v & 0x00FF_FFFF,
            Err(f) => {
                if matches!(f.kind, BusFaultKind::BusError) {
                    self.trigger_bus_error(bus, addr, false, false, 3);
                }
                0
            }
        }
    }

    /// Write byte to memory (data space).
    #[inline]
    pub fn write_8<B: AddressBus>(&mut self, bus: &mut B, addr: u32, value: u8) {
        if self.faulted() {
            return;
        }
        // Part E.2: report internal clocks elapsed before this bus access.
        self.flush_sync(bus);
        let mut addr = self.address(addr);
        if self.mmu_write_suppress == Some(addr) {
            // RTE'd 030 bus-fault frame with DF cleared on a write fault:
            // the handler completed or absorbed this write.
            self.mmu_write_suppress = None;
            return;
        }
        self.pending_fault_wdata = value as u32;
        {
            if self.has_pmmu && self.pmmu_enabled {
                match crate::mmu::translate_address(
                    self,
                    bus,
                    addr,
                    /*write=*/ true,
                    self.is_supervisor(),
                    /*instruction=*/ false,
                ) {
                    Ok(p) => addr = self.address(p),
                    Err(f) => {
                        self.handle_mmu_fault(bus, f, true, false, 1);
                        return;
                    }
                }
            }
        }
        if let Err(f) = bus.try_write_byte(addr, value)
            && matches!(f.kind, BusFaultKind::BusError)
        {
            self.trigger_bus_error(bus, addr, true, false, 1);
        }
    }

    /// Write word to memory (data space).
    #[inline]
    pub fn write_16<B: AddressBus>(&mut self, bus: &mut B, addr: u32, value: u16) {
        if self.faulted() {
            return;
        }
        // Part E.2: report internal clocks elapsed before this bus access.
        self.flush_sync(bus);
        let mut addr = self.address(addr);
        if matches!(
            self.cpu_type,
            CpuType::M68000 | CpuType::M68010 | CpuType::SCC68070
        ) && (addr & 1) != 0
        {
            self.trigger_address_error(bus, addr, true, false);
            return;
        }
        if self.has_pmmu && self.pmmu_enabled {
            let pm = self.mmu_page_mask();
            if addr & pm == pm {
                // Misaligned word straddling an MMU page: two byte cycles,
                // each translated (and fault-suppressed) on its own page.
                self.write_8(bus, addr, (value >> 8) as u8);
                if self.faulted() {
                    return;
                }
                self.write_8(bus, addr.wrapping_add(1), value as u8);
                return;
            }
        }
        if self.mmu_write_suppress == Some(addr) {
            // See write_8: DF-cleared write fault, already completed.
            self.mmu_write_suppress = None;
            return;
        }
        self.pending_fault_wdata = value as u32;
        {
            if self.has_pmmu && self.pmmu_enabled {
                match crate::mmu::translate_address(
                    self,
                    bus,
                    addr,
                    /*write=*/ true,
                    self.is_supervisor(),
                    /*instruction=*/ false,
                ) {
                    Ok(p) => addr = self.address(p),
                    Err(f) => {
                        self.handle_mmu_fault(bus, f, true, false, 2);
                        return;
                    }
                }
            }
        }
        if let Err(f) = bus.try_write_word(addr, value)
            && matches!(f.kind, BusFaultKind::BusError)
        {
            self.trigger_bus_error(bus, addr, true, false, 2);
        }
    }

    /// Write the low 24 bits of `value` to memory (data space) as a
    /// three-byte operand.
    ///
    /// See [`CpuCore::read_24`]: the memory bit-field instructions are the
    /// only producers of a three-byte operand.
    #[inline]
    pub fn write_24<B: AddressBus>(&mut self, bus: &mut B, addr: u32, value: u32) {
        if self.faulted() {
            return;
        }
        // Part E.2: report internal clocks elapsed before this bus access.
        self.flush_sync(bus);
        let mut addr = self.address(addr);
        if self.has_pmmu && self.pmmu_enabled {
            let pm = self.mmu_page_mask();
            if addr & pm > pm - 2 {
                // Three-byte operand straddling an MMU page: a word cycle and
                // a byte cycle, each translated (and fault-suppressed) on its
                // own page.
                self.write_16(bus, addr, (value >> 8) as u16);
                if self.faulted() {
                    return;
                }
                self.write_8(bus, addr.wrapping_add(2), value as u8);
                return;
            }
        }
        if self.mmu_write_suppress == Some(addr) {
            // See write_8: DF-cleared write fault, already completed.
            self.mmu_write_suppress = None;
            return;
        }
        self.pending_fault_wdata = value & 0x00FF_FFFF;
        {
            if self.has_pmmu && self.pmmu_enabled {
                match crate::mmu::translate_address(
                    self,
                    bus,
                    addr,
                    /*write=*/ true,
                    self.is_supervisor(),
                    /*instruction=*/ false,
                ) {
                    Ok(p) => addr = self.address(p),
                    Err(f) => {
                        self.handle_mmu_fault(bus, f, true, false, 3);
                        return;
                    }
                }
            }
        }
        if let Err(f) = bus.try_write_three_bytes(addr, value & 0x00FF_FFFF)
            && matches!(f.kind, BusFaultKind::BusError)
        {
            self.trigger_bus_error(bus, addr, true, false, 3);
        }
    }

    /// Write long to memory (data space).
    #[inline]
    pub fn write_32<B: AddressBus>(&mut self, bus: &mut B, addr: u32, value: u32) {
        if self.faulted() {
            return;
        }
        // Part E.2: report internal clocks elapsed before this bus access.
        self.flush_sync(bus);
        let mut addr = self.address(addr);
        if matches!(
            self.cpu_type,
            CpuType::M68000 | CpuType::M68010 | CpuType::SCC68070
        ) && (addr & 1) != 0
        {
            self.trigger_address_error(bus, addr, true, false);
            return;
        }
        if self.has_pmmu && self.pmmu_enabled {
            let pm = self.mmu_page_mask();
            if addr & pm > pm - 3 {
                // Long straddling an MMU page: two word cycles, each
                // translated (and fault-suppressed) on its own page.
                self.write_16(bus, addr, (value >> 16) as u16);
                if self.faulted() {
                    return;
                }
                self.write_16(bus, addr.wrapping_add(2), value as u16);
                return;
            }
        }
        if self.mmu_write_suppress == Some(addr) {
            // See write_8: DF-cleared write fault, already completed.
            self.mmu_write_suppress = None;
            return;
        }
        self.pending_fault_wdata = value;
        {
            if self.has_pmmu && self.pmmu_enabled {
                match crate::mmu::translate_address(
                    self,
                    bus,
                    addr,
                    /*write=*/ true,
                    self.is_supervisor(),
                    /*instruction=*/ false,
                ) {
                    Ok(p) => addr = self.address(p),
                    Err(f) => {
                        self.handle_mmu_fault(bus, f, true, false, 4);
                        return;
                    }
                }
            }
        }
        if let Err(f) = bus.try_write_long(addr, value)
            && matches!(f.kind, BusFaultKind::BusError)
        {
            self.trigger_bus_error(bus, addr, true, false, 4);
        }
    }

    pub(crate) fn handle_mmu_fault<B: AddressBus>(
        &mut self,
        bus: &mut B,
        fault: crate::mmu::MmuFault,
        write: bool,
        instruction: bool,
        size: u32,
    ) {
        use crate::core::exceptions::vector;
        use crate::mmu::MmuFaultKind;

        // Note: Infinite recursion prevention is handled by:
        // 1. exception_processing flag in translate() bypasses MMU during exception handling
        // 2. Double-fault detection in take_exception() halts CPU on recursive faults

        self.pending_fault_cause = Some(fault.cause);
        match fault.kind {
            MmuFaultKind::BusError => {
                self.trigger_bus_error(bus, fault.address, write, instruction, size)
            }
            MmuFaultKind::ConfigurationError => {
                let _ = self.take_exception(bus, vector::MMU_CONFIGURATION_ERROR);
                self.fault_resume = Some((self.pc, self.get_sr(), self.dar));
                self.run_mode = RUN_MODE_BERR_AERR_RESET;
            }
            MmuFaultKind::IllegalOperation => {
                let _ = self.take_exception(bus, vector::MMU_ILLEGAL_OPERATION_ERROR);
                self.fault_resume = Some((self.pc, self.get_sr(), self.dar));
                self.run_mode = RUN_MODE_BERR_AERR_RESET;
            }
            MmuFaultKind::AccessLevelViolation => {
                // Integrated 68030/68040 MMU faults vector to BUS_ERROR
                // (vector 2), not the 68851 access-level vector. Route through
                // trigger_bus_error so the instruction is rolled back and RTE
                // can restart it once the handler fixes the mapping (the 040
                // gets a resumable format-7 frame; the 030 long bus-fault
                // format-A/B frame is still the minimal fallback).
                self.trigger_bus_error(bus, fault.address, write, instruction, size);
            }
        }
        // A faulted MOVES cycle never reaches its own override cleanup: the
        // dispatch above is the instruction's end, so drop the SFC/DFC
        // override here (the frame's SSW has already captured it).
        self.mmu_fc_override = None;
    }

    pub(crate) fn handle_mmu_fetch_fault<B: AddressBus>(
        &mut self,
        bus: &mut B,
        fault: crate::mmu::MmuFault,
    ) {
        use crate::core::exceptions::vector;
        use crate::mmu::MmuFaultKind;

        match fault.kind {
            MmuFaultKind::BusError => {
                self.trigger_bus_error_no_rollback(bus, fault.address, false, true)
            }
            MmuFaultKind::ConfigurationError => {
                let _ = self.take_exception(bus, vector::MMU_CONFIGURATION_ERROR);
                self.run_mode = RUN_MODE_BERR_AERR_RESET;
            }
            MmuFaultKind::IllegalOperation => {
                let _ = self.take_exception(bus, vector::MMU_ILLEGAL_OPERATION_ERROR);
                self.run_mode = RUN_MODE_BERR_AERR_RESET;
            }
            MmuFaultKind::AccessLevelViolation => {
                let _ = self.take_exception(bus, vector::MMU_ACCESS_LEVEL_VIOLATION_ERROR);
                self.run_mode = RUN_MODE_BERR_AERR_RESET;
            }
        }
    }

    /// Execute a COP0/PMMU `0xF0xx` instruction.
    ///
    /// On the 68030 this implements PTEST and PMOVE for TC, SRP, CRP,
    /// TT0, TT1, and MMUSR/PSR. PLOAD and PFLUSH-family encodings are
    /// recognized as compatibility no-ops because the 68030 walker does
    /// not retain translations in an ATC. The 68040 accepts the 030-form
    /// PTEST probes used by 68040.library as no-ops; its architectural MMU
    /// controls use MOVEC and dedicated opcodes. The 68060 rejects this
    /// encoding group.
    ///
    /// Returns zero for an invalid or unsupported encoding so the caller
    /// can take the Line-F exception.
    pub fn exec_mmu_op0<B: AddressBus>(&mut self, bus: &mut B, opcode: u16) -> i32 {
        use super::ea::AddressingMode;
        use super::types::Size;

        // The 68060 has no PMOVE (MMU registers are MOVEC-only) and no
        // 030-form PTEST/PFLUSH in this encoding space: undefined F-line.
        // Watch item: the 040 arm below NOPs 030-form PTESTs because
        // 68040.library issues them during setup; extend that pragmatism
        // here if an OS's 68060 support library turns out to do the same.
        if self.is_060() {
            return 0;
        }

        // MMU ops require PMMU-capable CPU (68030/68040).
        if !self.has_pmmu {
            return 0;
        }
        // The 68040 has none of these 030-form encodings: real silicon
        // raises Line-F even in user mode (the supervisor-mode PTEST/PFLUSH
        // pragmatism below exists only for 68040.library's setup probes).
        if !self.is_supervisor() {
            if self.is_040() {
                return 0;
            }
            return self.exception_privilege(bus);
        }

        // Extension word immediately after opcode.
        let modes = self.read_imm_16(bus);

        // Decode PTEST before the PMOVE register family. On the 68040,
        // accept the 030-form compatibility probe as a NOP.
        let is_ptest = (modes & 0xE000) == 0x8000;
        let is_040 = matches!(
            self.cpu_type,
            super::types::CpuType::M68EC040
                | super::types::CpuType::M68LC040
                | super::types::CpuType::M68040
        );
        if is_ptest && is_040 {
            // 030-form PTEST on the 68040 - treat as NOP (68040.library
            // issues these during setup; the 040 form is 0xF548).
            return 4;
        }
        if is_ptest {
            // 68030 PTEST: walk the tables for the EA in the address space
            // named by the extension word's fc field, at most `level`
            // descriptors deep, and report the outcome in MMUSR. With the
            // A bit set, the physical address of the last descriptor
            // examined lands in An -- mmu.library's lazy fault handler
            // finds the shared descriptor slot to materialize by stepping
            // PTEST through the levels exactly this way.
            let level = ((modes >> 10) & 7) as u32;
            let read = (modes & 0x0200) != 0;
            let a_bit = (modes & 0x0100) != 0;
            let an = ((modes >> 5) & 7) as usize;
            let fcf = (modes & 0x1F) as u32;
            let fc = if fcf & 0x10 != 0 {
                fcf & 7 // immediate
            } else if fcf & 0x08 != 0 {
                self.d((fcf & 7) as usize) & 7 // Dn
            } else if fcf == 1 {
                self.dfc & 7
            } else {
                self.sfc & 7 // 00000 = SFC (00001 = DFC above)
            };
            let ea_mode = ((opcode >> 3) & 0x7) as u8;
            let ea_reg = (opcode & 0x7) as u8;
            let Some(am) = AddressingMode::decode(ea_mode, ea_reg) else {
                return 0;
            };
            let super::ea::EaResult::Memory(addr) = self.resolve_ea(bus, am, Size::Long) else {
                return 0;
            };
            let (sr, desc_addr) = crate::mmu::ptest_030(self, bus, addr, fc, !read, level);
            self.mmu_sr = sr as u32;
            if a_bit && level != 0 {
                self.set_a(an, desc_addr);
            }
            return 8;
        }
        // PLOAD / PFLUSH / PFLUSHA (68030 forms): recognized but not yet
        // fully modelled. Treat them as NOPs rather than returning 0, which
        // the decoder would turn into a LINE-1111 trap -- AROS and the
        // 68040.library issue these during MMU setup, so trapping crashes
        // the boot. There is no ATC on the 030 walk, so a flush has nothing
        // to drop.
        if (modes & 0xFDE0) == 0x2000   // PLOAD
            || (modes & 0xE200) == 0x2000
            || modes == 0xA000          // PFLUSHA
            || modes == 0x2800
            || (modes & 0xFFF8) == 0x2C00
        // PFLUSH
        {
            return 8;
        }

        // Decode effective address from opcode.
        let ea_mode = ((opcode >> 3) & 0x7) as u8;
        let ea_reg = (opcode & 0x7) as u8;
        let Some(am) = AddressingMode::decode(ea_mode, ea_reg) else {
            return 0;
        };

        // Determine whether this is PMOVE <reg> -> <ea> or <ea> -> <reg>.
        // Musashi uses bit 9 (0x0200): if set, it writes EA from MMU reg.
        let to_ea = (modes & 0x0200) != 0;
        let preg = ((modes >> 10) & 0x1F) as u8;

        // Helper: resolve EA and require memory for 64-bit transfers.
        let ea = self.resolve_ea(bus, am, Size::Long);

        fn ea_addr_only(ea: super::ea::EaResult) -> Option<u32> {
            match ea {
                super::ea::EaResult::Memory(a) => Some(a),
                _ => None,
            }
        }

        // 68030 PMOVE preg encoding (5-bit):
        //   0x10 = TC    (32-bit)
        //   0x12 = SRP   (64-bit)
        //   0x13 = CRP   (64-bit)
        //   0x02 = TT0   (32-bit)
        //   0x03 = TT1   (32-bit)
        if to_ea {
            match preg {
                0x10 => {
                    // TC (32)
                    self.write_resolved_ea(bus, ea, Size::Long, self.mmu_tc);
                    4
                }
                0x12 => {
                    // SRP (64): [limit, aptr]
                    let Some(a) = ea_addr_only(ea) else { return 0 };
                    self.write_32(bus, a, self.mmu_srp_limit);
                    self.write_32(bus, a.wrapping_add(4), self.mmu_srp_aptr);
                    8
                }
                0x13 => {
                    // CRP (64)
                    let Some(a) = ea_addr_only(ea) else { return 0 };
                    self.write_32(bus, a, self.mmu_crp_limit);
                    self.write_32(bus, a.wrapping_add(4), self.mmu_crp_aptr);
                    8
                }
                0x02 => {
                    // TT0 (32)
                    self.write_resolved_ea(bus, ea, Size::Long, self.mmu_tt0);
                    4
                }
                0x03 => {
                    // TT1 (32)
                    self.write_resolved_ea(bus, ea, Size::Long, self.mmu_tt1);
                    4
                }
                0x18 => {
                    // MMUSR / PSR (16): how a fault handler reads the PTEST
                    // result (PMOVE PSR,<ea>).
                    self.write_resolved_ea(bus, ea, Size::Word, self.mmu_sr & 0xFFFF);
                    4
                }
                _ => 0,
            }
        } else {
            match preg {
                0x10 => {
                    // TC (32)
                    let v = self.read_resolved_ea(bus, ea, Size::Long);
                    self.mmu_tc = v;
                    // PMOVE is 68030-only, so tc_enable() reads TC[31] here.
                    self.pmmu_enabled = self.tc_enable();
                    4
                }
                0x12 => {
                    // SRP (64)
                    let Some(a) = ea_addr_only(ea) else { return 0 };
                    let limit = self.read_32(bus, a);
                    let aptr = self.read_32(bus, a.wrapping_add(4));
                    self.mmu_srp_limit = limit;
                    self.mmu_srp_aptr = aptr;
                    8
                }
                0x13 => {
                    // CRP (64)
                    let Some(a) = ea_addr_only(ea) else { return 0 };
                    let limit = self.read_32(bus, a);
                    let aptr = self.read_32(bus, a.wrapping_add(4));
                    self.mmu_crp_limit = limit;
                    self.mmu_crp_aptr = aptr;
                    8
                }
                0x02 => {
                    // TT0 (32)
                    let v = self.read_resolved_ea(bus, ea, Size::Long);
                    self.mmu_tt0 = v;
                    4
                }
                0x03 => {
                    // TT1 (32)
                    let v = self.read_resolved_ea(bus, ea, Size::Long);
                    self.mmu_tt1 = v;
                    4
                }
                0x18 => {
                    // MMUSR / PSR (16)
                    let v = self.read_resolved_ea(bus, ea, Size::Word);
                    self.mmu_sr = v & 0xFFFF;
                    4
                }
                _ => 0,
            }
        }
    }

    // ========== SR/CCR Access ==========

    /// Get Status Register (composed from flags).
    pub fn get_sr(&self) -> u16 {
        let mut sr = 0u16;
        sr |= (self.t1_flag & 0x8000) as u16;
        sr |= (self.t0_flag & 0x4000) as u16;
        sr |= ((self.s_flag & SFLAG_SET) << 11) as u16;
        sr |= ((self.m_flag & MFLAG_SET) << 11) as u16;
        sr |= (self.int_mask & 0x0700) as u16;
        sr |= ((self.x_flag & XFLAG_SET) >> 4) as u16;
        sr |= ((self.n_flag & NFLAG_SET) >> 4) as u16;
        sr |= if self.not_z_flag == 0 { 0x04 } else { 0x00 };
        sr |= ((self.v_flag & VFLAG_SET) >> 6) as u16;
        sr |= ((self.c_flag & CFLAG_SET) >> 8) as u16;
        sr
    }

    /// Set Status Register (decomposes to flags) with stack banking.
    pub fn set_sr(&mut self, sr: u16) {
        let sr = sr & self.sr_mask as u16;
        self.t1_flag = (sr as u32) & 0x8000;
        self.t0_flag = (sr as u32) & 0x4000;
        self.int_mask = (sr as u32) & 0x0700;
        self.set_ccr_internal(sr as u8);
        // Set S and M with banking (M must be 0 when S=0)
        let mut sm = ((sr >> 11) & 6) as u32;
        if (sm & SFLAG_SET) == 0 {
            sm &= !MFLAG_SET;
        }
        self.set_sm_flag(sm);
    }

    /// Set SR without interrupt check or stack pointer change.
    pub fn set_sr_noint_nosp(&mut self, sr: u16) {
        let sr = sr & self.sr_mask as u16;
        self.t1_flag = (sr as u32) & 0x8000;
        self.t0_flag = (sr as u32) & 0x4000;
        self.int_mask = (sr as u32) & 0x0700;
        self.set_ccr_internal(sr as u8);
        let mut sm = ((sr >> 11) & 6) as u32;
        if (sm & SFLAG_SET) == 0 {
            sm &= !MFLAG_SET;
        }
        self.set_sm_flag_nosp(sm);
    }

    /// Internal CCR setter.
    fn set_ccr_internal(&mut self, ccr: u8) {
        self.x_flag = if ccr & 0x10 != 0 { XFLAG_SET } else { 0 };
        self.n_flag = if ccr & 0x08 != 0 { NFLAG_SET } else { 0 };
        self.not_z_flag = if ccr & 0x04 != 0 { 0 } else { 1 };
        self.v_flag = if ccr & 0x02 != 0 { VFLAG_SET } else { 0 };
        self.c_flag = if ccr & 0x01 != 0 { CFLAG_SET } else { 0 };
    }

    /// Get Condition Code Register (low byte of SR).
    pub fn get_ccr(&self) -> u8 {
        (self.get_sr() & 0xFF) as u8
    }

    /// Set Condition Code Register.
    pub fn set_ccr(&mut self, ccr: u8) {
        self.set_ccr_internal(ccr);
    }

    // ========== Flag Helpers ==========

    #[inline]
    /// Return whether the extend (X) condition-code bit is set.
    pub fn flag_x(&self) -> bool {
        self.x_flag != 0
    }
    #[inline]
    /// Return whether the negative (N) condition-code bit is set.
    pub fn flag_n(&self) -> bool {
        self.n_flag != 0
    }
    #[inline]
    /// Return whether the zero (Z) condition-code bit is set.
    pub fn flag_z(&self) -> bool {
        self.not_z_flag == 0
    }
    #[inline]
    /// Return whether the overflow (V) condition-code bit is set.
    pub fn flag_v(&self) -> bool {
        self.v_flag != 0
    }
    #[inline]
    /// Return whether the carry (C) condition-code bit is set.
    pub fn flag_c(&self) -> bool {
        self.c_flag != 0
    }
    #[inline]
    /// Return whether the CPU is currently in supervisor mode.
    pub fn is_supervisor(&self) -> bool {
        self.s_flag != 0
    }

    // ========== Condition Tests ==========

    /// Evaluate condition code.
    pub fn test_condition(&self, cond: u8) -> bool {
        match cond & 0x0F {
            0x0 => true,                                               // T
            0x1 => false,                                              // F
            0x2 => !self.flag_c() && !self.flag_z(),                   // HI
            0x3 => self.flag_c() || self.flag_z(),                     // LS
            0x4 => !self.flag_c(),                                     // CC/HS
            0x5 => self.flag_c(),                                      // CS/LO
            0x6 => !self.flag_z(),                                     // NE
            0x7 => self.flag_z(),                                      // EQ
            0x8 => !self.flag_v(),                                     // VC
            0x9 => self.flag_v(),                                      // VS
            0xA => !self.flag_n(),                                     // PL
            0xB => self.flag_n(),                                      // MI
            0xC => self.flag_n() == self.flag_v(),                     // GE
            0xD => self.flag_n() != self.flag_v(),                     // LT
            0xE => !self.flag_z() && (self.flag_n() == self.flag_v()), // GT
            0xF => self.flag_z() || (self.flag_n() != self.flag_v()),  // LE
            _ => true,
        }
    }
}