m68k 0.5.1

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
//! Main execution loop.
//!
//! Implements the fetch-decode-execute cycle.

use super::cpu::{CpuCore, SFLAG_SET};
use super::decode::{dispatch_instruction, needs_rollback_snapshot};
use super::memory::AddressBus;
use super::op_cache::BatchInnerExit;
use super::trace_jit;
use super::types::{BatchExit, BatchResult, CycleBatchExit, CycleBatchResult, StepResult};

/// Stop level constants.
pub const STOP_LEVEL_STOP: u32 = 1;
/// Halted after a double bus/address fault; only reset can resume execution.
pub const STOP_LEVEL_HALT: u32 = 2;

/// Run mode constants.
pub const RUN_MODE_NORMAL: u32 = 0;
/// Bus/address-error recovery or reset processing is active.
pub const RUN_MODE_BERR_AERR_RESET: u32 = 1;

impl CpuCore {
    #[inline]
    fn prepare_rollback_snapshot(&mut self, opcode: u16) {
        if needs_rollback_snapshot(opcode) {
            self.dar_save = self.dar;
            self.sr_save = self.get_sr();
        } else if (self.t1_flag | self.t0_flag) != 0 {
            // Trace checks still need the pre-instruction SR. Simple no-fault instructions do
            // not need the D/A rollback snapshot.
            self.sr_save = self.get_sr();
        } else {
            self.sr_save = 0;
        }
    }

    /// Unconditional snapshot for paths where the opcode is already known
    /// not to be a simple op (a decoded-op-cache miss). Skips
    /// `needs_rollback_snapshot`, which would re-run the full simple-op
    /// decode just to conclude the same thing.
    #[inline]
    fn prepare_rollback_snapshot_full(&mut self) {
        self.dar_save = self.dar;
        self.sr_save = self.get_sr();
    }

    /// Execute instructions for the given number of cycles.
    ///
    /// Returns the number of cycles actually consumed.
    ///
    /// Trap instructions are taken as hardware exceptions. Use
    /// [`step`](Self::step) when the host needs to intercept trap opcodes.
    pub fn execute<B: AddressBus>(&mut self, bus: &mut B, num_cycles: i32) -> i32 {
        self.set_precise_bus(true);
        // Handle reset cycles
        if self.reset_cycles > 0 {
            let rc = self.reset_cycles as i32;
            self.reset_cycles = 0;
            let remaining = num_cycles - rc;
            if remaining <= 0 {
                return rc;
            }
            self.cycles_remaining = remaining;
        } else {
            self.cycles_remaining = num_cycles;
        }
        self.initial_cycles = num_cycles;

        // Check for pending interrupts
        self.check_and_service_interrupts(bus);

        // If stopped, run the stopped-state supervisor check (a STOP that
        // loaded an S-clear SR wakes into a privilege violation here);
        // otherwise consume no cycles.
        if self.stopped != 0 {
            if let Some(cycles) = self.stopped_supervisor_check(bus) {
                self.cycles_remaining -= cycles;
            } else {
                self.cycles_remaining = 0;
                return self.initial_cycles;
            }
        }

        // Main execution loop
        while self.cycles_remaining > 0 {
            self.instruction_exception_vector = None;
            bus.begin_instruction_fetches();
            // Save previous PC
            self.ppc = self.pc;

            // Save D/A registers for bus error recovery
            self.dar_save = self.dar;
            // Save SR for bus/address error recovery
            self.sr_save = self.get_sr();

            // Fetch opcode
            self.ir = self.fetch_opcode(bus) as u32;

            // If a bus/address error occurred during fetch, the exception is already taken.
            if self.run_mode == RUN_MODE_BERR_AERR_RESET {
                self.end_faulted_instruction();
                // A double fault halts the CPU: no further fetches, and the
                // fault run mode is left set for is_halted().
                if self.stopped != 0 {
                    break;
                }
                continue;
            }

            // Dispatch instruction (sampling whether the opcode fetch
            // hit the icache before dispatch consumes more of the stream).
            let opcode_fetch_cached = bus.last_fetch_was_cached();
            let result = dispatch_instruction(self, bus, self.ir as u16);
            let fetch_cached = if matches!(
                self.cpu_type,
                super::types::CpuType::M68EC020 | super::types::CpuType::M68020
            ) {
                bus.instruction_fetches_were_cached()
            } else {
                opcode_fetch_cached
            };

            // Auto-take all trap exceptions, extract cycles
            use crate::core::types::InternalStepResult;
            let cycles = match result {
                InternalStepResult::Ok { cycles } => self.finalize_cycles(cycles, fetch_cached),
                InternalStepResult::AlineTrap { .. } => self.take_aline_exception(bus),
                InternalStepResult::FlineTrap { .. } => self.take_fline_exception(bus),
                InternalStepResult::TrapInstruction { trap_num } => {
                    self.take_trap_exception(bus, trap_num)
                }
                InternalStepResult::Breakpoint { .. } => self.take_bkpt_exception(bus),
                InternalStepResult::IllegalInstruction { .. } => self.take_illegal_exception(bus),
            };
            self.cycles_remaining -= cycles;

            // If a bus/address error occurred mid-instruction, we already built the exception frame
            // and jumped to the handler. Skip trace/interrupt checks for the faulting instruction.
            if self.run_mode == RUN_MODE_BERR_AERR_RESET {
                self.end_faulted_instruction();
                // A double fault halts the CPU: stop the batch dead instead
                // of letting another opcode through before the bottom-of-loop
                // stopped check.
                if self.stopped != 0 {
                    break;
                }
                continue;
            }

            // End-of-instruction prefetch: top the queue back up to two words
            // (a no-op after flow changes, whose refill already filled it).
            self.top_up_prefetch(bus);

            // Check for trace exception (T1 flag set before instruction)
            if self.check_trace() {
                let trace_cycles = self.exception_trace(bus);
                self.cycles_remaining -= trace_cycles;
            }

            // Check for interrupts after each instruction
            if self.int_level > 0 {
                self.check_and_service_interrupts(bus);
            }

            // Check if stopped/halted
            if self.stopped != 0 {
                break;
            }
        }

        // Return cycles consumed
        self.initial_cycles - self.cycles_remaining
    }

