1#[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 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#[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 assert!(gpu::gp1::ACK_IRQ & 0xffff == 0);
432 assert!(dma::dpcr_enable(dma::channel::GPU) <= 0xffff);
434};
435
436pub const CONSOLE_DIAG: bool = cfg!(feature = "console-diag");
439
440#[cfg(all(feature = "console-diag", target_arch = "mips"))]
442pub(crate) fn present_kick_count() -> u32 {
443 #[cfg(feature = "present-queue")]
444 return unsafe { core::ptr::addr_of!(__psx_rt_present_kick_count).read_volatile() };
446 #[cfg(not(feature = "present-queue"))]
447 0
448}
449
450#[cfg(all(feature = "console-diag", target_arch = "mips"))]
452pub(crate) fn present_skip_count() -> u32 {
453 #[cfg(feature = "present-queue")]
454 return unsafe { core::ptr::addr_of!(__psx_rt_present_skip_count).read_volatile() };
456 #[cfg(not(feature = "present-queue"))]
457 0
458}
459
460pub const PRESENT_QUEUE: bool = cfg!(feature = "present-queue");
463
464#[cfg(feature = "present-queue")]
467#[no_mangle]
468pub(crate) static mut __psx_rt_present_head: u32 = 0;
469
470#[cfg(feature = "present-queue")]
473#[no_mangle]
474pub(crate) static mut __psx_rt_present_display: u32 = 0;
475
476#[cfg(feature = "present-queue")]
478#[no_mangle]
479pub(crate) static mut __psx_rt_present_kick_count: u32 = 0;
480
481#[cfg(feature = "present-queue")]
484#[no_mangle]
485pub(crate) static mut __psx_rt_present_skip_count: u32 = 0;
486
487pub const STRICT_FAULTS: bool = cfg!(feature = "strict-faults");
491
492#[no_mangle]
494static mut __psx_rt_vblank_count: u32 = 0;
495
496pub const DEFAULT_MIN_FLIP_VBLANKS: u32 = 2;
499
500pub const FLIP_HISTOGRAM_BUCKETS: usize = 8;
504
505#[no_mangle]
508static mut __psx_rt_flip_min: u32 = DEFAULT_MIN_FLIP_VBLANKS;
509
510#[no_mangle]
513static mut __psx_rt_flip_hold: u32 = 0;
514
515#[no_mangle]
518static mut __psx_rt_flip_age: u32 = FLIP_AGE_UNKNOWN;
519
520#[no_mangle]
522static mut __psx_rt_flip_hist: [u32; FLIP_HISTOGRAM_BUCKETS] = [0; FLIP_HISTOGRAM_BUCKETS];
523
524const FLIP_AGE_UNKNOWN: u32 = FLIP_HISTOGRAM_BUCKETS as u32 - 1;
526
527#[no_mangle]
549static mut __psx_rt_fault_count: u32 = 0;
550
551#[no_mangle]
554static mut __psx_rt_gte_skip_count: u32 = 0;
555
556#[no_mangle]
558static mut __psx_rt_fault_cause: u32 = 0;
559
560#[no_mangle]
562static mut __psx_rt_fault_epc: u32 = 0;
563
564#[no_mangle]
568static mut __psx_rt_fault_badvaddr: u32 = 0;
569
570#[no_mangle]
574static mut __psx_rt_pending_gp1: u32 = 0;
575
576#[no_mangle]
579static mut __psx_rt_stray_irq_count: u32 = 0;
580
581#[no_mangle]
583static mut __psx_rt_stray_irq_last: u32 = 0;
584
585#[no_mangle]
588static mut __psx_rt_claimed_irq: u32 = 0;
589
590pub fn claim_interrupt_sources(bits: u32) {
603 psx_io::irq::without_interrupts(|| {
607 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
617pub fn release_interrupt_sources(bits: u32) {
619 psx_io::irq::without_interrupts(|| {
620 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
628pub fn claimed_interrupt_sources() -> u32 {
630 unsafe { core::ptr::read_volatile(&raw const __psx_rt_claimed_irq) }
632}
633
634#[inline]
640pub fn stray_interrupt_count() -> u32 {
641 unsafe { core::ptr::read_volatile(&raw const __psx_rt_stray_irq_count) }
644}
645
646#[inline]
649pub fn last_stray_interrupt_sources() -> u32 {
650 unsafe { core::ptr::read_volatile(&raw const __psx_rt_stray_irq_last) }
653}
654
655pub const fn stray_interrupt_sources(status: u32, mask: u32, cause: u32) -> u32 {
663 stray_unclaimed(status, mask, cause, 0)
664}
665
666pub 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#[cfg(target_arch = "mips")]
681static mut INSTALLED: bool = false;
682
683#[cfg(target_arch = "mips")]
686static mut BOOT_VECTOR_WORD: u32 = 0;
687
688#[cfg(target_arch = "mips")]
690static mut BOOT_VECTOR_RECORDED: bool = false;
691
692#[cfg(target_arch = "mips")]
695pub(crate) fn record_boot_vector() {
696 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#[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#[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 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 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 psx_io::gpu::set_flip_pacer(Some(pace_direct_flip));
769 irq::acknowledge(1 << psx_hw::irq::source::VBLANK);
770 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#[cfg(not(target_arch = "mips"))]
780pub fn install_vblank_counter() {}
781
782#[cfg(target_arch = "mips")]
787static mut VECTOR_EPOCH: u32 = 0;
788
789pub fn vector_epoch() -> u32 {
791 #[cfg(target_arch = "mips")]
792 unsafe {
794 core::ptr::read_volatile(&raw const VECTOR_EPOCH)
795 }
796 #[cfg(not(target_arch = "mips"))]
797 0
798}
799
800#[inline]
803pub fn fault_count() -> u32 {
804 unsafe { core::ptr::read_volatile(&raw const __psx_rt_fault_count) }
807}
808
809#[inline]
812pub fn gte_skip_count() -> u32 {
813 unsafe { core::ptr::read_volatile(&raw const __psx_rt_gte_skip_count) }
816}
817
818#[inline]
824pub const fn is_gte_command(word: u32) -> bool {
825 psx_hw::gte::is_command(word)
826}
827
828#[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
851pub const fn fault_resume_pc(cause: u32, epc: u32, badvaddr: u32) -> Option<u32> {
868 resume_after_fault(STRICT_FAULTS, cause, epc, badvaddr)
869}
870
871const 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 9 | 6 => return None,
879 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#[inline]
892#[doc(alias = "BadVAddr")]
893pub fn fault_bad_address() -> u32 {
894 unsafe { core::ptr::read_volatile(&raw const __psx_rt_fault_badvaddr) }
897}
898
899#[inline]
901pub fn fault_cause() -> u32 {
902 unsafe { core::ptr::read_volatile(&raw const __psx_rt_fault_cause) }
905}
906
907#[inline]
909#[doc(alias = "EPC")]
910pub fn fault_pc() -> u32 {
911 unsafe { core::ptr::read_volatile(&raw const __psx_rt_fault_epc) }
914}
915
916pub fn set_min_flip_vblanks(vblanks: u8) {
935 unsafe { core::ptr::write_volatile(&raw mut __psx_rt_flip_min, u32::from(vblanks.max(1))) }
938}
939
940#[must_use]
942pub fn min_flip_vblanks() -> u8 {
943 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#[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 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
968pub fn reset_flip_histogram() {
971 psx_io::irq::without_interrupts(|| {
972 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#[cfg(target_arch = "mips")]
990fn cpu_interrupts_enabled() -> bool {
991 let sr: u32;
992 unsafe { core::arch::asm!("mfc0 $8, $12", "nop", lateout("$8") sr) };
995 sr & 1 != 0
996}
997
998#[cfg(target_arch = "mips")]
1005fn pace_direct_flip() {
1006 let min = unsafe { core::ptr::read_volatile(&raw const __psx_rt_flip_min) };
1008 let running = unsafe { core::ptr::read_volatile(&raw const INSTALLED) };
1010 if min > 1 && running && cpu_interrupts_enabled() {
1011 crate::wait::wait_while(
1012 || unsafe { core::ptr::read_volatile(&raw const __psx_rt_flip_hold) } != 0,
1014 || false,
1015 || {},
1016 crate::wait::SPIN_LIMIT,
1017 );
1018 }
1019 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#[inline]
1033#[doc(alias = "VSync")]
1034pub fn vblank_count() -> u32 {
1035 unsafe { core::ptr::read_volatile(&raw const __psx_rt_vblank_count) }
1039}
1040
1041#[cfg(target_arch = "mips")]
1066#[inline]
1067#[doc(alias = "GP1")]
1068pub fn queue_display_control_at_vblank(word: u32) {
1069 unsafe { core::ptr::write_volatile(&raw mut __psx_rt_pending_gp1, word) }
1072}
1073
1074#[cfg(not(target_arch = "mips"))]
1076#[inline]
1077#[doc(alias = "GP1")]
1078pub fn queue_display_control_at_vblank(_word: u32) {}
1079
1080#[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#[cfg(target_arch = "mips")]
1090#[inline]
1091#[doc(alias = "GP1")]
1092pub fn is_display_control_queued() -> bool {
1093 unsafe { core::ptr::read_volatile(&raw const __psx_rt_pending_gp1) != 0 }
1096}
1097
1098#[cfg(target_arch = "mips")]
1112#[inline]
1113#[doc(alias = "GP1")]
1114pub fn take_queued_display_control() -> u32 {
1115 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#[cfg(not(target_arch = "mips"))]
1128#[inline]
1129#[doc(alias = "GP1")]
1130pub fn take_queued_display_control() -> u32 {
1131 0
1132}
1133
1134#[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#[cfg(not(target_arch = "mips"))]
1143#[inline]
1144#[doc(alias = "GP1")]
1145pub fn is_display_control_queued() -> bool {
1146 false
1147}
1148
1149#[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#[cfg(target_arch = "mips")]
1176#[doc(alias = "VSync")]
1177pub fn wait_vblank() {
1178 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#[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#[cfg(not(target_arch = "mips"))]
1213#[doc(alias = "VSync")]
1214pub fn wait_vblank() {}
1215
1216#[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#[cfg(target_arch = "mips")]
1227static mut STACK_SAFE_HANDLER: u32 = 0;
1228
1229#[cfg(target_arch = "mips")]
1257pub unsafe fn declare_stack_safe_handler(handler: unsafe extern "C" fn()) {
1258 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#[cfg(not(target_arch = "mips"))]
1274pub unsafe fn declare_stack_safe_handler(_handler: unsafe extern "C" fn()) {}
1275
1276#[cfg(target_arch = "mips")]
1279pub fn is_stack_safe_handler_installed() -> bool {
1280 let declared = unsafe { core::ptr::read_volatile(&raw const STACK_SAFE_HANDLER) };
1282 is_handler_installed() || (declared != 0 && vector_word() == declared)
1283}
1284
1285#[cfg(target_arch = "mips")]
1287fn jump_word(handler: u32) -> u32 {
1288 0x0800_0000 | ((handler >> 2) & 0x03ff_ffff)
1289}
1290
1291#[cfg(target_arch = "mips")]
1293fn vector_word() -> u32 {
1294 const EXCEPTION_VECTOR: *const u32 = 0x8000_0080 as *const u32;
1295 unsafe { core::ptr::read_volatile(EXCEPTION_VECTOR) }
1297}
1298
1299#[cfg(target_arch = "mips")]
1301pub fn are_interrupts_enabled() -> bool {
1302 let sr: u32;
1303 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 unsafe { core::arch::asm!("mfc0 $8, $12", "nop", lateout("$8") sr) };
1324 sr |= STATUS_IE | STATUS_IM2 | STATUS_CU2;
1325 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 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 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, 0x4889_6000, 0x4842_f800, 0x48c2_c000, 0xc885_0000, 0xe8ac_0000, 0x4900_0003, 0x4901_0003, 0x4080_6000, 0x0000_0000, 0x8c82_0000, 0x03e0_0008, ];
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 let branches = [
1399 0x1509_fff0, 0x1000_0004, 0x0c00_4000, 0x0800_4000, 0x0100_f809, 0x03e0_0008, ];
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 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 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 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 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 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 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 assert!(may_install_lazily(Some(BIOS_STUB), BIOS_STUB, RT_JUMP));
1501 assert!(may_install_lazily(Some(BIOS_STUB), RT_JUMP, RT_JUMP));
1502 assert!(!may_install_lazily(Some(BIOS_STUB), GAME_JUMP, RT_JUMP));
1504 assert!(may_install_lazily(Some(GAME_JUMP), GAME_JUMP, RT_JUMP));
1506 assert!(may_install_lazily(None, GAME_JUMP, RT_JUMP));
1508 }
1509
1510 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 assert_eq!(
1520 stray_interrupt_sources(CDROM_BIT, VBLANK_BIT | CDROM_BIT, INTERRUPT),
1521 CDROM_BIT
1522 );
1523 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 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 let mask = VBLANK_BIT | CDROM_BIT | GPU_BIT;
1550 assert_eq!(stray_unclaimed(CDROM_BIT, mask, INTERRUPT, CDROM_BIT), 0);
1551 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 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 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}