Skip to main content
← PSoXide SDK guides and examples · SDK 80d1c329e977 · All Cargo features enabled; check feature gates before use.

psx_rt/
interrupts.rs

1//! Minimal interrupt support used by engine-level clocks.
2//!
3//! The first consumer is a monotonic VBlank counter. We install a
4//! tiny exception-vector trampoline that handles VBlank IRQs itself,
5//! increments a volatile counter, acknowledges the IRQ, then returns
6//! with `rfe`. The handler deliberately uses only the MIPS kernel
7//! registers `$k0/$k1`, so it does not need a stack frame.
8
9#[cfg(target_arch = "mips")]
10use psx_hw::{cop0, dma, gpu, gte, memory};
11#[cfg(target_arch = "mips")]
12use psx_io::irq;
13
14#[cfg(target_arch = "mips")]
15core::arch::global_asm!(
16    r#"
17    .set noreorder
18    # The presentation cap's bookkeeping for one applied display flip: arm the
19    # hold (the cap's VBlanks, counted down once per edge below) and count the
20    # flip in the interval histogram by the edges since the last one. Clobbers
21    # $26 and $27.
22    .macro PSX_RT_FLIP_RECORD
23    lui   $26, %hi(__psx_rt_flip_min)
24    lw    $27, %lo(__psx_rt_flip_min)($26)
25    lui   $26, %hi(__psx_rt_flip_hold)
26    sw    $27, %lo(__psx_rt_flip_hold)($26)
27    lui   $26, %hi(__psx_rt_flip_age)
28    lw    $27, %lo(__psx_rt_flip_age)($26)
29    nop
30    sw    $zero, %lo(__psx_rt_flip_age)($26)
31    sltiu $26, $27, 7
32    bnez  $26, .Lpsx_flip_bucket\@
33    nop
34    addiu $27, $zero, 7
35.Lpsx_flip_bucket\@:
36    sll   $27, $27, 2
37    lui   $26, %hi(__psx_rt_flip_hist)
38    addu  $26, $26, $27
39    lw    $27, %lo(__psx_rt_flip_hist)($26)
40    nop
41    addiu $27, $27, 1
42    sw    $27, %lo(__psx_rt_flip_hist)($26)
43    .endm
44    .section .text.psx_rt_exception
45    .globl __psx_rt_exception_handler
46__psx_rt_exception_handler:
47    # Console stop-panel builds: an exception taken with the cache isolated (the isolate bit of SR) means the
48    # fault is inside an instruction-cache flush, where this handler's loads and stores would
49    # reach the isolated cache and not RAM (every fault there was silent). Clear the bit first
50    # and record that it was set. Interrupts are masked for the whole flush, so only a fault can
51    # arrive here with it set.
52    .if {diag}
53    mfc0  $26, $12
54    lui   $27, {isc_hi}
55    and   $27, $26, $27
56    beqz  $27, 10f
57    nop
58    xor   $26, $26, $27
59    mtc0  $26, $12
60    nop
61    nop
62    lui   $26, %hi(__psx_diag_isc_hit)
63    addiu $27, $zero, 1
64    sw    $27, %lo(__psx_diag_isc_hit)($26)
6510:
66    .endif
67    lui   $26, {io_hi}
68    lw    $27, {i_stat}($26)
69    lw    $26, {i_mask}($26)
70    nop
71    and   $27, $27, $26
72    andi  $27, $27, {vblank_mask}
73    beqz  $27, 9f
74    nop
75
76    lui   $26, %hi(__psx_rt_vblank_count)
77    lw    $27, %lo(__psx_rt_vblank_count)($26)
78    nop
79    addiu $27, $27, 1
80    sw    $27, %lo(__psx_rt_vblank_count)($26)
81
82    # Present queue (`crate::present`, `present-queue` feature only). One
83    # published chain waits in __psx_rt_present_head (0 = empty). Kick it on
84    # the first edge where the previous chain's closing GP0(1Fh) has run
85    # (GPUSTAT bit 24) and DMA channel 2 is idle: flip to the finished frame,
86    # acknowledge the flag with GP1(02h) (the new chain raises it again at its
87    # own end), point GP0 DMA at the CPU with GP1(04h)=2, enable channel 2 in
88    # DPCR and start the linked-list walk. Ported from quake-psx 3ca915c.
89    # With the slot empty this costs one load.
90    .if {present}
91    lui   $26, %hi(__psx_rt_present_head)
92    lw    $27, %lo(__psx_rt_present_head)($26)
93    nop
94    beqz  $27, 8f
95    nop
96    # The presentation cap: hold the chain (and its flip) while the last flip is
97    # fewer than the cap's VBlanks old.
98    lui   $26, %hi(__psx_rt_flip_hold)
99    lw    $26, %lo(__psx_rt_flip_hold)($26)
100    nop
101    bnez  $26, 8f
102    nop
103    lui   $26, {io_hi}
104    lw    $27, {gp1}($26)
105    nop
106    srl   $27, $27, {gpustat_irq1_shift}
107    andi  $27, $27, 1
108    beqz  $27, 7f
109    nop
110    lw    $27, {gpu_chcr}($26)
111    nop
112    srl   $27, $27, {chcr_start_shift}
113    andi  $27, $27, 1
114    bnez  $27, 7f
115    nop
116    lui   $27, %hi(__psx_rt_present_display)
117    lw    $27, %lo(__psx_rt_present_display)($27)
118    nop
119    beqz  $27, 6f
120    nop
121    sw    $27, {gp1}($26)
122    PSX_RT_FLIP_RECORD
123    lui   $26, {io_hi}
1246:
125    lui   $27, {ack_irq_hi}
126    sw    $27, {gp1}($26)
127    lui   $27, {dma_dir_hi}
128    ori   $27, $27, {dma_dir_lo}
129    sw    $27, {gp1}($26)
130    lw    $27, {dpcr}($26)
131    nop
132    ori   $27, $27, {gpu_dpcr_enable}
133    sw    $27, {dpcr}($26)
134    lui   $27, %hi(__psx_rt_present_head)
135    lw    $27, %lo(__psx_rt_present_head)($27)
136    nop
137    sw    $27, {gpu_madr}($26)
138    sw    $zero, {gpu_bcr}($26)
139    lui   $27, {chcr_hi}
140    ori   $27, $27, {chcr_lo}
141    sw    $27, {gpu_chcr}($26)
142    lui   $26, %hi(__psx_rt_present_head)
143    sw    $zero, %lo(__psx_rt_present_head)($26)
144    lui   $26, %hi(__psx_rt_present_kick_count)
145    lw    $27, %lo(__psx_rt_present_kick_count)($26)
146    nop
147    addiu $27, $27, 1
148    b     8f
149    sw    $27, %lo(__psx_rt_present_kick_count)($26)
1507:
151    lui   $26, %hi(__psx_rt_present_skip_count)
152    lw    $27, %lo(__psx_rt_present_skip_count)($26)
153    nop
154    addiu $27, $27, 1
155    sw    $27, %lo(__psx_rt_present_skip_count)($26)
1568:
157    .endif
158
159    # Apply one queued GP1 word exactly at the blank edge (deferred display
160    # flip). Zero means no request; a display-start word is never zero.
161    # Only apply once GPUSTAT bit 24 is set: the frame's work ends with
162    # GP0(1Fh), which sets it when the GPU reaches it, i.e. when everything
163    # before it has been drawn, and the game acknowledged the flag with
164    # GP1(02h) when it kicked that work. Until then the word stays queued for
165    # a later edge, so a flip never exposes a partial buffer and the CPU never
166    # blocks on the GPU. Bit 28 is not a drawing-complete test: on silicon it
167    # rises when the DMA has pushed the last packet, about one large
168    # primitive before the drawing ends (hardware-tests v1.24 cases 219-226);
169    # the v1.24 present probe flipped on bit 24 with 120 of 120 frames right.
170    lui   $26, %hi(__psx_rt_pending_gp1)
171    lw    $27, %lo(__psx_rt_pending_gp1)($26)
172    nop
173    beqz  $27, 2f
174    nop
175    # A display-start word (GP1 05h) is a flip and waits out the presentation cap;
176    # any other word (display enable, say) is applied as before.
177    srl   $26, $27, 24
178    addiu $26, $26, -5
179    bnez  $26, 21f
180    nop
181    lui   $26, %hi(__psx_rt_flip_hold)
182    lw    $26, %lo(__psx_rt_flip_hold)($26)
183    nop
184    bnez  $26, 2f
185    nop
18621:
187    lui   $26, {io_hi}
188    lw    $26, {gp1}($26)
189    nop
190    srl   $26, $26, {gpustat_irq1_shift}
191    andi  $26, $26, 1
192    beqz  $26, 2f
193    nop
194    lui   $26, %hi(__psx_rt_pending_gp1)
195    sw    $zero, %lo(__psx_rt_pending_gp1)($26)
196    lui   $26, {io_hi}
197    sw    $27, {gp1}($26)
198    srl   $26, $27, 24
199    addiu $26, $26, -5
200    bnez  $26, 2f
201    nop
202    PSX_RT_FLIP_RECORD
203
2042:
205    lui   $26, {io_hi}
206    addiu $27, $zero, {ack_vblank}
207    sw    $27, {i_stat}($26)
208
209    # The presentation cap counts one edge off the hold and ages the last flip.
210    lui   $26, %hi(__psx_rt_flip_hold)
211    lw    $27, %lo(__psx_rt_flip_hold)($26)
212    nop
213    beqz  $27, 22f
214    nop
215    addiu $27, $27, -1
216    sw    $27, %lo(__psx_rt_flip_hold)($26)
21722:
218    lui   $26, %hi(__psx_rt_flip_age)
219    lw    $27, %lo(__psx_rt_flip_age)($26)
220    nop
221    addiu $27, $27, 1
222    sw    $27, %lo(__psx_rt_flip_age)($26)
223
224    # Console stop-panel watchdog (`diag`, feature `console-diag` only): save every
225    # register, run the watch on its own stack, put everything back.
226    .if {diag}
227    lui   $26, %hi(.Lpsx_diag_ret)
228    addiu $26, $26, %lo(.Lpsx_diag_ret)
229    j     __psx_diag_vblank_tramp
230    nop
231.Lpsx_diag_ret:
232    .endif
233
2341:
235    mfc0  $27, $13
236    nop
237    andi  $27, $27, 0x007c
238    beqz  $27, 2f
239    nop
240
241    # Preserve a compact unexpected-exception signature before deciding
242    # whether this fault is recoverable. Immediate-abort panics compile to
243    # BREAK, so Cause + EPC are the only reliable shipping diagnostics.
244    lui   $26, %hi(__psx_rt_fault_cause)
245    mfc0  $27, $13
246    nop
247    sw    $27, %lo(__psx_rt_fault_cause)($26)
248    lui   $26, %hi(__psx_rt_fault_epc)
249    mfc0  $27, $14
250    nop
251    sw    $27, %lo(__psx_rt_fault_epc)($26)
252    lui   $26, %hi(__psx_rt_fault_badvaddr)
253    mfc0  $27, $8
254    nop
255    sw    $27, %lo(__psx_rt_fault_badvaddr)($26)
256
257    lui   $26, %hi(__psx_rt_fault_count)
258    lw    $27, %lo(__psx_rt_fault_count)($26)
259    nop
260    addiu $27, $27, 1
261    sw    $27, %lo(__psx_rt_fault_count)($26)
262
263    # Never advance EPC for fatal instruction-side faults. BREAK (ExcCode 9,
264    # 0x24) marks panic=immediate-abort; IBE (ExcCode 6, 0x18) cannot become
265    # executable by skipping one word. For AdEL (ExcCode 4, 0x10), halt only
266    # when BadVAddr == EPC, which identifies a misaligned instruction fetch;
267    # retain the historical skip-and-count policy for data-side AdEL.
268    mfc0  $27, $13
269    nop
270    andi  $27, $27, 0x007c
271    addiu $26, $zero, 0x0024
272    beq   $27, $26, 3f
273    nop
274    addiu $26, $zero, 0x0018
275    beq   $27, $26, 3f
276    nop
277    addiu $26, $zero, 0x0010
278    bne   $27, $26, 4f
279    nop
280    mfc0  $26, $8
281    mfc0  $27, $14
282    nop
283    beq   $26, $27, 3f
284    nop
285
286    # Step over the faulting instruction: resume at EPC + 4. Not with
287    # Cause.BD set: then it sat in the delay slot of the branch at EPC, and
288    # EPC + 4 would re-run it as if the branch had fallen through. Resuming
289    # correctly means evaluating that branch, which costs every game code
290    # for a path only a bug reaches, so halt on it like a fatal fault, with
291    # Cause, EPC and BadVAddr recorded. With the `strict-faults` feature
292    # nothing is stepped over: every fault halts here. `fault_resume_pc`
293    # below is the same decision in Rust, unit-tested on host.
2944:
295    .if {strict}
296    b     3f
297    nop
298    .endif
299    mfc0  $27, $13
300    mfc0  $26, $14
301    nop
302    bltz  $27, 3f
303    nop
304    addiu $26, $26, 4
305    jr    $26
306    .word {rfe}
307
308    # Interrupt return: EPC, or EPC + 4 when the word at EPC is a GTE
309    # command (top seven bits 0100101). An interrupt taken on a GTE command
310    # lets the command run and still leaves EPC on it, so returning to EPC
311    # runs it a second time (hardware-tests v1.24 on silicon: case 0xC9,
312    # 38 of 38 such interrupts ran an RTPS twice; with this step, case 0xCB,
313    # 61 skips, none doubled or lost). This is psx-spx's fix and the Sony
314    # kernel's. With Cause.BD set EPC holds the branch, never a GTE command,
315    # so a GTE command in a delay slot is not stepped over and does run twice:
316    # psx-spx's answer is to keep GTE commands out of delay slots, and
317    # hazard-scan warns about any it finds. `interrupt_resume_pc`
318    # below is the same decision in Rust, unit-tested on host.
3192:
320    mfc0  $26, $14
321    nop
322    lw    $27, 0($26)
323    nop
324    srl   $27, $27, {gte_prefix_shift}
325    xori  $27, $27, {gte_prefix}
326    bnez  $27, 5f
327    nop
328    lui   $27, %hi(__psx_rt_gte_skip_count)
329    lw    $26, %lo(__psx_rt_gte_skip_count)($27)
330    nop
331    addiu $26, $26, 1
332    sw    $26, %lo(__psx_rt_gte_skip_count)($27)
333    mfc0  $26, $14
334    nop
335    addiu $26, $26, 4
3365:
337    jr    $26
338    .word {rfe}
3393:
340    .if {diag}
341    j     __psx_diag_fault_tramp
342    nop
343    .else
344    b     3b
345    nop
346    .endif
347
348    # No VBlank pending. An interrupt (ExcCode 0) with an enabled source
349    # pending here is one nothing in this handler owns, and returning without
350    # acknowledging it re-enters at once, forever. Record it, acknowledge it
351    # (writing a 0 to an I_STAT bit clears it, a 1 leaves it) and count it,
352    # then go on to the common return. Not done when VBlank is pending too:
353    # a game's own handler chains here for VBlank, and a source it services
354    # itself must stay in I_STAT until it does. `stray_interrupt_sources`
355    # below is the same decision in Rust, unit-tested on host.
3569:
357    mfc0  $27, $13
358    nop
359    andi  $27, $27, 0x007c
360    bnez  $27, 1b
361    nop
362    lui   $26, {io_hi}
363    lw    $27, {i_stat}($26)
364    lw    $26, {i_mask}($26)
365    nop
366    and   $27, $27, $26
367    # A source a wrapper in front of this handler has claimed is not a stray
368    # even though it is pending here: it arrived while another wrapper's handler
369    # ran, or while the claimant's own handler held interrupts off, and the
370    # claimant will take it as soon as this returns. Leave it pending.
371    lui   $26, %hi(__psx_rt_claimed_irq)
372    lw    $26, %lo(__psx_rt_claimed_irq)($26)
373    nop
374    nor   $26, $26, $zero
375    and   $27, $27, $26
376    beqz  $27, 1b
377    nop
378    lui   $26, %hi(__psx_rt_stray_irq_last)
379    sw    $27, %lo(__psx_rt_stray_irq_last)($26)
380    nor   $27, $27, $zero
381    lui   $26, {io_hi}
382    sw    $27, {i_stat}($26)
383    lui   $26, %hi(__psx_rt_stray_irq_count)
384    lw    $27, %lo(__psx_rt_stray_irq_count)($26)
385    nop
386    addiu $27, $27, 1
387    b     1b
388    sw    $27, %lo(__psx_rt_stray_irq_count)($26)
389    .set reorder
390    "#,
391    strict = const STRICT_FAULTS as u32,
392    present = const PRESENT_QUEUE as u32,
393    diag = const CONSOLE_DIAG as u32,
394    isc_hi = const crate::cache::ISOLATE_CACHE_BIT >> 16,
395    // Every register the handler touches is in the I/O window, so one `lui`
396    // of the window's high half reaches them all and the offsets are the low
397    // halves (checked by the assertions below the block).
398    io_hi = const memory::io::BASE >> 16,
399    i_stat = const psx_hw::irq::I_STAT & 0xFFFF,
400    i_mask = const psx_hw::irq::I_MASK & 0xFFFF,
401    vblank_mask = const 1u32 << psx_hw::irq::source::VBLANK,
402    ack_vblank = const !(1u32 << psx_hw::irq::source::VBLANK) as i32,
403    gp1 = const gpu::GP1 & 0xFFFF,
404    gpustat_irq1_shift = const gpu::GpuStat::IRQ1.bits().trailing_zeros(),
405    ack_irq_hi = const gpu::gp1::ACK_IRQ >> 16,
406    dma_dir_hi = const gpu::gp1::dma_direction(gpu::DmaDirection::CpuToGp0 as u32) >> 16,
407    dma_dir_lo = const gpu::gp1::dma_direction(gpu::DmaDirection::CpuToGp0 as u32) & 0xFFFF,
408    gpu_madr = const (dma::CHANNEL_BASE + dma::CHANNEL_STRIDE * dma::channel::GPU + dma::MADR) & 0xFFFF,
409    gpu_bcr = const (dma::CHANNEL_BASE + dma::CHANNEL_STRIDE * dma::channel::GPU + dma::BCR) & 0xFFFF,
410    gpu_chcr = const (dma::CHANNEL_BASE + dma::CHANNEL_STRIDE * dma::channel::GPU + dma::CHCR) & 0xFFFF,
411    chcr_start_shift = const dma::CHCR_START.trailing_zeros(),
412    chcr_hi = const dma::CHCR_LINKED_LIST_TO_DEVICE >> 16,
413    chcr_lo = const dma::CHCR_LINKED_LIST_TO_DEVICE & 0xFFFF,
414    dpcr = const dma::DPCR & 0xFFFF,
415    gpu_dpcr_enable = const dma::dpcr_enable(dma::channel::GPU),
416    rfe = const cop0::RFE,
417    gte_prefix_shift = const gte::PREFIX_SHIFT,
418    gte_prefix = const gte::COMMAND >> gte::PREFIX_SHIFT,
419);
420// The handler reaches every register through one `lui` of the I/O window's
421// high half plus a signed 16-bit offset, and builds its GP1 and CHCR words
422// from immediates; check each the way the template spells them.
423#[cfg(target_arch = "mips")]
424const _: () = {
425    let window = memory::io::BASE >> 16;
426    assert!(psx_hw::irq::I_STAT >> 16 == window && psx_hw::irq::I_MASK >> 16 == window);
427    assert!(gpu::GP1 >> 16 == window && dma::DPCR >> 16 == window);
428    let gpu_block = dma::CHANNEL_BASE + dma::CHANNEL_STRIDE * dma::channel::GPU;
429    assert!(gpu_block >> 16 == window && (gpu_block + dma::CHCR) & 0xffff < 0x8000);
430    // `lui` of a GP1 word with an empty low half.
431    assert!(gpu::gp1::ACK_IRQ & 0xffff == 0);
432    // `ori` takes an unsigned 16-bit immediate.
433    assert!(dma::dpcr_enable(dma::channel::GPU) <= 0xffff);
434};
435
436/// True when psx-rt was built with the `console-diag` feature: the VBlank handler
437/// runs the stall watch and a fatal fault shows the stop-panel (see `diag`).
438pub const CONSOLE_DIAG: bool = cfg!(feature = "console-diag");
439
440/// Chains the present queue has kicked (0 without the `present-queue` feature).
441#[cfg(all(feature = "console-diag", target_arch = "mips"))]
442pub(crate) fn present_kick_count() -> u32 {
443    #[cfg(feature = "present-queue")]
444    // SAFETY: a volatile aligned read of a counter only the handler writes.
445    return unsafe { core::ptr::addr_of!(__psx_rt_present_kick_count).read_volatile() };
446    #[cfg(not(feature = "present-queue"))]
447    0
448}
449
450/// Present-queue edges that found the previous chain undrawn (0 without the feature).
451#[cfg(all(feature = "console-diag", target_arch = "mips"))]
452pub(crate) fn present_skip_count() -> u32 {
453    #[cfg(feature = "present-queue")]
454    // SAFETY: a volatile aligned read of a counter only the handler writes.
455    return unsafe { core::ptr::addr_of!(__psx_rt_present_skip_count).read_volatile() };
456    #[cfg(not(feature = "present-queue"))]
457    0
458}
459
460/// True when psx-rt was built with the `present-queue` feature: the VBlank
461/// handler kicks frames published through [`crate::present`].
462pub const PRESENT_QUEUE: bool = cfg!(feature = "present-queue");
463
464/// Present-queue slot: the chain head the VBlank handler kicks at the next
465/// ready edge, 0 when empty. Owned by [`crate::present`].
466#[cfg(feature = "present-queue")]
467#[no_mangle]
468pub(crate) static mut __psx_rt_present_head: u32 = 0;
469
470/// GP1(05h) word the handler writes just before kicking the slot's chain;
471/// 0 = no flip.
472#[cfg(feature = "present-queue")]
473#[no_mangle]
474pub(crate) static mut __psx_rt_present_display: u32 = 0;
475
476/// Chains the handler has kicked.
477#[cfg(feature = "present-queue")]
478#[no_mangle]
479pub(crate) static mut __psx_rt_present_kick_count: u32 = 0;
480
481/// Edges on which a published chain found the previous one undrawn or DMA
482/// channel 2 still busy.
483#[cfg(feature = "present-queue")]
484#[no_mangle]
485pub(crate) static mut __psx_rt_present_skip_count: u32 = 0;
486
487/// True when psx-rt was built with the `strict-faults` feature: the
488/// exception handler halts on every fault instead of stepping over the
489/// faulting instruction (see [`fault_resume_pc`]).
490pub const STRICT_FAULTS: bool = cfg!(feature = "strict-faults");
491
492/// Monotonic VBlank IRQ count.
493#[no_mangle]
494static mut __psx_rt_vblank_count: u32 = 0;
495
496/// The presentation cap every program starts with: a flip at most every second
497/// VBlank, 30 fps NTSC and 25 PAL (`psx_tick::PresentCap::HZ30`).
498pub const DEFAULT_MIN_FLIP_VBLANKS: u32 = 2;
499
500/// Buckets of the flip-interval histogram: flips 0 to 6 VBlanks after the
501/// previous one, and the last bucket for 7 or more
502/// (`psx_tick::FLIP_HISTOGRAM_BUCKETS`).
503pub const FLIP_HISTOGRAM_BUCKETS: usize = 8;
504
505/// The presentation cap: fewest VBlanks between two display flips
506/// (`psx_tick::PresentCap`). 2 is 30 fps; 1 is the explicit opt-out.
507#[no_mangle]
508static mut __psx_rt_flip_min: u32 = DEFAULT_MIN_FLIP_VBLANKS;
509
510/// VBlank edges a flip stays held back, set to the cap when a flip is applied
511/// and counted down once per edge by the handler. A flip is applied only at 0.
512#[no_mangle]
513static mut __psx_rt_flip_hold: u32 = 0;
514
515/// VBlank edges since the last applied flip, for the interval histogram. Starts
516/// at the last bucket so the first flip is not counted as a fast one.
517#[no_mangle]
518static mut __psx_rt_flip_age: u32 = FLIP_AGE_UNKNOWN;
519
520/// Flips by VBlanks since the previous one (see `psx_tick::FlipHistogram`).
521#[no_mangle]
522static mut __psx_rt_flip_hist: [u32; FLIP_HISTOGRAM_BUCKETS] = [0; FLIP_HISTOGRAM_BUCKETS];
523
524/// The age of a flip with no predecessor: lands in the last histogram bucket.
525const FLIP_AGE_UNKNOWN: u32 = FLIP_HISTOGRAM_BUCKETS as u32 - 1;
526
527/// Count of exceptions that were NOT interrupts: bus errors, address
528/// errors, reserved instructions.
529///
530/// The handler used to return straight to EPC for these, which
531/// re-executes the faulting instruction and loops forever: a silent
532/// freeze with no diagnostic, indistinguishable from a hung spin. It now
533/// steps over the faulting instruction and counts it here, so a bad
534/// access costs one wrong value instead of the whole program, and the
535/// count says it happened. Fatal instruction-side faults are deliberately
536/// different: BREAK is the shipping representation of
537/// `panic=immediate-abort`, while IBE and instruction-side AdEL cannot be
538/// repaired by skipping one word. The handler records Cause/EPC and halts for
539/// all three instead of entering unreachable or non-executable code. It also
540/// halts on any fault in a branch delay slot, where skipping one word would
541/// drop the branch (see [`fault_resume_pc`]).
542///
543/// Stepping over hides bugs: a misaligned store that is skipped leaves the
544/// program running on a wrong value, and only this count says so (one such
545/// store in WipEout drew wrong geometry in one build and, landing in a delay
546/// slot, hung another). Build development and test discs with the
547/// `strict-faults` feature to halt on the first fault instead.
548#[no_mangle]
549static mut __psx_rt_fault_count: u32 = 0;
550
551/// Interrupts the handler returned from at EPC + 4 because the word at EPC
552/// was a GTE command (see [`interrupt_resume_pc`]).
553#[no_mangle]
554static mut __psx_rt_gte_skip_count: u32 = 0;
555
556/// Raw COP0 Cause captured for the latest unexpected exception.
557#[no_mangle]
558static mut __psx_rt_fault_cause: u32 = 0;
559
560/// COP0 EPC captured for the latest unexpected exception.
561#[no_mangle]
562static mut __psx_rt_fault_epc: u32 = 0;
563
564/// COP0 BadVAddr captured for the latest unexpected exception. Only
565/// meaningful for an address error; other faults leave a stale value in the
566/// register.
567#[no_mangle]
568static mut __psx_rt_fault_badvaddr: u32 = 0;
569
570/// One queued GP1 word the VBlank handler writes to the GPU at the first
571/// blank edge on which GPUSTAT bit 24 is set, then clears. Zero = empty.
572/// Written by [`queue_display_control_at_vblank`].
573#[no_mangle]
574static mut __psx_rt_pending_gp1: u32 = 0;
575
576/// Interrupts other than VBlank the handler acknowledged because nothing
577/// owned them (see [`stray_interrupt_sources`]).
578#[no_mangle]
579static mut __psx_rt_stray_irq_count: u32 = 0;
580
581/// The `I_STAT & I_MASK` sources of the latest stray interrupt.
582#[no_mangle]
583static mut __psx_rt_stray_irq_last: u32 = 0;
584
585/// Sources that wrappers in front of this handler own (see
586/// [`claim_interrupt_sources`]): never acknowledged as strays.
587#[no_mangle]
588static mut __psx_rt_claimed_irq: u32 = 0;
589
590/// Declare that a handler in front of psx-rt's owns the `I_STAT` sources in
591/// `bits` (a mask of [`psx_hw::irq::source`] positions).
592///
593/// psx-rt's handler acknowledges an enabled source that is pending when no
594/// VBlank is, because nothing it knows owns it. A wrapper chained in front
595/// (psx-cdstream's for the CD controller, the pad engine's for the controller
596/// port and root counter 0) does own its sources, but an interrupt can arrive
597/// while another wrapper's handler runs, or while its own runs with interrupts
598/// off, and so reach psx-rt's handler pending, where the acknowledge loses it:
599/// a CD sector, a pad byte. A claimed source is left pending, and the exception
600/// is taken again at once, into the owner. Call from foreground code when the
601/// wrapper is installed; [`release_interrupt_sources`] undoes it.
602pub fn claim_interrupt_sources(bits: u32) {
603    // The CD wrapper's engine opens and closes its source, and so claims and
604    // releases it, from its interrupt handler too; with interrupts on, that
605    // could land between this read and write and be overwritten.
606    psx_io::irq::without_interrupts(|| {
607        // SAFETY: the read-modify-write runs with CPU interrupts off, so no
608        // handler writes the word meanwhile; the exception handler only reads
609        // it, and an aligned word store cannot tear.
610        unsafe {
611            let claimed = core::ptr::read_volatile(&raw const __psx_rt_claimed_irq);
612            core::ptr::write_volatile(&raw mut __psx_rt_claimed_irq, claimed | bits);
613        }
614    });
615}
616
617/// Undo [`claim_interrupt_sources`] for `bits`.
618pub fn release_interrupt_sources(bits: u32) {
619    psx_io::irq::without_interrupts(|| {
620        // SAFETY: as in `claim_interrupt_sources`.
621        unsafe {
622            let claimed = core::ptr::read_volatile(&raw const __psx_rt_claimed_irq);
623            core::ptr::write_volatile(&raw mut __psx_rt_claimed_irq, claimed & !bits);
624        }
625    });
626}
627
628/// The sources currently claimed.
629pub fn claimed_interrupt_sources() -> u32 {
630    // SAFETY: a volatile aligned read.
631    unsafe { core::ptr::read_volatile(&raw const __psx_rt_claimed_irq) }
632}
633
634/// Stray interrupts acknowledged so far. psx-rt's handler owns VBlank only;
635/// any other source enabled in `I_MASK` that fires while no VBlank is
636/// pending, and that no handler in front of this one claimed, is
637/// acknowledged and counted here instead of re-entering forever. Non-zero
638/// means something enabled a source nothing services.
639#[inline]
640pub fn stray_interrupt_count() -> u32 {
641    // SAFETY: a volatile aligned u32 read through a raw pointer, so no reference is formed. Only
642    // the asm exception handler writes it, and an aligned word load cannot tear.
643    unsafe { core::ptr::read_volatile(&raw const __psx_rt_stray_irq_count) }
644}
645
646/// The `I_STAT & I_MASK` bits of the latest stray interrupt
647/// ([`stray_interrupt_count`]); zero before the first.
648#[inline]
649pub fn last_stray_interrupt_sources() -> u32 {
650    // SAFETY: a volatile aligned u32 read through a raw pointer, so no reference is formed. Only
651    // the asm exception handler writes it, and an aligned word load cannot tear.
652    unsafe { core::ptr::read_volatile(&raw const __psx_rt_stray_irq_last) }
653}
654
655/// The sources psx-rt's handler acknowledges as strays for one entry, given
656/// `I_STAT`, `I_MASK` and COP0 Cause; zero when it leaves them alone.
657///
658/// It acts only on an interrupt (Cause.ExcCode 0) with no VBlank pending: a
659/// pending VBlank means a game's own handler may have chained here with a
660/// source of its own still waiting for it, which must stay in `I_STAT`. The
661/// handler's assembly makes exactly this decision.
662pub const fn stray_interrupt_sources(status: u32, mask: u32, cause: u32) -> u32 {
663    stray_unclaimed(status, mask, cause, 0)
664}
665
666/// [`stray_interrupt_sources`] with the sources wrappers have claimed
667/// ([`claim_interrupt_sources`]) left out.
668pub const fn stray_unclaimed(status: u32, mask: u32, cause: u32, claimed: u32) -> u32 {
669    let pending = status & mask & !claimed;
670    let is_interrupt = (cause >> 2) & 0x1f == 0;
671    if is_interrupt && pending & (1 << psx_hw::irq::source::VBLANK) == 0 {
672        pending
673    } else {
674        0
675    }
676}
677
678/// Set once [`install_vblank_counter`] has run, so [`wait_vblank`] can
679/// install lazily without resetting a counter the game is already using.
680#[cfg(target_arch = "mips")]
681static mut INSTALLED: bool = false;
682
683/// The first word of the exception vector as `_start` found it, before any
684/// game code ran: the BIOS's own, or whatever a previous program left.
685#[cfg(target_arch = "mips")]
686static mut BOOT_VECTOR_WORD: u32 = 0;
687
688/// Set once `_start` has stored [`BOOT_VECTOR_WORD`].
689#[cfg(target_arch = "mips")]
690static mut BOOT_VECTOR_RECORDED: bool = false;
691
692/// Remember the vector word as the program found it. Called once from
693/// `_start`, after `.bss` is zeroed and before `main`.
694#[cfg(target_arch = "mips")]
695pub(crate) fn record_boot_vector() {
696    // SAFETY: two private statics written once at boot, before `main` and before any code that
697    // reads them runs; volatile aligned stores through raw pointers.
698    unsafe {
699        core::ptr::write_volatile(&raw mut BOOT_VECTOR_WORD, vector_word());
700        core::ptr::write_volatile(&raw mut BOOT_VECTOR_RECORDED, true);
701    }
702}
703
704/// Whether [`wait_vblank`] may install psx-rt's handler on first use.
705///
706/// It may when the vector still holds what the program booted with (nobody
707/// has taken it) or already jumps to psx-rt's handler. A different word
708/// means the game put its own handler there (hk-psx and cs-psx wrap psx-rt's
709/// to service CD interrupts), and a safe wait must not overwrite it. An
710/// entry that never recorded the boot word keeps the old rule: install.
711#[cfg(any(target_arch = "mips", test))]
712const fn may_install_lazily(boot_word: Option<u32>, vector: u32, handler_jump: u32) -> bool {
713    match boot_word {
714        None => true,
715        Some(boot) => vector == boot || vector == handler_jump,
716    }
717}
718
719#[cfg(target_arch = "mips")]
720extern "C" {
721    fn __psx_rt_exception_handler();
722}
723
724/// Install and enable the VBlank counter interrupt path.
725///
726/// This writes a branch into the MIPS general exception vector,
727/// enables the VBlank source in `I_MASK`, and sets the COP0 interrupt
728/// enable bits used by the R3000A. The operation is idempotent for
729/// the current runtime: reinstalling simply resets the software
730/// counter and refreshes the vector.
731///
732/// The handler owns VBlank only. Another source enabled in `I_MASK` that
733/// fires while no VBlank is pending is acknowledged and counted
734/// ([`stray_interrupt_count`]) rather than re-entering forever, so a source a
735/// game needs must be serviced by the game's own handler ahead of this one
736/// (which then chains here), not left to this handler.
737#[cfg(target_arch = "mips")]
738pub fn install_vblank_counter() {
739    const EXCEPTION_VECTOR: *mut u32 = 0x8000_0080 as *mut u32;
740    const J_OPCODE: u32 = 0x0800_0000;
741
742    // SAFETY: 0x8000_0080 is the R3000 general exception vector in KSEG0 kernel RAM, two aligned
743    // words written here as `j handler` plus a nop delay slot, then the I-cache is flushed so the
744    // CPU fetches them. The counter and INSTALLED are psx-rt-private statics written through raw
745    // pointers, so no reference aliases them. `enable_cpu_interrupts` runs only after the vector
746    // points at psx-rt's handler. Assumes nothing still depends on the vector this replaces (a game
747    // wrapper installed earlier is overwritten).
748    unsafe {
749        let handler = __psx_rt_exception_handler as *const () as usize as u32;
750        core::ptr::write_volatile(EXCEPTION_VECTOR, J_OPCODE | ((handler >> 2) & 0x03ff_ffff));
751        core::ptr::write_volatile(EXCEPTION_VECTOR.add(1), 0);
752        crate::cache::flush_instruction_cache();
753
754        // Whatever wrapper was in front of the old handler is gone: a wrapper
755        // that kept its own record of being installed can tell by the epoch,
756        // and no source is claimed any more.
757        core::ptr::write_volatile(
758            &raw mut VECTOR_EPOCH,
759            core::ptr::read_volatile(&raw const VECTOR_EPOCH).wrapping_add(1),
760        );
761        core::ptr::write_volatile(&raw mut __psx_rt_claimed_irq, 0);
762
763        core::ptr::write_volatile(&raw mut __psx_rt_vblank_count, 0);
764        core::ptr::write_volatile(&raw mut __psx_rt_flip_hold, 0);
765        core::ptr::write_volatile(&raw mut __psx_rt_flip_age, FLIP_AGE_UNKNOWN);
766        // The cap itself stays as the program set it. Direct flips (`DoubleBuffer::swap`) wait
767        // on it through this pacer.
768        psx_io::gpu::set_flip_pacer(Some(pace_direct_flip));
769        irq::acknowledge(1 << psx_hw::irq::source::VBLANK);
770        // This handler services VBlank only. After a BIOS disc boot, do not
771        // preserve CD-ROM/DMA/etc. bits the BIOS may have left enabled.
772        irq::set_mask(1 << psx_hw::irq::source::VBLANK);
773        enable_cpu_interrupts();
774        core::ptr::write_volatile(&raw mut INSTALLED, true);
775    }
776}
777
778/// Install and enable the VBlank counter interrupt path.
779#[cfg(not(target_arch = "mips"))]
780pub fn install_vblank_counter() {}
781
782/// How many times [`install_vblank_counter`] has put psx-rt's handler in the
783/// vector. That drops every wrapper chained in front of it, so a wrapper
784/// (psx-cdstream's, the pad engine's) that remembers installing itself is
785/// still in the chain only while this reads what it read then.
786#[cfg(target_arch = "mips")]
787static mut VECTOR_EPOCH: u32 = 0;
788
789/// See [`VECTOR_EPOCH`]; zero off-target.
790pub fn vector_epoch() -> u32 {
791    #[cfg(target_arch = "mips")]
792    // SAFETY: a volatile aligned read of a word only this module writes.
793    unsafe {
794        core::ptr::read_volatile(&raw const VECTOR_EPOCH)
795    }
796    #[cfg(not(target_arch = "mips"))]
797    0
798}
799
800/// Unexpected exceptions survived so far. Non-zero means some access
801/// faulted and was stepped over; the value it read or wrote is garbage.
802#[inline]
803pub fn fault_count() -> u32 {
804    // SAFETY: a volatile aligned u32 read through a raw pointer, so no reference is formed. Only
805    // the asm exception handler writes it, and an aligned word load cannot tear.
806    unsafe { core::ptr::read_volatile(&raw const __psx_rt_fault_count) }
807}
808
809/// Interrupts that landed on a GTE command, whose return the handler moved
810/// to EPC + 4 so the command did not run twice.
811#[inline]
812pub fn gte_skip_count() -> u32 {
813    // SAFETY: a volatile aligned u32 read through a raw pointer, so no reference is formed. Only
814    // the asm exception handler writes it, and an aligned word load cannot tear.
815    unsafe { core::ptr::read_volatile(&raw const __psx_rt_gte_skip_count) }
816}
817
818/// True when `word` is a GTE command (a COP2 `cofun`: opcode 0x12 with bit
819/// 25 set, so the top seven bits are `0100101`). psx-spx's test is
820/// `(word & 0xFE00_0000) == 0x4A00_0000`. GTE register moves (`mfc2`,
821/// `mtc2`, `cfc2`, `ctc2`), `lwc2`/`swc2` and the `bc2` branches are not
822/// commands: an interrupt on them is taken before they run.
823#[inline]
824pub const fn is_gte_command(word: u32) -> bool {
825    psx_hw::gte::is_command(word)
826}
827
828/// Where psx-rt's exception handler resumes after an interrupt: `epc`, or
829/// `epc + 4` when `word_at_epc` is a GTE command.
830///
831/// On silicon an interrupt taken on a GTE command lets the command run and
832/// still reports EPC at it, so resuming at EPC runs it twice
833/// (hardware-tests v1.24, case 0xC9: 38 of 38; with this rule, case 0xCB:
834/// 61 skips, none doubled or lost). The handler's assembly makes exactly
835/// this decision.
836///
837/// With Cause.BD set, EPC is the branch whose delay slot was interrupted,
838/// so `word_at_epc` is a branch and the result is `epc`: the branch and a
839/// GTE command in its delay slot both run again. psx-spx documents that
840/// the fix cannot cover delay slots; keep GTE commands out of them
841/// (`hazard-scan` warns about any in an image).
842#[inline]
843pub const fn interrupt_resume_pc(epc: u32, word_at_epc: u32) -> u32 {
844    if is_gte_command(word_at_epc) {
845        epc.wrapping_add(4)
846    } else {
847        epc
848    }
849}
850
851/// Where psx-rt's exception handler resumes after a fault (any exception
852/// but an interrupt), or `None` where it halts. `badvaddr` is COP0
853/// BadVAddr.
854///
855/// BREAK (the shipping form of `panic=immediate-abort`), an instruction bus
856/// error and a misaligned instruction fetch (AdEL with BadVAddr == EPC)
857/// halt. So does any fault with [`psx_hw::cop0::CAUSE_BD`] set: the faulting instruction
858/// sat in the delay slot of the branch at EPC, which has already run, so
859/// `epc + 4` would run the faulting instruction again as if the branch had
860/// fallen through, and resuming where the branch goes would take decoding
861/// it, handler code every game carries for a path only a bug reaches.
862/// Every other fault is stepped over (`epc + 4`) and counted, unless
863/// [`STRICT_FAULTS`] is set, in which case every fault halts. The
864/// handler's assembly makes exactly this decision; before halting it
865/// records Cause, EPC and BadVAddr ([`fault_cause`], [`fault_pc`],
866/// [`fault_bad_address`]).
867pub const fn fault_resume_pc(cause: u32, epc: u32, badvaddr: u32) -> Option<u32> {
868    resume_after_fault(STRICT_FAULTS, cause, epc, badvaddr)
869}
870
871/// [`fault_resume_pc`] for either policy, so host tests cover both.
872const fn resume_after_fault(strict: bool, cause: u32, epc: u32, badvaddr: u32) -> Option<u32> {
873    if strict {
874        return None;
875    }
876    match (cause >> 2) & 0x1f {
877        // Break, IBE
878        9 | 6 => return None,
879        // AdEL on the fetch itself
880        4 if badvaddr == epc => return None,
881        _ => {}
882    }
883    if cause & psx_hw::cop0::CAUSE_BD != 0 {
884        None
885    } else {
886        Some(epc.wrapping_add(4))
887    }
888}
889
890/// COP0 BadVAddr captured for the latest unexpected exception.
891#[inline]
892#[doc(alias = "BadVAddr")]
893pub fn fault_bad_address() -> u32 {
894    // SAFETY: a volatile aligned u32 read through a raw pointer, so no reference is formed. Only
895    // the asm exception handler writes it, and an aligned word load cannot tear.
896    unsafe { core::ptr::read_volatile(&raw const __psx_rt_fault_badvaddr) }
897}
898
899/// Raw COP0 Cause captured for the latest unexpected exception.
900#[inline]
901pub fn fault_cause() -> u32 {
902    // SAFETY: a volatile aligned u32 read through a raw pointer, so no reference is formed. Only
903    // the asm exception handler writes it, and an aligned word load cannot tear.
904    unsafe { core::ptr::read_volatile(&raw const __psx_rt_fault_cause) }
905}
906
907/// COP0 EPC captured for the latest unexpected exception.
908#[inline]
909#[doc(alias = "EPC")]
910pub fn fault_pc() -> u32 {
911    // SAFETY: a volatile aligned u32 read through a raw pointer, so no reference is formed. Only
912    // the asm exception handler writes it, and an aligned word load cannot tear.
913    unsafe { core::ptr::read_volatile(&raw const __psx_rt_fault_epc) }
914}
915
916/// Set the presentation cap: the fewest VBlanks between two display flips (0 is
917/// treated as 1).
918///
919/// Every program starts at 2 ([`DEFAULT_MIN_FLIP_VBLANKS`], `psx_tick::PresentCap::HZ30`), so the picture never changes
920/// faster than 30 fps NTSC (25 PAL): a flip a frame finished early waits for its
921/// slot. A game that deliberately targets the full display rate opts out by name,
922/// once at boot:
923///
924/// ```ignore
925/// psx_rt::interrupts::set_min_flip_vblanks(psx_tick::PresentCap::UNCAPPED.min_vblanks());
926/// ```
927///
928/// The cap applies to every display flip made through psx-rt: a word queued
929/// with [`queue_display_control_at_vblank`] (the handler holds it at the edge
930/// until the cap allows it), a frame kicked by the present queue, and a
931/// `DoubleBuffer::swap` (which waits, bounded, before the flip). Other display
932/// words (video on or off) are never held. Frames slower than the cap are not
933/// delayed.
934pub fn set_min_flip_vblanks(vblanks: u8) {
935    // SAFETY: an aligned volatile word store; the handler only reads it and the cap is a plain
936    // value, so no ordering with the handler matters.
937    unsafe { core::ptr::write_volatile(&raw mut __psx_rt_flip_min, u32::from(vblanks.max(1))) }
938}
939
940/// The presentation cap in force, in VBlanks (see [`set_min_flip_vblanks`]).
941#[must_use]
942pub fn min_flip_vblanks() -> u8 {
943    // SAFETY: an aligned volatile word load of a value written only by `set_present_cap`.
944    let min = unsafe { core::ptr::read_volatile(&raw const __psx_rt_flip_min) };
945    min.min(u32::from(u8::MAX)) as u8
946}
947
948/// How many flips came 0, 1, 2 ... VBlanks after the one before, since boot or
949/// [`reset_flip_histogram`]. With the cap on, no flip is counted below its
950/// VBlanks (`psx_tick::FlipHistogram::from_buckets(flip_histogram())
951/// .below(min_flip_vblanks()) == 0`); the first flip after a reset has no
952/// predecessor and counts in the last bucket.
953#[must_use]
954pub fn flip_histogram() -> [u32; FLIP_HISTOGRAM_BUCKETS] {
955    let mut histogram = [0u32; FLIP_HISTOGRAM_BUCKETS];
956    let mut bucket = 0;
957    while bucket < FLIP_HISTOGRAM_BUCKETS {
958        // SAFETY: an aligned volatile word load of a counter only the handler and
959        // `reset_flip_histogram` write; a torn view across buckets is harmless for a count.
960        histogram[bucket] = unsafe {
961            core::ptr::read_volatile((&raw const __psx_rt_flip_hist).cast::<u32>().add(bucket))
962        };
963        bucket += 1;
964    }
965    histogram
966}
967
968/// Zero the flip histogram and forget the last flip, so the next one is the
969/// first of a new count. Call it at the start of a measured stretch.
970pub fn reset_flip_histogram() {
971    psx_io::irq::without_interrupts(|| {
972        // SAFETY: with CPU interrupts masked the handler cannot run, so these volatile stores
973        // are the only accesses.
974        unsafe {
975            let mut bucket = 0;
976            while bucket < FLIP_HISTOGRAM_BUCKETS {
977                core::ptr::write_volatile(
978                    (&raw mut __psx_rt_flip_hist).cast::<u32>().add(bucket),
979                    0,
980                );
981                bucket += 1;
982            }
983            core::ptr::write_volatile(&raw mut __psx_rt_flip_age, FLIP_AGE_UNKNOWN);
984        }
985    });
986}
987
988/// Whether CPU interrupts are enabled (COP0 SR.IEc).
989#[cfg(target_arch = "mips")]
990fn cpu_interrupts_enabled() -> bool {
991    let sr: u32;
992    // SAFETY: reads COP0 SR into $8 (the output); the nop covers MFC0's load delay. No memory or
993    // other register is touched.
994    unsafe { core::arch::asm!("mfc0 $8, $12", "nop", lateout("$8") sr) };
995    sr & 1 != 0
996}
997
998/// The wait in front of a direct display flip (`Gpu::set_display_start`): until
999/// the handler has counted the cap's VBlanks off since the last flip, then count
1000/// this flip like the handler counts a queued one.
1001///
1002/// Skipped without the counter running or with interrupts masked, where nothing
1003/// would ever release it; bounded either way ([`crate::wait::SPIN_LIMIT`]).
1004#[cfg(target_arch = "mips")]
1005fn pace_direct_flip() {
1006    // SAFETY: an aligned volatile word load of a static only `set_min_flip_vblanks` writes.
1007    let min = unsafe { core::ptr::read_volatile(&raw const __psx_rt_flip_min) };
1008    // SAFETY: an aligned volatile byte load of a flag only `install_vblank_counter` writes.
1009    let running = unsafe { core::ptr::read_volatile(&raw const INSTALLED) };
1010    if min > 1 && running && cpu_interrupts_enabled() {
1011        crate::wait::wait_while(
1012            // SAFETY: an aligned volatile word load; the handler is the only writer.
1013            || unsafe { core::ptr::read_volatile(&raw const __psx_rt_flip_hold) } != 0,
1014            || false,
1015            || {},
1016            crate::wait::SPIN_LIMIT,
1017        );
1018    }
1019    // SAFETY: with CPU interrupts masked the handler cannot run, so these aligned volatile
1020    // accesses to its statics are the only ones, and the histogram index is clamped in range.
1021    psx_io::irq::without_interrupts(|| unsafe {
1022        let age = core::ptr::read_volatile(&raw const __psx_rt_flip_age);
1023        let bucket = (age as usize).min(FLIP_HISTOGRAM_BUCKETS - 1);
1024        let slot = (&raw mut __psx_rt_flip_hist).cast::<u32>().add(bucket);
1025        core::ptr::write_volatile(slot, core::ptr::read_volatile(slot).wrapping_add(1));
1026        core::ptr::write_volatile(&raw mut __psx_rt_flip_age, 0);
1027        core::ptr::write_volatile(&raw mut __psx_rt_flip_hold, min);
1028    });
1029}
1030
1031/// Current monotonic VBlank count.
1032#[inline]
1033#[doc(alias = "VSync")]
1034pub fn vblank_count() -> u32 {
1035    // SAFETY: a volatile aligned u32 read through a raw pointer, so no reference is formed. The
1036    // asm handler and `install_vblank_counter` are the only writers, and an aligned word load
1037    // cannot tear.
1038    unsafe { core::ptr::read_volatile(&raw const __psx_rt_vblank_count) }
1039}
1040
1041/// Queue one GP1 word for the VBlank handler to apply at a blank edge
1042/// (deferred tear-free display flip). Overwrites any unapplied word.
1043///
1044/// The handler applies the word at the first VBlank edge on which GPUSTAT
1045/// bit 24 (the GPU's IRQ1 flag) is set, so the frame must signal its own
1046/// end:
1047///
1048/// 1. acknowledge the flag with GP1(02h) before kicking the frame's work
1049///    (`psx_gpu::arm_draw_done`), after the previous flip has landed;
1050/// 2. end that work with GP0(1Fh): as the last node of the DMA chain
1051///    (`psx_gpu::OrderingTable::end_with_draw_done`, or a one-word packet
1052///    in an ordered stream) or, after drawing through the ports,
1053///    `psx_gpu::signal_draw_done`;
1054/// 3. queue the display-start word here.
1055///
1056/// The flag stays set until the next acknowledge, so a word queued while
1057/// the GPU is idle after such a frame (a display enable, say) applies at
1058/// the next edge. A game that never sends GP0(1Fh) never flips: before this
1059/// handler tested bit 24 it tested GPUSTAT bit 28, which on silicon rises
1060/// about one large primitive before the drawing ends (hardware-tests v1.24
1061/// cases 219-226), so a flip could expose a frame one primitive short.
1062/// Keep interrupt source 1 (GPU) masked in `I_MASK`: this handler owns VBlank
1063/// only, so a GPU interrupt it finds is acknowledged as a stray and counted
1064/// ([`stray_interrupt_count`]), which costs a handler entry per frame.
1065#[cfg(target_arch = "mips")]
1066#[inline]
1067#[doc(alias = "GP1")]
1068pub fn queue_display_control_at_vblank(word: u32) {
1069    // SAFETY: a volatile aligned u32 store through a raw pointer, so no reference is formed. The
1070    // VBlank handler is the only other accessor, and an aligned word store cannot tear.
1071    unsafe { core::ptr::write_volatile(&raw mut __psx_rt_pending_gp1, word) }
1072}
1073
1074/// Host no-op: no IRQ exists to consume the queue off-target.
1075#[cfg(not(target_arch = "mips"))]
1076#[inline]
1077#[doc(alias = "GP1")]
1078pub fn queue_display_control_at_vblank(_word: u32) {}
1079
1080/// Renamed to [`queue_display_control_at_vblank`].
1081#[deprecated(note = "renamed to `queue_display_control_at_vblank`")]
1082#[inline(always)]
1083pub fn queue_gp1_at_vblank(word: u32) {
1084    queue_display_control_at_vblank(word)
1085}
1086
1087/// True while a word queued by [`queue_display_control_at_vblank`] has not
1088/// yet been applied by the VBlank handler.
1089#[cfg(target_arch = "mips")]
1090#[inline]
1091#[doc(alias = "GP1")]
1092pub fn is_display_control_queued() -> bool {
1093    // SAFETY: a volatile aligned u32 read through a raw pointer, so no reference is formed. The
1094    // VBlank handler is the only other accessor, and an aligned word load cannot tear.
1095    unsafe { core::ptr::read_volatile(&raw const __psx_rt_pending_gp1) != 0 }
1096}
1097
1098/// Empty the queue and hand back the word the handler has not applied, so
1099/// the caller can write it to GP1 itself. Returns 0 when nothing was queued.
1100///
1101/// The handler only applies its word at a blank edge on which GPUSTAT
1102/// bit 24 is set (see [`queue_display_control_at_vblank`]), so a long enough frame, or
1103/// one that never sends GP0(1Fh), leaves it queued indefinitely. A caller that has given up waiting must take the word
1104/// rather than leave it: the next [`queue_display_control_at_vblank`] overwrites the
1105/// slot, and a display start that never reaches the GPU desynchronises the
1106/// display side from the draw side for the rest of the session.
1107///
1108/// Racing the handler is harmless. If the IRQ lands between the read and
1109/// the clear, the handler applies the word and the caller writes the same
1110/// value again; GP1(05h) is idempotent.
1111#[cfg(target_arch = "mips")]
1112#[inline]
1113#[doc(alias = "GP1")]
1114pub fn take_queued_display_control() -> u32 {
1115    // SAFETY: volatile aligned u32 accesses through a raw pointer, so no reference is formed. A
1116    // handler run between the read and the clear is harmless (see above).
1117    unsafe {
1118        let word = core::ptr::read_volatile(&raw const __psx_rt_pending_gp1);
1119        if word != 0 {
1120            core::ptr::write_volatile(&raw mut __psx_rt_pending_gp1, 0);
1121        }
1122        word
1123    }
1124}
1125
1126/// Host: nothing is ever queued, so nothing can be taken.
1127#[cfg(not(target_arch = "mips"))]
1128#[inline]
1129#[doc(alias = "GP1")]
1130pub fn take_queued_display_control() -> u32 {
1131    0
1132}
1133
1134/// Renamed to [`take_queued_display_control`].
1135#[deprecated(note = "renamed to `take_queued_display_control`")]
1136#[inline(always)]
1137pub fn take_pending_gp1() -> u32 {
1138    take_queued_display_control()
1139}
1140
1141/// Host no-op: nothing is ever pending off-target.
1142#[cfg(not(target_arch = "mips"))]
1143#[inline]
1144#[doc(alias = "GP1")]
1145pub fn is_display_control_queued() -> bool {
1146    false
1147}
1148
1149/// Renamed to [`is_display_control_queued`].
1150#[deprecated(note = "renamed to `is_display_control_queued`")]
1151#[inline(always)]
1152pub fn gp1_queue_pending() -> bool {
1153    is_display_control_queued()
1154}
1155
1156/// Block until the next VBlank IRQ.
1157///
1158/// This is the display-sync primitive: a frame that finishes early sleeps
1159/// until the blank, and a slow frame snaps to the next one, so presentation
1160/// quantizes to whole display periods. (`psx_gpu::vsync()` cannot do this:
1161/// it reconfigures Timer 1 on every call, and a mode write resets the
1162/// counter, so it busy-waits a fixed 242 HBlanks from the call site
1163/// instead of syncing to the display.)
1164///
1165/// Installs the VBlank counter on first use if the game has not already
1166/// called [`install_vblank_counter`], but only while the exception vector is
1167/// still the one the program booted with. A game that has put its own
1168/// handler there keeps it: this function never overwrites it. Such a game
1169/// calls [`install_vblank_counter`] first and then wraps psx-rt's handler,
1170/// or its handler chains to psx-rt's, which is what advances the count this
1171/// waits on. The wait is bounded: after about four million reads
1172/// without the count moving it returns (and asserts in a debug build) instead
1173/// of hanging, as it would inside a critical section or without the handler.
1174/// [`try_wait_vblank`] takes the bound.
1175#[cfg(target_arch = "mips")]
1176#[doc(alias = "VSync")]
1177pub fn wait_vblank() {
1178    // SAFETY: volatile reads of private flags through raw pointers; only `install_vblank_counter`
1179    // and `record_boot_vector` write them, on this same single thread.
1180    unsafe {
1181        if !core::ptr::read_volatile(&raw const INSTALLED) {
1182            let boot = core::ptr::read_volatile(&raw const BOOT_VECTOR_RECORDED)
1183                .then(|| core::ptr::read_volatile(&raw const BOOT_VECTOR_WORD));
1184            let handler = __psx_rt_exception_handler as *const () as usize as u32;
1185            if may_install_lazily(boot, vector_word(), jump_word(handler)) {
1186                install_vblank_counter();
1187            }
1188        }
1189    }
1190    if !try_wait_vblank(crate::wait::SPIN_LIMIT) {
1191        debug_assert!(
1192            false,
1193            "wait_vblank: the VBlank count never advanced; psx-rt's handler is not running"
1194        );
1195    }
1196}
1197
1198/// [`wait_vblank`] with its own bound: `true` once the count has advanced,
1199/// `false` after `spins` reads of it without a change. A `false` means no
1200/// VBlank interrupt reached psx-rt's handler: interrupts are masked (inside a
1201/// [`critical_section`](crate::critical_section)), the counter was never
1202/// installed, or a game's handler does not chain to psx-rt's. Does not
1203/// install the counter; [`wait_vblank`] does that first.
1204#[cfg(target_arch = "mips")]
1205pub fn try_wait_vblank(spins: u32) -> bool {
1206    let start = vblank_count();
1207    crate::wait::wait_while(|| vblank_count() == start, || false, || {}, spins)
1208}
1209
1210/// Block until the next VBlank IRQ. Host no-op: the counter never
1211/// advances off-target, so waiting would hang.
1212#[cfg(not(target_arch = "mips"))]
1213#[doc(alias = "VSync")]
1214pub fn wait_vblank() {}
1215
1216/// True when the general exception vector jumps to psx-rt's handler, the
1217/// one that never touches `$sp` (so interrupts are safe on any stack).
1218#[cfg(target_arch = "mips")]
1219pub fn is_handler_installed() -> bool {
1220    let handler = __psx_rt_exception_handler as *const () as usize as u32;
1221    vector_word() == jump_word(handler)
1222}
1223
1224/// The vector word of a game's exception handler declared with
1225/// [`declare_stack_safe_handler`]; zero when none is.
1226#[cfg(target_arch = "mips")]
1227static mut STACK_SAFE_HANDLER: u32 = 0;
1228
1229/// Declare that the game's own exception handler at `handler` is safe to
1230/// take an interrupt on any stack, including a
1231/// [`ScratchpadStack`](crate::scratchpad::ScratchpadStack).
1232///
1233/// With the `scratchpad-stack-check` feature, a stack switch traps when
1234/// interrupts are on and the general exception vector jumps anywhere but
1235/// psx-rt's handler, because a handler that pushes onto the interrupted
1236/// stack would write below the scratchpad stack's frames. A game that
1237/// installs its own vector (hk-psx wraps psx-rt's handler to service CD
1238/// interrupts, then jumps to it) calls this once with the address it puts
1239/// in the vector; the check then accepts exactly that vector word, and
1240/// still traps any other handler, such as a BIOS vector restored behind the
1241/// game's back. Declaring does not install anything.
1242///
1243/// ```no_run
1244/// unsafe extern "C" fn game_exception_wrapper() {}
1245/// // SAFETY: game_exception_wrapper switches to its own stack before it
1246/// // stores anything and restores $sp before it hands back.
1247/// unsafe { psx_rt::interrupts::declare_stack_safe_handler(game_exception_wrapper) };
1248/// ```
1249///
1250/// # Safety
1251///
1252/// `handler`, and everything it calls or jumps to, must leave `$sp` and the
1253/// memory below it alone: it uses only `$k0`/`$k1` or saves state to memory
1254/// of its own and runs on a stack of its own, and it returns (or chains to
1255/// psx-rt's handler) with `$sp` unchanged.
1256#[cfg(target_arch = "mips")]
1257pub unsafe fn declare_stack_safe_handler(handler: unsafe extern "C" fn()) {
1258    // SAFETY: a plain store; nothing reads it from an interrupt.
1259    unsafe {
1260        core::ptr::write_volatile(
1261            &raw mut STACK_SAFE_HANDLER,
1262            jump_word(handler as *const () as usize as u32),
1263        )
1264    }
1265}
1266
1267/// Declare a stack-safe exception handler. Host no-op: there are no
1268/// exception vectors off-target.
1269///
1270/// # Safety
1271///
1272/// As on the target.
1273#[cfg(not(target_arch = "mips"))]
1274pub unsafe fn declare_stack_safe_handler(_handler: unsafe extern "C" fn()) {}
1275
1276/// True when the general exception vector jumps to psx-rt's handler or to
1277/// the one declared with [`declare_stack_safe_handler`].
1278#[cfg(target_arch = "mips")]
1279pub fn is_stack_safe_handler_installed() -> bool {
1280    // SAFETY: a plain read of a word only this module writes.
1281    let declared = unsafe { core::ptr::read_volatile(&raw const STACK_SAFE_HANDLER) };
1282    is_handler_installed() || (declared != 0 && vector_word() == declared)
1283}
1284
1285/// The `j handler` word psx-rt writes into the vector.
1286#[cfg(target_arch = "mips")]
1287fn jump_word(handler: u32) -> u32 {
1288    0x0800_0000 | ((handler >> 2) & 0x03ff_ffff)
1289}
1290
1291/// The first word of the general exception vector.
1292#[cfg(target_arch = "mips")]
1293fn vector_word() -> u32 {
1294    const EXCEPTION_VECTOR: *const u32 = 0x8000_0080 as *const u32;
1295    // SAFETY: a read of the kernel's vector word.
1296    unsafe { core::ptr::read_volatile(EXCEPTION_VECTOR) }
1297}
1298
1299/// True when COP0 SR has interrupts enabled (IEc).
1300#[cfg(target_arch = "mips")]
1301pub fn are_interrupts_enabled() -> bool {
1302    let sr: u32;
1303    // The nop covers MFC0's load delay.
1304    // SAFETY: reads COP0 SR into $8, declared as the output, and the nop covers MFC0's load delay.
1305    // No memory or stack is touched, as the options state.
1306    unsafe { core::arch::asm!("mfc0 $8, $12", "nop", lateout("$8") sr, options(nomem, nostack)) };
1307    sr & 1 != 0
1308}
1309
1310#[cfg(target_arch = "mips")]
1311unsafe fn enable_cpu_interrupts() {
1312    const STATUS_IE: u32 = 1 << 0;
1313    const STATUS_IM2: u32 = 1 << 10;
1314    const STATUS_CU2: u32 = 1 << 30;
1315
1316    let mut sr: u32;
1317    // MFC0 has a one-instruction load-delay hazard on the R3000: without the
1318    // nop the asm block hands back the STALE $8, and whatever garbage it held
1319    // gets OR'd into SR (seen in the wild as BEV set -> exceptions vectoring
1320    // into ROM -> pc walking off the end of the BIOS).
1321    // SAFETY: reads COP0 SR into $8, declared as the output, and the nop covers MFC0's load delay.
1322    // No other register or memory is touched.
1323    unsafe { core::arch::asm!("mfc0 $8, $12", "nop", lateout("$8") sr) };
1324    sr |= STATUS_IE | STATUS_IM2 | STATUS_CU2;
1325    // SAFETY: writes SR back with IEc, IM2 and CU2 set and every other bit as read above. The only
1326    // caller, `install_vblank_counter`, has already pointed the exception vector at psx-rt's
1327    // handler, so the interrupts this enables land there.
1328    unsafe { core::arch::asm!("mtc0 $8, $12", in("$8") sr) };
1329}
1330
1331#[cfg(test)]
1332mod tests {
1333    use super::*;
1334
1335    const EPC: u32 = 0x8001_2340;
1336
1337    /// GTE commands the SDK issues, as their encoded words.
1338    const RTPS: u32 = 0x4a18_0001;
1339    const RTPT: u32 = 0x4a28_0030;
1340    const NCLIP: u32 = 0x4b40_0006;
1341    const MVMVA: u32 = 0x4a48_6012;
1342    const AVSZ3: u32 = 0x4b58_002d;
1343    const GPF: u32 = 0x4b90_003d;
1344
1345    #[test]
1346    fn an_interrupt_on_a_gte_command_resumes_after_it() {
1347        for word in [RTPS, RTPT, NCLIP, MVMVA, AVSZ3, GPF] {
1348            assert!(is_gte_command(word), "{word:#010x}");
1349            assert_eq!(interrupt_resume_pc(EPC, word), EPC + 4, "{word:#010x}");
1350        }
1351    }
1352
1353    #[test]
1354    fn psx_spx_mask_and_seven_bit_test_agree() {
1355        // Every top byte, with the rest of the word set both ways.
1356        for top in 0u32..=0xff {
1357            for low in [0, 0x00ff_ffff] {
1358                let word = (top << 24) | low;
1359                assert_eq!(
1360                    is_gte_command(word),
1361                    word & 0xfe00_0000 == 0x4a00_0000,
1362                    "{word:#010x}"
1363                );
1364            }
1365        }
1366    }
1367
1368    #[test]
1369    fn gte_register_moves_and_loads_resume_at_epc() {
1370        let not_commands = [
1371            0x480c_6000, // mfc2 $12, SXY0
1372            0x4889_6000, // mtc2 $9, SXY0
1373            0x4842_f800, // cfc2 $2, FLAG
1374            0x48c2_c000, // ctc2 $2, OFX
1375            0xc885_0000, // lwc2 $5, 0($4)
1376            0xe8ac_0000, // swc2 $12, 0($5)
1377            0x4900_0003, // bc2f
1378            0x4901_0003, // bc2t
1379            0x4080_6000, // mtc0 $0, SR
1380            0x0000_0000, // nop
1381            0x8c82_0000, // lw $2, 0($4)
1382            0x03e0_0008, // jr $ra
1383        ];
1384        for word in not_commands {
1385            assert!(!is_gte_command(word), "{word:#010x}");
1386            assert_eq!(interrupt_resume_pc(EPC, word), EPC, "{word:#010x}");
1387        }
1388    }
1389
1390    #[test]
1391    fn a_gte_command_in_a_delay_slot_is_not_stepped_over() {
1392        // Cause.BD set: EPC names the branch, the RTPS sits at EPC + 4. The
1393        // handler reads the branch, so it resumes at EPC and the branch and
1394        // its RTPS both run again (psx-spx: the fix does not cover delay
1395        // slots). Stepping to EPC + 4 would drop the branch instead, and
1396        // EPC + 8 would drop the branch target; neither is safe, which is
1397        // why the answer is to keep GTE commands out of delay slots.
1398        let branches = [
1399            0x1509_fff0, // bne $8, $9, back
1400            0x1000_0004, // b forward
1401            0x0c00_4000, // jal
1402            0x0800_4000, // j
1403            0x0100_f809, // jalr $8
1404            0x03e0_0008, // jr $ra
1405        ];
1406        for branch in branches {
1407            assert_eq!(interrupt_resume_pc(EPC, branch), EPC, "{branch:#010x}");
1408        }
1409    }
1410
1411    #[test]
1412    fn the_resume_address_wraps_like_the_hardware_add() {
1413        assert_eq!(interrupt_resume_pc(0xffff_fffc, RTPS), 0);
1414        assert_eq!(resume_after_fault(false, DBE, 0xffff_fffc, 0), Some(0));
1415    }
1416
1417    // Fault path. Cause values are ExcCode << 2, plus CAUSE_BD.
1418    const ADEL: u32 = 4 << 2;
1419    const ADES: u32 = 5 << 2;
1420    const IBE: u32 = 6 << 2;
1421    const DBE: u32 = 7 << 2;
1422    const BREAK: u32 = 9 << 2;
1423    const RI: u32 = 10 << 2;
1424    const CPU: u32 = 11 << 2;
1425    const OV: u32 = 12 << 2;
1426
1427    /// A misaligned data address: never equal to an (aligned) EPC.
1428    const BAD_DATA: u32 = 0x8001_0001;
1429
1430    #[test]
1431    fn a_fault_outside_a_delay_slot_resumes_after_it() {
1432        for cause in [ADEL, ADES, DBE, RI, CPU, OV] {
1433            assert_eq!(
1434                resume_after_fault(false, cause, EPC, BAD_DATA),
1435                Some(EPC + 4),
1436                "{cause:#x}"
1437            );
1438        }
1439    }
1440
1441    #[test]
1442    fn a_fault_in_a_delay_slot_halts() {
1443        // Cause.BD: the faulting word is at EPC + 4, behind the branch at
1444        // EPC. EPC + 4 would re-run it with the branch dropped (a taken
1445        // branch would fall through), so the handler halts instead.
1446        for cause in [ADEL, ADES, DBE, RI, CPU, OV] {
1447            assert_eq!(
1448                resume_after_fault(false, cause | psx_hw::cop0::CAUSE_BD, EPC, BAD_DATA),
1449                None,
1450                "{cause:#x}"
1451            );
1452        }
1453    }
1454
1455    #[test]
1456    fn fatal_faults_halt_in_or_out_of_a_delay_slot() {
1457        for bd in [0, psx_hw::cop0::CAUSE_BD] {
1458            assert_eq!(resume_after_fault(false, BREAK | bd, EPC, 0), None);
1459            assert_eq!(resume_after_fault(false, IBE | bd, EPC, 0), None);
1460            assert_eq!(resume_after_fault(false, ADEL | bd, EPC, EPC), None);
1461        }
1462    }
1463
1464    #[test]
1465    fn a_gte_command_in_a_delay_slot_interrupt_versus_fault() {
1466        // bne $8, $9, -4 at EPC with an RTPS in its slot. An interrupt there
1467        // resumes at the branch, so both run again (documented above); a
1468        // fault there (Coprocessor Unusable with SR.CU2 clear, say) halts.
1469        let bne = 0x1509_fffc;
1470        assert_eq!(interrupt_resume_pc(EPC, bne), EPC);
1471        assert_eq!(
1472            resume_after_fault(false, CPU | psx_hw::cop0::CAUSE_BD, EPC, 0),
1473            None
1474        );
1475        // Outside a delay slot the same fault steps over the RTPS.
1476        assert_eq!(resume_after_fault(false, CPU, EPC, 0), Some(EPC + 4));
1477    }
1478
1479    #[test]
1480    fn strict_faults_halt_on_every_fault() {
1481        for bd in [0, psx_hw::cop0::CAUSE_BD] {
1482            for cause in [ADEL, ADES, IBE, DBE, BREAK, RI, CPU, OV] {
1483                assert_eq!(
1484                    resume_after_fault(true, cause | bd, EPC, BAD_DATA),
1485                    None,
1486                    "{cause:#x} {bd:#x}"
1487                );
1488            }
1489        }
1490    }
1491
1492    // Vector words: a BIOS stub, psx-rt's jump, and a game wrapper's jump.
1493    const BIOS_STUB: u32 = 0x3c1a_0000;
1494    const RT_JUMP: u32 = 0x0800_4000;
1495    const GAME_JUMP: u32 = 0x0800_8000;
1496
1497    #[test]
1498    fn a_safe_wait_installs_only_over_the_boot_vector_or_its_own() {
1499        // Untouched since boot, or already psx-rt's: install.
1500        assert!(may_install_lazily(Some(BIOS_STUB), BIOS_STUB, RT_JUMP));
1501        assert!(may_install_lazily(Some(BIOS_STUB), RT_JUMP, RT_JUMP));
1502        // A game's own handler is never overwritten.
1503        assert!(!may_install_lazily(Some(BIOS_STUB), GAME_JUMP, RT_JUMP));
1504        // The boot word was itself another program's handler: still "untouched".
1505        assert!(may_install_lazily(Some(GAME_JUMP), GAME_JUMP, RT_JUMP));
1506        // No recorded boot word: the entry predates the rule, keep installing.
1507        assert!(may_install_lazily(None, GAME_JUMP, RT_JUMP));
1508    }
1509
1510    // I_STAT / I_MASK bits (psx-spx): VBlank 0, GPU 1, CDROM 2, DMA 3.
1511    const VBLANK_BIT: u32 = 1 << 0;
1512    const GPU_BIT: u32 = 1 << 1;
1513    const CDROM_BIT: u32 = 1 << 2;
1514    const INTERRUPT: u32 = 0;
1515
1516    #[test]
1517    fn an_enabled_source_nothing_owns_is_acknowledged() {
1518        // CD enabled and firing with no VBlank: the case that re-entered forever.
1519        assert_eq!(
1520            stray_interrupt_sources(CDROM_BIT, VBLANK_BIT | CDROM_BIT, INTERRUPT),
1521            CDROM_BIT
1522        );
1523        // Only enabled sources count.
1524        assert_eq!(
1525            stray_interrupt_sources(CDROM_BIT | GPU_BIT, VBLANK_BIT | GPU_BIT, INTERRUPT),
1526            GPU_BIT
1527        );
1528        assert_eq!(stray_interrupt_sources(CDROM_BIT, VBLANK_BIT, INTERRUPT), 0);
1529    }
1530
1531    #[test]
1532    fn claims_add_and_release_independently() {
1533        // Nothing else in the host tests touches the claim word.
1534        assert_eq!(claimed_interrupt_sources(), 0);
1535        claim_interrupt_sources(0x80 | 0x10);
1536        claim_interrupt_sources(0x01);
1537        assert_eq!(claimed_interrupt_sources(), 0x91);
1538        release_interrupt_sources(0x10);
1539        assert_eq!(claimed_interrupt_sources(), 0x81);
1540        release_interrupt_sources(0x81);
1541        assert_eq!(claimed_interrupt_sources(), 0);
1542    }
1543
1544    #[test]
1545    fn a_claimed_source_is_left_pending_for_its_wrapper() {
1546        // A CD interrupt that arrived while the pad wrapper's handler ran, and
1547        // a pad interrupt that arrived while the CD handler held interrupts
1548        // off, are not strays: their wrappers take them on the retry.
1549        let mask = VBLANK_BIT | CDROM_BIT | GPU_BIT;
1550        assert_eq!(stray_unclaimed(CDROM_BIT, mask, INTERRUPT, CDROM_BIT), 0);
1551        // Only the claimed ones; an unowned source beside them is still one.
1552        assert_eq!(
1553            stray_unclaimed(CDROM_BIT | GPU_BIT, mask, INTERRUPT, CDROM_BIT),
1554            GPU_BIT
1555        );
1556        assert_eq!(
1557            stray_unclaimed(CDROM_BIT, mask, INTERRUPT, 0),
1558            stray_interrupt_sources(CDROM_BIT, mask, INTERRUPT)
1559        );
1560    }
1561
1562    #[test]
1563    fn a_chained_vblank_leaves_other_sources_for_their_owner() {
1564        // A game's handler services CD itself and chains here for VBlank; a CD
1565        // flag that latched in between must stay in I_STAT for it.
1566        let mask = VBLANK_BIT | CDROM_BIT;
1567        assert_eq!(
1568            stray_interrupt_sources(VBLANK_BIT | CDROM_BIT, mask, INTERRUPT),
1569            0
1570        );
1571    }
1572
1573    #[test]
1574    fn only_interrupts_are_acknowledged() {
1575        for cause in [ADEL, ADES, IBE, DBE, BREAK, RI, CPU, OV] {
1576            assert_eq!(
1577                stray_interrupt_sources(CDROM_BIT, CDROM_BIT, cause),
1578                0,
1579                "{cause:#x}"
1580            );
1581        }
1582        // Cause bits above ExcCode (BD, pending lines) do not hide an interrupt.
1583        let busy = psx_hw::cop0::CAUSE_BD | 0x0400;
1584        assert_eq!(
1585            stray_interrupt_sources(CDROM_BIT, CDROM_BIT, busy),
1586            CDROM_BIT
1587        );
1588    }
1589
1590    #[test]
1591    fn the_public_decision_follows_the_feature() {
1592        for cause in [ADEL, ADES, DBE, RI, CPU, OV] {
1593            assert_eq!(
1594                fault_resume_pc(cause, EPC, BAD_DATA),
1595                resume_after_fault(STRICT_FAULTS, cause, EPC, BAD_DATA),
1596                "{cause:#x}"
1597            );
1598        }
1599    }
1600}