    /// Execute complete instructions until `cycle_budget` is met or crossed,
    /// or until an event requiring host attention occurs.
    ///
    /// This is the cycle-scheduled counterpart to [`run_batch`](Self::run_batch):
    /// it keeps the transaction-exact [`AddressBus`] execution contract and
    /// reports the actual cycle count, while surfacing traps in the same CPU
    /// and PC state as [`step`](Self::step).
    ///
    /// # Boundary semantics
    ///
    /// - Instructions are never split. The final instruction may overshoot
    ///   the budget.
    /// - A surfaced A-line/F-line/TRAP/BKPT/illegal instruction is not counted
    ///   in `instructions`, and no exception-entry cycles are charged.
    /// - RESET executes synchronously, calls [`AddressBus::reset_devices`],
    ///   and counts as an instruction.
    /// - Exceptions raised internally by an instruction (for example,
    ///   divide-by-zero, privilege, bus, and address faults) complete their
    ///   exception entry and the faulting instruction is counted.
    /// - A serviceable interrupt is taken on entry or after an instruction.
    ///   Its entry cycles are included, but it does not increment the
    ///   instruction count. An interrupt can therefore satisfy the budget
    ///   before the first handler instruction executes.
    /// - A non-positive budget returns immediately with
    ///   [`CycleBatchExit::BudgetExhausted`].
    /// - A bus boundary request is polled after each normally completed
    ///   instruction. It includes that instruction in both totals and takes
    ///   precedence over simultaneous budget exhaustion. STOP and surfaced
    ///   traps retain their existing exit reasons.
    pub fn run_for_cycles<B: AddressBus>(
        &mut self,
        bus: &mut B,
        cycle_budget: i32,
    ) -> CycleBatchResult {
        self.set_precise_bus(true);
        self.initial_cycles = cycle_budget;

        if cycle_budget <= 0 {
            self.cycles_remaining = cycle_budget;
            return CycleBatchResult {
                cycles: 0,
                instructions: 0,
                exit: CycleBatchExit::BudgetExhausted,
            };
        }

        if self.reset_cycles > 0 {
            let reset_cycles = self.reset_cycles as i32;
            self.reset_cycles = 0;
            self.cycles_remaining = cycle_budget - reset_cycles;
        } else {
            self.cycles_remaining = cycle_budget;
        }

        // Interrupts are instruction-boundary events. Service one before the
        // first fetch, including when it wakes a stopped CPU.
        self.check_and_service_interrupts(bus);

        let mut instructions = 0;
        loop {
            if self.cycles_remaining <= 0 {
                return CycleBatchResult {
                    cycles: self.initial_cycles - self.cycles_remaining,
                    instructions,
                    exit: CycleBatchExit::BudgetExhausted,
                };
            }
            if self.stopped != 0 {
                return CycleBatchResult {
                    cycles: self.initial_cycles - self.cycles_remaining,
                    instructions,
                    exit: CycleBatchExit::Stopped,
                };
            }

            match self.step(bus) {
                StepResult::Ok { cycles } => {
                    self.cycles_remaining -= cycles;
                    instructions += 1;
                    // STOP is an observable exit even when its own cycles
                    // simultaneously exhaust the budget.
                    if self.stopped != 0 {
                        return CycleBatchResult {
                            cycles: self.initial_cycles - self.cycles_remaining,
                            instructions,
                            exit: CycleBatchExit::Stopped,
                        };
                    }
                    if bus.take_boundary_request() {
                        return CycleBatchResult {
                            cycles: self.initial_cycles - self.cycles_remaining,
                            instructions,
                            exit: CycleBatchExit::BoundaryRequested,
                        };
                    }
                }
                StepResult::Stopped => {
                    return CycleBatchResult {
                        cycles: self.initial_cycles - self.cycles_remaining,
                        instructions,
                        exit: CycleBatchExit::Stopped,
                    };
                }
                StepResult::AlineTrap { opcode } => {
                    return CycleBatchResult {
                        cycles: self.initial_cycles - self.cycles_remaining,
                        instructions,
                        exit: CycleBatchExit::AlineTrap { opcode },
                    };
                }
                StepResult::FlineTrap { opcode } => {
                    return CycleBatchResult {
                        cycles: self.initial_cycles - self.cycles_remaining,
                        instructions,
                        exit: CycleBatchExit::FlineTrap { opcode },
                    };
                }
                StepResult::TrapInstruction { trap_num } => {
                    return CycleBatchResult {
                        cycles: self.initial_cycles - self.cycles_remaining,
                        instructions,
                        exit: CycleBatchExit::TrapInstruction { trap_num },
                    };
                }
                StepResult::Breakpoint { bp_num } => {
                    return CycleBatchResult {
                        cycles: self.initial_cycles - self.cycles_remaining,
                        instructions,
                        exit: CycleBatchExit::Breakpoint { bp_num },
                    };
                }
                StepResult::IllegalInstruction { opcode } => {
                    return CycleBatchResult {
                        cycles: self.initial_cycles - self.cycles_remaining,
                        instructions,
                        exit: CycleBatchExit::IllegalInstruction { opcode },
                    };
                }
            }
        }
    }

    /// Execute up to `max_instructions` instructions, returning on the first
    /// interesting event.
    ///
    /// This is the fast path for High-Level Emulation embedders that would
    /// otherwise call [`step`](Self::step) in a loop: the whole batch runs
    /// inside the decoded-operation and trace-execution loops, and control
    /// returns to the caller only when it has something to do:
    ///
    /// - a trap the embedder wants to intercept (A-line/F-line/TRAP/BKPT/
    ///   illegal — surfaced exactly like [`step`](Self::step), never taken
    ///   as a hardware exception),
    /// - the CPU stopping (STOP instruction),
    /// - execution reaching a PC listed in `watch_pcs`, or
    /// - the instruction budget running out.
    ///
    /// Watch semantics: `watch_pcs` is checked after every retired
    /// instruction, *before* the instruction at the new PC executes. The
    /// entry PC is intentionally **not** checked, so a caller that resumes
    /// from a watched PC does not loop forever; keep the list short (it is
    /// scanned linearly).
    ///
    /// Unlike [`execute`](Self::execute), this entry point is
    /// instruction-budgeted and does not maintain cycle accounting
    /// (`cycles_remaining` is clobbered). Trace exceptions are taken
    /// internally and pending interrupts are serviced between instructions,
    /// matching [`step`](Self::step) semantics.
    pub fn run_batch<B: AddressBus>(
        &mut self,
        bus: &mut B,
        max_instructions: u32,
        watch_pcs: &[u32],
    ) -> BatchResult {
        let prior_precision = self.precise_bus;
        self.set_precise_bus(false);
        // Capture the bus's fastmem window for the duration of this batch.
        // Never with an active MMU: fastmem addresses are physical.
        if !(self.has_pmmu && self.pmmu_enabled)
            && let Some(fm) = bus.fast_mem()
            && fm.len >= 4
            && !fm.ptr.is_null()
        {
            self.fm_ptr = fm.ptr as usize;
            self.fm_base = fm.base;
            self.fm_len = fm.len;
            // Memory traces are skipped (and probe-filtered) while no
            // window is active; with the window up they can run, so
            // re-arm the trace filters.
            self.trace_record_skip = [super::trace_jit::TRACE_PC_NONE; 4];
            self.trace_probe_skip = [super::trace_jit::TRACE_PC_NONE; 4];
        }
        let result = self.run_batch_inner(bus, max_instructions, watch_pcs);
        self.fm_ptr = 0;
        self.fm_base = 0;
        self.fm_len = 0;
        self.set_precise_bus(prior_precision);
        result
    }

    fn run_batch_inner<B: AddressBus>(
        &mut self,
        bus: &mut B,
        max_instructions: u32,
        watch_pcs: &[u32],
    ) -> BatchResult {
        use crate::core::types::InternalStepResult;

        if self.stopped != 0 {
            return BatchResult {
                instructions: 0,
                exit: BatchExit::Stopped,
            };
        }

        let mut retired: u32 = 0;
        let mut probe_on_entry = true;

        loop {
            // The trace JIT's headroom guard compares against
            // `cycles_remaining`; keep it topped up so it can never gate a
            // trace in this instruction-budgeted mode (traces decrement it
            // as they run).
            self.cycles_remaining = i32::MAX / 2;

            if retired >= max_instructions {
                return BatchResult {
                    instructions: retired,
                    exit: BatchExit::BudgetExhausted,
                };
            }

            let mut known_complex = false;
            let opcode = if self.can_run_decoded_simple_ops() {
                match self.run_decoded_simple_batch(
                    bus,
                    max_instructions - retired,
                    watch_pcs,
                    &mut retired,
                    probe_on_entry,
                ) {
                    BatchInnerExit::Budget => {
                        return BatchResult {
                            instructions: retired,
                            exit: BatchExit::BudgetExhausted,
                        };
                    }
                    BatchInnerExit::Watched(pc) => {
                        return BatchResult {
                            instructions: retired,
                            exit: BatchExit::WatchedPc { pc },
                        };
                    }
                    BatchInnerExit::Fault => {
                        self.run_mode = RUN_MODE_NORMAL;
                        probe_on_entry = true;
                        continue;
                    }
                    BatchInnerExit::Miss(opcode) => {
                        known_complex = true;
                        opcode
                    }
                }
            } else {
                self.ppc = self.pc;
                let opcode = self.read_opcode_16(bus);
                if self.run_mode == RUN_MODE_BERR_AERR_RESET {
                    self.run_mode = RUN_MODE_NORMAL;
                    probe_on_entry = true;
                    continue;
                }
                self.ir = opcode as u32;
                opcode
            };

            if self.ir != opcode as u32 {
                self.ir = opcode as u32;
            }

            if known_complex {
                self.prepare_rollback_snapshot_full();
            } else {
                self.prepare_rollback_snapshot(opcode);
            }

            let result = dispatch_instruction(self, bus, opcode);

            // A dispatched instruction may have enabled the MMU
            // (PMOVE/MOVEC); fastmem addresses are physical, so drop the
            // window as soon as translation turns on.
            if self.fm_len != 0 && self.has_pmmu && self.pmmu_enabled {
                self.fm_ptr = 0;
                self.fm_base = 0;
                self.fm_len = 0;
            }

            let exit = match result {
                InternalStepResult::Ok { .. } => None,
                InternalStepResult::AlineTrap { opcode } => Some(BatchExit::AlineTrap { opcode }),
                InternalStepResult::FlineTrap { opcode } => Some(BatchExit::FlineTrap { opcode }),
                InternalStepResult::TrapInstruction { trap_num } => {
                    Some(BatchExit::TrapInstruction { trap_num })
                }
                InternalStepResult::Breakpoint { bp_num } => Some(BatchExit::Breakpoint { bp_num }),
                InternalStepResult::IllegalInstruction { opcode } => {
                    Some(BatchExit::IllegalInstruction { opcode })
                }
            };
            if let Some(exit) = exit {
                return BatchResult {
                    instructions: retired,
                    exit,
                };
            }
            retired += 1;

            // A bus/address error mid-instruction already built the exception
            // frame and jumped to the handler; skip trace/interrupt checks
            // for the faulting instruction (mirrors `execute`).
            if self.run_mode == RUN_MODE_BERR_AERR_RESET {
                self.run_mode = RUN_MODE_NORMAL;
                probe_on_entry = true;
            } else {
                // Mirrors `execute`: only backward branches can reach a
                // trace head, so straight-line dispatches re-enter the
                // fast loop without a trace-cache probe.
                probe_on_entry =
                    self.pc <= self.ppc && trace_jit::note_backward_branch(self, self.cpu_type);

                if !self.sst_m68000_compat && self.check_trace() {
                    let _ = self.exception_trace(bus);
                }

                if self.int_level > 0 {
                    self.check_and_service_interrupts(bus);
                }
            }

            if self.stopped != 0 {
                return BatchResult {
                    instructions: retired,
                    exit: BatchExit::Stopped,
                };
            }

            if !watch_pcs.is_empty() && watch_pcs.contains(&self.pc) {
                return BatchResult {
                    instructions: retired,
                    exit: BatchExit::WatchedPc { pc: self.pc },
                };
            }
        }
    }

    /// Execute a single instruction.
    ///
    /// Returns a `StepResult` indicating:
    /// - `Ok { cycles }` - Normal instruction execution
    /// - `Stopped` - CPU is stopped
    ///
    /// Traps are surfaced as `StepResult` variants; exceptions are not taken
    /// automatically in this mode. For HLE interception with automatic fallback
    /// to exceptions, use `step_with_hle_handler()`.
    pub fn step<B: AddressBus>(&mut self, bus: &mut B) -> StepResult {
        use crate::core::types::{InternalStepResult, StepResult};

        self.set_precise_bus(true);
        if self.stopped != 0 {
            if let Some(cycles) = self.stopped_supervisor_check(bus) {
                return StepResult::Ok { cycles };
            }
            return StepResult::Stopped;
        }

        self.instruction_exception_vector = None;
        bus.begin_instruction_fetches();
        self.ppc = self.pc;
        self.dar_save = self.dar;
        self.sr_save = self.get_sr();
        self.ir = self.fetch_opcode(bus) as u32;

        if self.run_mode == RUN_MODE_BERR_AERR_RESET {
            self.end_faulted_instruction();
            return StepResult::Ok { cycles: 0 };
        }

        let opcode_fetch_cached = bus.last_fetch_was_cached();
        let result = dispatch_instruction(self, bus, self.ir as u16);
        let fetch_cached = if matches!(
            self.cpu_type,
            super::types::CpuType::M68EC020 | super::types::CpuType::M68020
        ) {
            bus.instruction_fetches_were_cached()
        } else {
            opcode_fetch_cached
        };

        if !matches!(result, InternalStepResult::Ok { .. }) {
            self.clear_execution_pipeline_state();
        }

        let res = match result {
            InternalStepResult::Ok { cycles } => StepResult::Ok {
                cycles: self.finalize_cycles(cycles, fetch_cached),
            },
            InternalStepResult::AlineTrap { opcode } => StepResult::AlineTrap { opcode },
            InternalStepResult::FlineTrap { opcode } => StepResult::FlineTrap { opcode },
            InternalStepResult::TrapInstruction { trap_num } => {
                StepResult::TrapInstruction { trap_num }
            }
            InternalStepResult::Breakpoint { bp_num } => StepResult::Breakpoint { bp_num },
            InternalStepResult::IllegalInstruction { opcode } => {
                StepResult::IllegalInstruction { opcode }
            }
        };

        if matches!(res, StepResult::Ok { .. }) {
            if self.run_mode == RUN_MODE_BERR_AERR_RESET {
                self.end_faulted_instruction();
                return res;
            }

            // End-of-instruction prefetch: top the queue back up to two words
            // (a no-op after flow changes, whose refill already filled it).
            self.top_up_prefetch(bus);

            // Check for trace exception
            if !self.sst_m68000_compat && self.check_trace() {
                let trace_cycles = self.exception_trace(bus);
                if let StepResult::Ok { cycles } = res {
                    return StepResult::Ok {
                        cycles: cycles + trace_cycles,
                    };
                }
            }

            // Check for interrupts after instruction
            if self.int_level > 0 {
                self.check_and_service_interrupts(bus);
            }
        }

        res
    }

    /// Execute a single instruction with HLE trap handling (CPU + bus access).
    ///
    /// This method is the preferred way to run the CPU with High-Level Emulation.
    /// When a trap instruction is encountered, the appropriate `HleHandler` method
    /// is called. If the handler returns `true`, the trap is considered handled
    /// and execution continues. If it returns `false` (or is not implemented),
    /// the real hardware exception is taken automatically.
    ///
    /// # Example
    /// ```
    /// use m68k::{AddressBus, CpuCore, HleHandler};
    ///
    /// struct MyHandler { handled: bool }
    /// impl HleHandler for MyHandler {
    ///     fn handle_aline(
    ///         &mut self,
    ///         _cpu: &mut CpuCore,
    ///         _bus: &mut dyn AddressBus,
    ///         _opcode: u16,
    ///     ) -> bool {
    ///         self.handled = true;
    ///         true // HLE handled it
    ///     }
    /// }
    /// ```
    pub fn step_with_hle_handler<B: AddressBus, T: super::types::HleHandler>(
        &mut self,
        bus: &mut B,
        handler: &mut T,
    ) -> StepResult {
        use crate::core::types::{InternalStepResult, StepResult};

        self.set_precise_bus(true);
        if self.stopped != 0 {
            if let Some(cycles) = self.stopped_supervisor_check(bus) {
                return StepResult::Ok { cycles };
            }
            return StepResult::Stopped;
        }

        self.instruction_exception_vector = None;
        bus.begin_instruction_fetches();
        self.ppc = self.pc;
        self.dar_save = self.dar;
        self.sr_save = self.get_sr();
        self.ir = self.fetch_opcode(bus) as u32;

        if self.run_mode == RUN_MODE_BERR_AERR_RESET {
            self.end_faulted_instruction();
            return StepResult::Ok { cycles: 0 };
        }

        let opcode_fetch_cached = bus.last_fetch_was_cached();
        let result = dispatch_instruction(self, bus, self.ir as u16);
        let fetch_cached = if matches!(
            self.cpu_type,
            super::types::CpuType::M68EC020 | super::types::CpuType::M68020
        ) {
            bus.instruction_fetches_were_cached()
        } else {
            opcode_fetch_cached
        };

        // A surfaced or HLE-handled trap still represents an architectural
        // execution boundary. Clear timing state before invoking callbacks,
        // since a handler may itself resume execution.
        if !matches!(result, InternalStepResult::Ok { .. }) {
            self.clear_execution_pipeline_state();
        }

        // Handle trap results via callbacks, fallback to exception if not handled
        let cycles = match result {
            InternalStepResult::Ok { cycles } => self.finalize_cycles(cycles, fetch_cached),
            InternalStepResult::AlineTrap { opcode } => {
                if !handler.handle_aline(self, bus, opcode) {
                    self.take_aline_exception(bus)
                } else {
                    0 // HLE handled, 0 cycles for now
                }
            }
            InternalStepResult::FlineTrap { opcode } => {
                if !handler.handle_fline(self, bus, opcode) {
                    self.take_fline_exception(bus)
                } else {
                    0
                }
            }
            InternalStepResult::TrapInstruction { trap_num } => {
                if !handler.handle_trap(self, bus, trap_num) {
                    self.take_trap_exception(bus, trap_num)
                } else {
                    0
                }
            }
            InternalStepResult::Breakpoint { bp_num } => {
                if !handler.handle_breakpoint(self, bus, bp_num) {
                    self.take_bkpt_exception(bus)
                } else {
                    0
                }
            }
            InternalStepResult::IllegalInstruction { opcode } => {
                if !handler.handle_illegal(self, bus, opcode) {
                    self.take_illegal_exception(bus)
                } else {
                    0
                }
            }
        };

        if self.run_mode == RUN_MODE_BERR_AERR_RESET {
            self.end_faulted_instruction();
            return StepResult::Ok { cycles };
        }

        // End-of-instruction prefetch: top the queue back up to two words
        // (a no-op after flow changes, whose refill already filled it).
        self.top_up_prefetch(bus);

        // Check for trace exception
        if !self.sst_m68000_compat && self.check_trace() {
            let trace_cycles = self.exception_trace(bus);
            return StepResult::Ok {
                cycles: cycles + trace_cycles,
            };
        }

        // Check for interrupts after instruction
        if self.int_level > 0 {
            self.check_and_service_interrupts(bus);
        }

        StepResult::Ok { cycles }
    }

    // ========== Stack Operations ==========

    /// Push a word onto the stack.
    #[inline]
    pub fn push_16<B: AddressBus>(&mut self, bus: &mut B, value: u16) {
        self.dar[15] = self.dar[15].wrapping_sub(2);
        self.write_16(bus, self.dar[15], value);
    }

    /// Push a long onto the stack.
    #[inline]
    pub fn push_32<B: AddressBus>(&mut self, bus: &mut B, value: u32) {
        self.dar[15] = self.dar[15].wrapping_sub(4);
        self.write_32(bus, self.dar[15], value);
    }

    /// Pull a word from the stack.
    #[inline]
    pub fn pull_16<B: AddressBus>(&mut self, bus: &mut B) -> u16 {
        let value = self.read_16(bus, self.dar[15]);
        self.dar[15] = self.dar[15].wrapping_add(2);
        value
    }

    /// Pull a long from the stack.
    #[inline]
    pub fn pull_32<B: AddressBus>(&mut self, bus: &mut B) -> u32 {
        let value = self.read_32(bus, self.dar[15]);
        self.dar[15] = self.dar[15].wrapping_add(4);
        value
    }

    // ========== Program Flow ==========

    /// Jump to a new PC.
    #[inline]
    pub fn jump(&mut self, new_pc: u32) {
        self.pc = self.address(new_pc);
    }

    /// Jump to an exception vector.
    pub fn jump_vector<B: AddressBus>(&mut self, bus: &mut B, vector: u32) {
        // Any exception entry breaks open execution-pipeline state.
        self.clear_execution_pipeline_state();
        // An earlier poll-point hold must not survive into the handler:
        // the refill below is a fresh IPL poll point (Moira jumpToVector
        // polls during the final refill read).
        bus.ipl_release_sample();
        // Any vectored dispatch ends 68010 loop mode; the refill below
        // restores normal instruction fetching.
        self.loop_mode = false;
        self.last_exception_vector = Some(vector);
        self.instruction_exception_vector = Some(vector);
        let addr = (vector << 2).wrapping_add(self.vbr);
        self.pc = self.read_32(bus, addr);
        // Exception entry refills the prefetch queue from the handler
        // address, with 2 internal clocks between the two refill reads.
        self.prefetch_first(bus);
        self.internal_cycles(2);
        self.prefetch_second(bus);
    }

    /// Branch with 8-bit displacement.
    #[inline]
    pub fn branch_8(&mut self, offset: u8) {
        self.pc = self.pc.wrapping_add(offset as i8 as i32 as u32);
    }

    /// Branch with 16-bit displacement.
    #[inline]
    pub fn branch_16(&mut self, offset: u16) {
        self.pc = self.pc.wrapping_add(offset as i16 as i32 as u32);
    }

    /// Branch with 32-bit displacement.
    #[inline]
    pub fn branch_32(&mut self, offset: u32) {
        self.pc = self.pc.wrapping_add(offset);
    }

    // ========== Interrupt Handling ==========

    /// Check and service pending interrupts.
    fn check_and_service_interrupts<B: AddressBus>(&mut self, bus: &mut B) {
        // NMI (level 7) always triggers, others compare to mask
        let mask_level = (self.int_mask >> 8) & 7;
        let int_level = self.int_level & 7;

        if int_level == 7 || int_level > mask_level {
            self.service_interrupt(bus, int_level as u8);
            // Clear pending interrupt level - bus.interrupt_acknowledge was called in
            // service_interrupt, so the device has had a chance to update its state.
            // We clear cpu.int_level here; the test harness will re-poll and set it
            // again in the next step if another interrupt is pending.
            self.int_level = 0;
        }
    }

    /// Map an interrupt-acknowledge response to a vector number.
    #[inline]
    fn iack_vector(response: u32, level: u8) -> u32 {
        if response == 0xFFFFFFFF {
            // Autovector
            24 + level as u32
        } else {
            response & 0xFF
        }
    }

    /// Service an interrupt.
    fn service_interrupt<B: AddressBus>(&mut self, bus: &mut B, level: u8) {
        // Match Musashi `m68ki_exception_interrupt`:
        // - save old SR
        // - clear trace, enter supervisor (but do not modify M)
        // - set interrupt mask
        // - stack format-0 frame; if M=1 and 68020+ also stack a format-1 throwaway frame on ISP
        let old_sr = self.get_sr();
        self.t1_flag = 0;
        self.t0_flag = 0;
        self.set_s_flag(SFLAG_SET);
        self.int_mask = ((level as u32) & 7) << 8;

        let stacked_pc = self.pc;
        let vector;

        if self.cpu_type == super::types::CpuType::M68000 {
            // 68000 interrupt microcode (per Moira execInterrupt, same
            // sequence as yacht): 6 idle clocks, PC-low write, the 4-clock
            // interrupt-acknowledge bus cycle that latches the vector
            // number, 4 more internal clocks, then the SR and PC-high
            // writes. The idle periods are billed in place so every frame
            // write and the IACK land at their hardware bus-time offsets
            // (previously the frame writes ran back to back and all idle
            // time was paid after the handler prefetch, letting the
            // handler's first instruction start ~14 clocks early).
            self.internal_cycles(6);
            let sp = self.dar[15].wrapping_sub(6);
            self.dar[15] = sp;
            self.write_16(bus, sp.wrapping_add(4), (stacked_pc & 0xFFFF) as u16);
            self.internal_cycles(4);
            self.flush_sync(bus);
            vector = Self::iack_vector(bus.interrupt_acknowledge(level), level);
            self.internal_cycles(4);
            self.write_16(bus, sp, old_sr);
            self.write_16(bus, sp.wrapping_add(2), (stacked_pc >> 16) as u16);
        } else if self.cpu_type == super::types::CpuType::M68010 {
            // 68010 interrupt microcode (Moira execInterrupt): 12 idle
            // clocks with the IACK at their end, then the format-0 frame
            // in hardware bus order PC low, SR, PC high, vector word.
            self.internal_cycles(12);
            self.flush_sync(bus);
            vector = Self::iack_vector(bus.interrupt_acknowledge(level), level);
            let sp = self.dar[15].wrapping_sub(8);
            self.dar[15] = sp;
            self.write_16(bus, sp.wrapping_add(4), (stacked_pc & 0xFFFF) as u16);
            self.write_16(bus, sp, old_sr);
            self.write_16(bus, sp.wrapping_add(2), (stacked_pc >> 16) as u16);
            self.write_16(bus, sp.wrapping_add(6), (vector as u16) << 2);
        } else {
            vector = Self::iack_vector(bus.interrupt_acknowledge(level), level);
            let vec_word = (vector as u16) << 2;
            // 68020+: format 0 frame: (vector<<2), PC, SR (vector word ends up at +6)
            self.push_16(bus, vec_word);
            self.push_32(bus, stacked_pc);
            self.push_16(bus, old_sr);
        }

        // If we were in supervisor master state, generate a throwaway frame on ISP.
        // (Musashi: clear M, force S in the stacked SR, then stack format-1 frame.)
        let is_ec020_plus = matches!(
            self.cpu_type,
            super::types::CpuType::M68EC020
                | super::types::CpuType::M68020
                | super::types::CpuType::M68EC030
                | super::types::CpuType::M68030
                | super::types::CpuType::M68EC040
                | super::types::CpuType::M68LC040
                | super::types::CpuType::M68040
        );
        if is_ec020_plus && self.m_flag != 0 {
            self.set_sm_flag(SFLAG_SET); // clear M => ISP active
            let sr2 = old_sr | 0x2000;
            self.push_16(bus, 0x1000 | (((vector as u16) << 2) & 0x0FFF));
            self.push_32(bus, stacked_pc);
            self.push_16(bus, sr2);
        } else if self.cpu_type == super::types::CpuType::M68060 && self.m_flag != 0 {
            // The 68060 clears M on interrupt entry but has a single
            // supervisor stack: no bank switch and no throwaway frame.
            self.m_flag = 0;
        }

        // Jump to vector
        self.jump_vector(bus, vector);

        // Clear stopped state
        self.stopped = 0;

        // Use exception cycles: 44 clocks on the 68000, 46 on the 68010
        // (12 leading internal clocks + the four-word frame), matching the
        // internal + bus clocks billed above so the accounting equals the
        // bus time actually consumed.
        self.cycles_remaining -= if self.cpu_type == super::types::CpuType::M68010 {
            46
        } else {
            44
        };
    }

    /// Stopped-state supervisor check, run at every instruction boundary
    /// while stopped: STOP loads its SR operand verbatim (a single-stepped
    /// STOP observes S and T exactly as written), and a loaded S-clear SR
    /// wakes the CPU here with a privilege violation -- 4 internal clocks,
    /// then the exception, stacking the STOP instruction itself so the
    /// handler's RTE re-executes it. Returns the cycles consumed when the
    /// wake fired; None leaves the CPU stopped (including a HALT).
    fn stopped_supervisor_check<B: AddressBus>(&mut self, bus: &mut B) -> Option<i32> {
        if self.stopped != STOP_LEVEL_STOP || self.s_flag != 0 {
            return None;
        }
        self.stopped = 0;
        self.internal_cycles(4);
        // PC sits past the STOP opcode and its SR operand word.
        self.ppc = self.pc.wrapping_sub(4);
        Some(4 + self.exception_privilege(bus))
    }

    /// Halt the CPU.
    pub fn halt(&mut self) {
        self.clear_execution_pipeline_state();
        self.stopped |= STOP_LEVEL_HALT;
    }

    /// Stop the CPU (STOP instruction).
    pub fn stop(&mut self, new_sr: u16) {
        self.clear_execution_pipeline_state();
        self.set_sr(new_sr);
        self.stopped |= STOP_LEVEL_STOP;
    }
}