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

psx_rt/
diag.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2//! Console stop-panel: what a program was doing when it stopped, on screen.
3//!
4//! Built only with the `console-diag` feature, for diagnostic discs; a
5//! shipping image does not contain any of it. Three things bring the panel up:
6//!
7//! * a **fault**: the exception handler reached its halt (a `BREAK` from
8//!   `panic=immediate-abort`, an instruction-side fault, a fault in a delay
9//!   slot);
10//! * a **panic** with a message (builds without `panic=immediate-abort`);
11//! * a **stall**: the VBlank handler saw no sign of life for [`STALL_VBLANKS`]
12//!   frames (no GP1 write, no GPU DMA kick, no CD sector or command), which is
13//!   how a bounded or unbounded wait that never ends looks.
14//!
15//! The panel takes over the display (it resets the GPU and shows its own
16//! 320x240 screen), then prints the program counter, return address and stack
17//! of the interrupted code, a guess at the call chain, the GPU, DMA and
18//! interrupt registers, the SDK's wait and CD counters ([`psx_io::diag`]) and
19//! any panic message, and keeps refreshing the frame counters so a photo shows
20//! the machine is alive but the program is not.
21//!
22//! Resolve the printed addresses against the link map of the same build.
23
24use core::arch::global_asm;
25use psx_hw::dma::{channel, CHANNEL_BASE, CHANNEL_STRIDE, CHCR, DPCR, MADR};
26use psx_hw::gpu::{GP0, GP1};
27use psx_hw::irq::{I_MASK, I_STAT};
28use psx_io::diag::{self, Block, PSX_DIAG};
29
30/// VBlanks without progress before the stall panel appears (15 seconds at 60 Hz).
31pub const STALL_VBLANKS: u32 = 900;
32
33/// The limit in force: [`STALL_VBLANKS`] unless [`set_stall_limit`] changed it.
34static mut STALL_LIMIT: u32 = STALL_VBLANKS;
35
36/// Change how many VBlanks without progress bring the stall panel up. A program
37/// with long steps that are legitimately silent (no GP1 write, GPU DMA kick or
38/// CD command for tens of seconds) raises it so the panel does not take the
39/// screen in the middle of a measurement; faults and panics are unaffected.
40pub fn set_stall_limit(vblanks: u32) {
41    // SAFETY: a plain word written before or between VBlanks on one thread; the
42    // watchdog only reads it.
43    unsafe { (&raw mut STALL_LIMIT).write_volatile(vblanks) };
44}
45
46const COLS: usize = 53;
47const ROWS: usize = 28;
48
49const BG: u16 = 0x1000;
50const WHITE: u16 = 0x7fff;
51const YELLOW: u16 = 0x03ff;
52const GREEN: u16 = 0x03e0;
53const RED: u16 = 0x001f;
54const CYAN: u16 = 0x7fe0;
55
56/// Saved registers of the interrupted code: index = register number, then HI, LO.
57#[no_mangle]
58static mut __psx_diag_regs: [u32; 40] = [0; 40];
59
60/// The cache control register as the fault found it, saved by the fault trampoline before it
61/// restores the running setting.
62#[no_mangle]
63static mut __psx_diag_fault_cc: u32 = 0;
64
65/// Set by the exception handler when a fault arrived with the cache isolated (the isolate bit of SR): the fault
66/// happened inside an instruction-cache flush. The handler clears the bit first, so its own loads
67/// and stores reach RAM and the panel can be drawn.
68#[no_mangle]
69static mut __psx_diag_isc_hit: u32 = 0;
70
71/// Stack the panel runs on, so it works however the program's own stack looks.
72#[no_mangle]
73static mut __psx_diag_stack: [u32; 256] = [0; 256];
74
75#[repr(C)]
76struct Watch {
77    last_sig: u32,
78    quiet: u32,
79    shown: u32,
80    frame: u32,
81}
82
83static mut WATCH: Watch = Watch {
84    last_sig: 0,
85    quiet: 0,
86    shown: 0,
87    frame: 0,
88};
89
90/// Panic text recorded by [`record_panic`].
91static mut PANIC_MSG: [u8; 120] = [0; 120];
92static mut PANIC_FILE: [u8; 48] = [0; 48];
93static mut PANIC_LINE: u32 = 0;
94static mut PANIC_SET: u32 = 0;
95
96/// Optional tag the build names itself with (`PSX_DIAG_TAG` at compile time).
97const TAG: &str = match option_env!("PSX_DIAG_TAG") {
98    Some(tag) => tag,
99    None => "",
100};
101
102// Save every register to `__psx_diag_regs` through $27, then switch to the panel stack.
103global_asm!(
104    r#"
105    .macro PSX_DIAG_SAVE
106    .set push
107    .set noat
108    lui   $27, %hi(__psx_diag_regs)
109    addiu $27, $27, %lo(__psx_diag_regs)
110    sw    $26, 136($27)
111    sw    $1,   4($27)
112    sw    $2,   8($27)
113    sw    $3,  12($27)
114    sw    $4,  16($27)
115    sw    $5,  20($27)
116    sw    $6,  24($27)
117    sw    $7,  28($27)
118    sw    $8,  32($27)
119    sw    $9,  36($27)
120    sw    $10, 40($27)
121    sw    $11, 44($27)
122    sw    $12, 48($27)
123    sw    $13, 52($27)
124    sw    $14, 56($27)
125    sw    $15, 60($27)
126    sw    $16, 64($27)
127    sw    $17, 68($27)
128    sw    $18, 72($27)
129    sw    $19, 76($27)
130    sw    $20, 80($27)
131    sw    $21, 84($27)
132    sw    $22, 88($27)
133    sw    $23, 92($27)
134    sw    $24, 96($27)
135    sw    $25, 100($27)
136    sw    $28, 112($27)
137    sw    $29, 116($27)
138    sw    $30, 120($27)
139    sw    $31, 124($27)
140    mfhi  $26
141    nop
142    sw    $26, 128($27)
143    mflo  $26
144    nop
145    sw    $26, 132($27)
146    # Run on the interrupted code's own stack, just below its stack pointer, when that is
147    # ordinary RAM; the fallback is the small static stack (a scratchpad stack, a wild $sp).
148    lw    $2, 116($27)
149    lui   $3, 0x8001
150    ori   $3, $3, 0x1000
151    sltu  $4, $2, $3
152    bnez  $4, 8f
153    nop
154    lui   $3, 0x8020
155    sltu  $4, $2, $3
156    beqz  $4, 8f
157    nop
158    andi  $4, $2, 3
159    bnez  $4, 8f
160    nop
161    addiu $29, $2, -256
162    b     9f
163    nop
1648:
165    lui   $29, %hi(__psx_diag_stack + 1008)
166    addiu $29, $29, %lo(__psx_diag_stack + 1008)
1679:
168    move  $4, $27
169    mfc0  $5, $14
170    nop
171    .set pop
172    .endm
173
174    .macro PSX_DIAG_RESTORE
175    .set push
176    .set noat
177    lui   $27, %hi(__psx_diag_regs)
178    addiu $27, $27, %lo(__psx_diag_regs)
179    lw    $26, 128($27)
180    nop
181    mthi  $26
182    lw    $26, 132($27)
183    nop
184    mtlo  $26
185    lw    $1,   4($27)
186    lw    $2,   8($27)
187    lw    $3,  12($27)
188    lw    $4,  16($27)
189    lw    $5,  20($27)
190    lw    $6,  24($27)
191    lw    $7,  28($27)
192    lw    $8,  32($27)
193    lw    $9,  36($27)
194    lw    $10, 40($27)
195    lw    $11, 44($27)
196    lw    $12, 48($27)
197    lw    $13, 52($27)
198    lw    $14, 56($27)
199    lw    $15, 60($27)
200    lw    $16, 64($27)
201    lw    $17, 68($27)
202    lw    $18, 72($27)
203    lw    $19, 76($27)
204    lw    $20, 80($27)
205    lw    $21, 84($27)
206    lw    $22, 88($27)
207    lw    $23, 92($27)
208    lw    $24, 96($27)
209    lw    $25, 100($27)
210    lw    $28, 112($27)
211    lw    $29, 116($27)
212    lw    $30, 120($27)
213    lw    $31, 124($27)
214    lw    $26, 136($27)
215    nop
216    jr    $26
217    nop
218    .set pop
219    .endm
220
221    # Called from the exception handler's VBlank path with every register still the
222    # interrupted code's (the handler has used only $26 and $27). Runs the Rust
223    # watchdog on the panel stack, then puts everything back.
224    .set noreorder
225    .section .text.psx_diag_tramp
226    .globl __psx_diag_vblank_tramp
227__psx_diag_vblank_tramp:
228    PSX_DIAG_SAVE
229    jal   __psx_diag_tick
230    nop
231    PSX_DIAG_RESTORE
232
233    # The fatal-fault halt: never returns. First thing, before any other store: note the cache
234    # control register as the fault found it and put the running setting back. A fault inside an
235    # instruction-cache flush leaves it in the flush setting (bus grant and read priority off),
236    # which with a DMA live is how the CPU can fetch the DMA's words; the panel's own code must
237    # not run like that. Uses $26 and $27 only, as the handler does. The exception handler has
238    # already cleared the isolate bit of SR.
239    .globl __psx_diag_fault_tramp
240__psx_diag_fault_tramp:
241    lui   $26, {cc_hi}
242    lw    $27, {cc_lo}($26)
243    nop
244    lui   $26, %hi(__psx_diag_fault_cc)
245    sw    $27, %lo(__psx_diag_fault_cc)($26)
246    lui   $26, {cc_hi}
247    lui   $27, {run_hi}
248    ori   $27, $27, {run_lo}
249    sw    $27, {cc_lo}($26)
250    PSX_DIAG_SAVE
251    jal   __psx_diag_fault
252    nop
2531:  b     1b
254    nop
255
256    .set reorder
257    "#,
258    cc_hi = const crate::cache::CONTROL_ADDRESS >> 16,
259    cc_lo = const crate::cache::CONTROL_ADDRESS & 0xFFFF,
260    run_hi = const crate::cache::RUNNING_SETTING >> 16,
261    run_lo = const crate::cache::RUNNING_SETTING & 0xFFFF,
262);
263
264// ---------------------------------------------------------------- text
265
266/// One text line under construction.
267struct Line {
268    buf: [u8; COLS],
269    len: usize,
270}
271
272impl Line {
273    const fn new() -> Self {
274        Line {
275            buf: [b' '; COLS],
276            len: 0,
277        }
278    }
279
280    #[inline(never)]
281    fn str(&mut self, s: &str) -> &mut Self {
282        for &b in s.as_bytes() {
283            self.byte(b);
284        }
285        self
286    }
287
288    #[inline(never)]
289    fn byte(&mut self, b: u8) {
290        if self.len < COLS {
291            self.buf[self.len] = b;
292            self.len += 1;
293        }
294    }
295
296    #[inline(never)]
297    fn hex(&mut self, v: u32, digits: usize) -> &mut Self {
298        let mut i = digits;
299        while i > 0 {
300            i -= 1;
301            let n = ((v >> (i * 4)) & 15) as u8;
302            self.byte(if n < 10 { b'0' + n } else { b'A' + n - 10 });
303        }
304        self
305    }
306
307    #[inline(never)]
308    fn dec(&mut self, mut v: u32) -> &mut Self {
309        let mut tmp = [0u8; 10];
310        let mut n = 0;
311        if v == 0 {
312            tmp[0] = b'0';
313            n = 1;
314        }
315        while v > 0 {
316            tmp[n] = b'0' + (v % 10) as u8;
317            v /= 10;
318            n += 1;
319        }
320        while n > 0 {
321            n -= 1;
322            self.byte(tmp[n]);
323        }
324        self
325    }
326
327    #[inline(never)]
328    fn sp(&mut self) -> &mut Self {
329        self.byte(b' ');
330        self
331    }
332}
333
334/// The 5x7 glyph for an ASCII byte (lower case folds to upper), one byte a row,
335/// bit 4 the left pixel. Drawn by this crate; it covers `' '..='_'`.
336#[optimize(size)]
337#[inline(never)]
338fn glyph(c: u8) -> [u8; 7] {
339    let c = if c.is_ascii_lowercase() { c - 32 } else { c };
340    if !(32..=95).contains(&c) {
341        return [31, 17, 17, 17, 17, 17, 31];
342    }
343    FONT[(c - 32) as usize]
344}
345
346const FONT: [[u8; 7]; 64] = [
347    [0, 0, 0, 0, 0, 0, 0],
348    [4, 4, 4, 4, 4, 0, 4],
349    [10, 10, 0, 0, 0, 0, 0],
350    [10, 10, 31, 10, 31, 10, 10],
351    [4, 15, 20, 14, 5, 30, 4],
352    [24, 25, 2, 4, 8, 19, 3],
353    [12, 18, 20, 8, 21, 18, 13],
354    [4, 4, 0, 0, 0, 0, 0],
355    [2, 4, 8, 8, 8, 4, 2],
356    [8, 4, 2, 2, 2, 4, 8],
357    [0, 4, 21, 14, 21, 4, 0],
358    [0, 4, 4, 31, 4, 4, 0],
359    [0, 0, 0, 0, 12, 4, 8],
360    [0, 0, 0, 31, 0, 0, 0],
361    [0, 0, 0, 0, 0, 12, 12],
362    [1, 1, 2, 4, 8, 16, 16],
363    [14, 17, 19, 21, 25, 17, 14],
364    [4, 12, 4, 4, 4, 4, 14],
365    [14, 17, 1, 2, 4, 8, 31],
366    [31, 2, 4, 2, 1, 17, 14],
367    [2, 6, 10, 18, 31, 2, 2],
368    [31, 16, 30, 1, 1, 17, 14],
369    [6, 8, 16, 30, 17, 17, 14],
370    [31, 1, 2, 4, 8, 8, 8],
371    [14, 17, 17, 14, 17, 17, 14],
372    [14, 17, 17, 15, 1, 2, 12],
373    [0, 12, 12, 0, 12, 12, 0],
374    [0, 12, 12, 0, 12, 4, 8],
375    [2, 4, 8, 16, 8, 4, 2],
376    [0, 0, 31, 0, 31, 0, 0],
377    [8, 4, 2, 1, 2, 4, 8],
378    [14, 17, 1, 2, 4, 0, 4],
379    [14, 17, 23, 21, 23, 16, 14],
380    [14, 17, 17, 31, 17, 17, 17],
381    [30, 17, 17, 30, 17, 17, 30],
382    [14, 17, 16, 16, 16, 17, 14],
383    [30, 17, 17, 17, 17, 17, 30],
384    [31, 16, 16, 30, 16, 16, 31],
385    [31, 16, 16, 30, 16, 16, 16],
386    [14, 17, 16, 23, 17, 17, 15],
387    [17, 17, 17, 31, 17, 17, 17],
388    [14, 4, 4, 4, 4, 4, 14],
389    [7, 2, 2, 2, 2, 18, 12],
390    [17, 18, 20, 24, 20, 18, 17],
391    [16, 16, 16, 16, 16, 16, 31],
392    [17, 27, 21, 21, 17, 17, 17],
393    [17, 17, 25, 21, 19, 17, 17],
394    [14, 17, 17, 17, 17, 17, 14],
395    [30, 17, 17, 30, 16, 16, 16],
396    [14, 17, 17, 17, 21, 18, 13],
397    [30, 17, 17, 30, 20, 18, 17],
398    [15, 16, 16, 14, 1, 1, 30],
399    [31, 4, 4, 4, 4, 4, 4],
400    [17, 17, 17, 17, 17, 17, 14],
401    [17, 17, 17, 17, 17, 10, 4],
402    [17, 17, 17, 21, 21, 27, 17],
403    [17, 17, 10, 4, 10, 17, 17],
404    [17, 17, 10, 4, 4, 4, 4],
405    [31, 1, 2, 4, 8, 16, 31],
406    [14, 8, 8, 8, 8, 8, 14],
407    [16, 16, 8, 4, 2, 1, 1],
408    [14, 2, 2, 2, 2, 2, 14],
409    [4, 10, 17, 0, 0, 0, 0],
410    [0, 0, 0, 0, 0, 0, 31],
411];
412
413// ---------------------------------------------------------------- GPU
414
415/// Register `offset` (`MADR`, `CHCR`) of DMA channel `ch`.
416const fn dma_reg(ch: u32, offset: u32) -> u32 {
417    CHANNEL_BASE + CHANNEL_STRIDE * ch + offset
418}
419
420fn rd(addr: u32) -> u32 {
421    // SAFETY: an aligned 32-bit read of a PS1 register or RAM word, as the caller intends.
422    unsafe { psx_io::read_u32(addr) }
423}
424
425fn wr(addr: u32, value: u32) {
426    // SAFETY: an aligned 32-bit write to a PS1 register.
427    unsafe { psx_io::write_u32(addr, value) }
428}
429
430fn gpu_ready() {
431    let mut n = 0u32;
432    while rd(GP1) & (1 << 26) == 0 && n < 200_000 {
433        n += 1;
434    }
435}
436
437/// Make the screen ours: stop the GPU DMA, reset the GPU, show 320x240 15-bit
438/// at the top of VRAM and clear it.
439#[optimize(size)]
440#[inline(never)]
441fn take_screen() {
442    // Channel 2 (GPU): drop START so nothing keeps feeding the GPU.
443    wr(dma_reg(channel::GPU, CHCR), 0);
444    wr(GP1, 0x0000_0000); // reset
445    wr(GP1, 0x0400_0000); // DMA off
446    wr(GP1, 0x0500_0000); // display start 0,0
447    wr(GP1, 0x06c6_0260); // horizontal range for 320
448    wr(GP1, 0x0704_0010); // vertical range, NTSC
449    wr(GP1, 0x0800_0001); // 320x240, NTSC, 15 bit
450    wr(GP1, 0x0300_0000); // display on
451    gpu_ready();
452    wr(GP0, 0xe100_0000);
453    wr(GP0, 0xe300_0000);
454    wr(GP0, 0xe403_bd3f);
455    wr(GP0, 0xe500_0000);
456    wr(GP0, 0x0220_0000); // fill, dark blue
457    wr(GP0, 0x0000_0000);
458    wr(GP0, (240 << 16) | 320);
459    gpu_ready();
460}
461
462/// Draw one 8-pixel-tall text row at VRAM row `y`, a pixel row at a time, computing each pair
463/// of pixels as it is written so no buffer is needed (the panel may run on a 1 KB stack).
464#[optimize(size)]
465fn draw_line(y: u16, line: &Line, color: u16) {
466    let mut row = 0usize;
467    while row < 8 {
468        gpu_ready();
469        wr(GP0, 0xa000_0000);
470        wr(GP0, (y as u32 + row as u32) << 16);
471        wr(GP0, (1 << 16) | 320);
472        let mut x = 0usize;
473        while x < 320 {
474            let mut pair = 0u32;
475            let mut k = 0;
476            while k < 2 {
477                let xx = x + k;
478                let col = xx / 6;
479                let px = xx % 6;
480                let on = col < COLS
481                    && px < 5
482                    && row < 7
483                    && glyph(line.buf[col])[row] & (1 << (4 - px)) != 0;
484                let c = if on { color } else { BG } as u32;
485                pair |= c << (16 * k);
486                k += 1;
487            }
488            wr(GP0, pair);
489            x += 2;
490        }
491        row += 1;
492    }
493}
494
495// ---------------------------------------------------------------- panel
496
497#[derive(Clone, Copy, PartialEq, Eq)]
498enum Reason {
499    Stall,
500    Fault,
501    Panic,
502}
503
504/// Boot-menu helper for diagnostic discs: reset the GPU (nothing may be in flight) and show a
505/// clear 320x240 screen for [`menu_entry`] and [`menu_countdown`]. Call it before the first
506/// entry, with no DMA running.
507pub fn menu_screen() {
508    take_screen();
509}
510
511/// Draw a menu line of 53 columns on row `row`: `marker`, a space, `letter`, two spaces, then
512/// `title`. `color` 0 white, 1 yellow, 2 green, 3 red, 4 cyan. A `letter` of 0 draws `title`
513/// alone. Polled GP0 fills only, so it works before any driver is set up.
514#[inline(never)]
515pub fn menu_entry(row: usize, color: u8, marker: u8, letter: u8, title: &str) {
516    let mut l = Line::new();
517    if letter != 0 {
518        l.byte(marker);
519        l.sp();
520        l.byte(letter);
521        l.sp().sp();
522    }
523    l.str(title);
524    let c = match color {
525        1 => YELLOW,
526        2 => GREEN,
527        3 => RED,
528        4 => CYAN,
529        _ => WHITE,
530    };
531    draw_line((row * 8 + 16) as u16, &l, c);
532}
533
534/// Draw `AUTO START IN nn S` on menu row `row`.
535#[inline(never)]
536pub fn menu_countdown(row: usize, seconds: u32) {
537    let mut l = Line::new();
538    l.str("AUTO START IN ").dec(seconds).str(" S ");
539    draw_line((row * 8 + 16) as u16, &l, GREEN);
540}
541
542#[inline(never)]
543fn is_return_address(w: u32) -> bool {
544    if !(0x8001_0000..0x8020_0000).contains(&w) || w & 3 != 0 {
545        return false;
546    }
547    let call = rd(w - 8);
548    // JAL, or JALR (SPECIAL, function 9).
549    call >> 26 == 3 || (call >> 26 == 0 && call & 0x3f == 9)
550}
551
552#[optimize(size)]
553#[inline(never)]
554fn put_line(row: &mut usize, line: &Line, color: u16) {
555    if *row < ROWS {
556        draw_line((*row * 8 + 16) as u16, line, color);
557        *row += 1;
558    }
559}
560
561#[optimize(size)]
562#[inline(never)]
563fn panel(reason: Reason, regs: *const u32, epc: u32) {
564    // SAFETY: `regs` is the register save area filled by the trampoline.
565    let reg = |n: usize| unsafe { regs.add(n).read_volatile() };
566    let b: *const Block = &raw const PSX_DIAG;
567    // SAFETY: every caller passes a field pointer into the diagnostics static.
568    let d = |f: *const u32| unsafe { diag::get(f) };
569    macro_rules! f {
570        ($name:ident) => {
571            // SAFETY: a field pointer into the diagnostics static.
572            d(unsafe { &raw const (*b).$name })
573        };
574    }
575    // SAFETY: the panel runs with interrupts off on one thread; nothing else touches WATCH.
576    let frame = unsafe {
577        let w = &raw mut WATCH;
578        (*w).frame = (*w).frame.wrapping_add(1);
579        (*w).frame
580    };
581    // SAFETY: as above.
582    let quiet = unsafe { (&raw const WATCH.quiet).read_volatile() };
583
584    let mut row = 0usize;
585    let mut l = Line::new();
586    l.str("PSXDIAG ")
587        .str(match reason {
588            Reason::Stall => "STALL NO PROGRESS",
589            Reason::Fault => "FAULT HALT",
590            Reason::Panic => "PANIC",
591        })
592        .sp()
593        .str(TAG);
594    put_line(
595        &mut row,
596        &l,
597        if reason == Reason::Stall { YELLOW } else { RED },
598    );
599
600    let mut l = Line::new();
601    l.str("VBL ")
602        .hex(crate::interrupts::vblank_count(), 8)
603        .str(" FRM ")
604        .dec(frame)
605        .str(" QUIET ")
606        .dec(quiet)
607        .str(" BASE ")
608        .dec(psx_io::disc_base::lba_offset());
609    put_line(&mut row, &l, WHITE);
610
611    let mut l = Line::new();
612    l.str("STEP ").dec(f!(step_id)).sp();
613    // SAFETY: a byte array in the static, read volatile.
614    let text = unsafe { (&raw const (*b).step_text).cast::<u8>() };
615    let mut i = 0;
616    while i < 24 {
617        // SAFETY: `i` < 24, inside `step_text`.
618        let c = unsafe { text.add(i).read_volatile() };
619        if c == 0 {
620            break;
621        }
622        l.byte(c);
623        i += 1;
624    }
625    put_line(&mut row, &l, CYAN);
626
627    let mut l = Line::new();
628    l.str("PC ")
629        .hex(epc, 8)
630        .str(" RA ")
631        .hex(reg(31), 8)
632        .str(" SP ")
633        .hex(reg(29), 8);
634    put_line(&mut row, &l, GREEN);
635
636    let mut l = Line::new();
637    l.str("A0 ")
638        .hex(reg(4), 8)
639        .str(" A1 ")
640        .hex(reg(5), 8)
641        .str(" V0 ")
642        .hex(reg(2), 8);
643    put_line(&mut row, &l, WHITE);
644
645    let mut l = Line::new();
646    l.str("FAULTS ")
647        .dec(crate::interrupts::fault_count())
648        .str(" CAUSE ")
649        .hex(crate::interrupts::fault_cause(), 8)
650        .str(" EPC ")
651        .hex(crate::interrupts::fault_pc(), 8);
652    put_line(
653        &mut row,
654        &l,
655        if reason == Reason::Fault { RED } else { WHITE },
656    );
657    let mut l = Line::new();
658    l.str("BADVADDR ")
659        .hex(crate::interrupts::fault_bad_address(), 8)
660        .str(" STRAY IRQ ")
661        .dec(crate::interrupts::stray_interrupt_count());
662    put_line(&mut row, &l, WHITE);
663
664    // A program counter outside any code: say what the word that sent it there would be as a
665    // jump, and where the GPU's DMA was reading. A GPU list header with this value means the
666    // instruction fetch received a word of the DMA's traffic.
667    let dma2_madr = rd(dma_reg(channel::GPU, MADR));
668    if reason == Reason::Fault && diag::is_wild_pc(epc) {
669        let mut l = Line::new();
670        l.str("WILD PC ")
671            .hex(epc, 8)
672            .str(" J ")
673            .hex(diag::jump_word_for(epc), 8)
674            .str(" MADR ")
675            .hex(dma2_madr, 8);
676        put_line(&mut row, &l, RED);
677    }
678
679    // A guess at the call chain: words on the stack that follow a call.
680    let sp = reg(29);
681    let mut l = Line::new();
682    l.str("CALLERS");
683    put_line(&mut row, &l, CYAN);
684    let mut l = Line::new();
685    let mut found = 0;
686    if (0x8000_0000..0x801f_ff00).contains(&sp) && sp & 3 == 0 {
687        let mut at = sp;
688        let end = (sp + 1024).min(0x8020_0000 - 8);
689        while at < end && found < 12 {
690            let w = rd(at);
691            if is_return_address(w) {
692                l.hex(w, 8).sp();
693                found += 1;
694                if found % 5 == 0 {
695                    put_line(&mut row, &l, WHITE);
696                    l = Line::new();
697                }
698            }
699            at += 4;
700        }
701    }
702    put_line(&mut row, &l, WHITE);
703
704    let mut l = Line::new();
705    l.str("GPUSTAT ")
706        .hex(rd(GP1), 8)
707        .str(" ISTAT ")
708        .hex(rd(I_STAT), 4)
709        .str(" IMASK ")
710        .hex(rd(I_MASK), 4);
711    put_line(&mut row, &l, WHITE);
712    let mut l = Line::new();
713    l.str("DMA2 CHCR ")
714        .hex(rd(dma_reg(channel::GPU, CHCR)), 8)
715        .str(" MADR ")
716        .hex(rd(dma_reg(channel::GPU, MADR)), 8)
717        .str(" DPCR ")
718        .hex(rd(DPCR), 8);
719    put_line(&mut row, &l, WHITE);
720    let mut l = Line::new();
721    l.str("DMA3 CHCR ")
722        .hex(rd(dma_reg(channel::CD, CHCR)), 8)
723        .str(" MADR ")
724        .hex(rd(dma_reg(channel::CD, MADR)), 8)
725        .str(" DMA4 ")
726        .hex(rd(dma_reg(channel::SPU, CHCR)), 8);
727    put_line(&mut row, &l, WHITE);
728
729    let mut l = Line::new();
730    l.str("KICKS");
731    // SAFETY: a field pointer into the diagnostics static.
732    let kicks = unsafe { (&raw const (*b).dma_kicks).cast::<u32>() };
733    let mut ch = 0;
734    while ch < 7 {
735        // SAFETY: `ch` < 7, inside `dma_kicks`.
736        l.sp().dec(d(unsafe { kicks.add(ch) }));
737        ch += 1;
738    }
739    put_line(&mut row, &l, WHITE);
740
741    let mut l = Line::new();
742    l.str("GP1 ")
743        .dec(f!(gp1_writes))
744        .str(" GPURESET ")
745        .dec(psx_io::gpu::command_reset_count())
746        .str(" GPUWAITFAIL ")
747        .dec(f!(gpu_wait_fail));
748    put_line(&mut row, &l, WHITE);
749    let mut l = Line::new();
750    l.str("DMAWAITFAIL ")
751        .dec(f!(dma_wait_fail))
752        .str(" CH ")
753        .dec(f!(dma_wait_ch));
754    put_line(&mut row, &l, WHITE);
755
756    let mut l = Line::new();
757    l.str("WAIT NOW ")
758        .hex(f!(wait_cur), 4)
759        .str(" LAST ")
760        .hex(f!(wait_last), 4)
761        .str(" SPINS ")
762        .dec(f!(wait_last_spins))
763        .str(" TMO ")
764        .dec(f!(wait_timeouts));
765    let now = f!(wait_cur);
766    put_line(&mut row, &l, if now != 0 { YELLOW } else { WHITE });
767
768    // The CD status register: reading index 0 has no side effect.
769    // SAFETY: an aligned byte read of the CD status register, which has no side effect.
770    let cd_status = unsafe { psx_io::read_u8(psx_hw::cd::BASE) };
771    let mut l = Line::new();
772    l.str("CD STAT ")
773        .hex(cd_status as u32, 2)
774        .str(" CMD ")
775        .hex(f!(cd_cmd), 2)
776        .str(" N ")
777        .dec(f!(cd_cmds))
778        .str(" IRQ ")
779        .hex(f!(cd_irq_seen), 2)
780        .str("/")
781        .hex(f!(cd_irq_acked), 2);
782    put_line(&mut row, &l, WHITE);
783    let mut l = Line::new();
784    l.str("CD INT5 ")
785        .dec(f!(cd_int5))
786        .str(" ST ")
787        .hex(f!(cd_int5_status), 2)
788        .str(" ERR ")
789        .hex(f!(cd_int5_code), 2)
790        .str(" TMO ")
791        .dec(f!(cd_timeouts))
792        .str(" ")
793        .hex(f!(cd_timeout_info), 8);
794    put_line(
795        &mut row,
796        &l,
797        if f!(cd_int5) + f!(cd_timeouts) != 0 {
798            YELLOW
799        } else {
800            WHITE
801        },
802    );
803    let mut l = Line::new();
804    l.str("CD SEC ")
805        .dec(f!(cd_sectors))
806        .str(" STARTS ")
807        .dec(f!(cd_starts))
808        .str(" LBA ")
809        .dec(f!(cd_lba))
810        .str(" FAIL ")
811        .dec(f!(cd_read_fail))
812        .str(" ")
813        .hex(f!(cd_fail_word), 8);
814    put_line(
815        &mut row,
816        &l,
817        if f!(cd_read_fail) != 0 { YELLOW } else { WHITE },
818    );
819
820    let mut l = Line::new();
821    l.str("LL SCANS ")
822        .dec(f!(ll_scans))
823        .str(" NODES ")
824        .dec(f!(ll_nodes))
825        .str(" BAD ")
826        .dec(f!(ll_bad))
827        .str(" MAX ")
828        .dec(f!(ll_max))
829        .str(" AT ")
830        .hex(f!(ll_bad_addr), 6);
831    put_line(&mut row, &l, if f!(ll_bad) != 0 { RED } else { WHITE });
832
833    if f!(flushes) != 0 {
834        let mut l = Line::new();
835        l.str("FLUSH N ")
836            .dec(f!(flushes))
837            .str(" WAIT ")
838            .dec(f!(flush_waits))
839            .str(" RETRY ")
840            .dec(f!(flush_retries))
841            .str(" TMO ")
842            .dec(f!(flush_timeouts))
843            .str(" SPIN ")
844            .dec(f!(flush_max_spins));
845        put_line(
846            &mut row,
847            &l,
848            if f!(flush_timeouts) != 0 { RED } else { WHITE },
849        );
850        if reason == Reason::Fault {
851            let mut l = Line::new();
852            l.str("ENTRY CC ")
853                .hex(f!(flush_cc), 8)
854                .str(" SR ")
855                .hex(f!(flush_sr), 8)
856                .str(" GS ")
857                .hex(f!(flush_gpustat), 8);
858            put_line(&mut row, &l, WHITE);
859            // SAFETY: a field pointer into the diagnostics static.
860            let chcr = unsafe { (&raw const (*b).flush_chcr).cast::<u32>() };
861            let mut busy = 0u32;
862            let mut ch = 0;
863            while ch < 7 {
864                // SAFETY: `ch` < 7, inside `flush_chcr`.
865                if d(unsafe { chcr.add(ch) }) & (1 << 24) != 0 {
866                    busy |= 1 << ch;
867                }
868                ch += 1;
869            }
870            let mut l = Line::new();
871            // SAFETY: plain reads of this module's statics, written before the panel runs.
872            let (fault_cc, isc) = unsafe {
873                (
874                    (&raw const __psx_diag_fault_cc).read_volatile(),
875                    (&raw const __psx_diag_isc_hit).read_volatile(),
876                )
877            };
878            l.str("ENTRY BUSY ")
879                .hex(busy, 2)
880                .str(" CHCR2 ")
881                // SAFETY: index 2 of 7, inside `flush_chcr`.
882                .hex(d(unsafe { chcr.add(2) }), 8)
883                .str(" FAULT CC ")
884                .hex(fault_cc, 8)
885                .str(" ISC ")
886                .hex(isc, 1);
887            put_line(&mut row, &l, if isc != 0 { RED } else { WHITE });
888        }
889    }
890
891    let mut l = Line::new();
892    l.str("PRESENT KICK ")
893        .dec(crate::interrupts::present_kick_count())
894        .str(" SKIP ")
895        .dec(crate::interrupts::present_skip_count());
896    put_line(&mut row, &l, WHITE);
897
898    // SAFETY: panic records are written once before the panel and only read here.
899    if unsafe { (&raw const PANIC_SET).read_volatile() } != 0 {
900        let mut l = Line::new();
901        let file = (&raw const PANIC_FILE).cast::<u8>();
902        let mut i = 0;
903        while i < 48 {
904            // SAFETY: `i` < 48, inside the buffer.
905            let c = unsafe { file.add(i).read_volatile() };
906            if c == 0 {
907                break;
908            }
909            l.byte(c);
910            i += 1;
911        }
912        // SAFETY: as above.
913        l.str(":")
914            .dec(unsafe { (&raw const PANIC_LINE).read_volatile() });
915        put_line(&mut row, &l, RED);
916        let msg = (&raw const PANIC_MSG).cast::<u8>();
917        let mut l = Line::new();
918        let mut i = 0;
919        while i < 120 {
920            // SAFETY: `i` < 120, inside the buffer.
921            let c = unsafe { msg.add(i).read_volatile() };
922            if c == 0 {
923                break;
924            }
925            if i > 0 && i % COLS == 0 {
926                put_line(&mut row, &l, RED);
927                l = Line::new();
928            }
929            l.byte(c);
930            i += 1;
931        }
932        put_line(&mut row, &l, RED);
933    }
934}
935
936/// VBlank watchdog, entered from the exception handler on every VBlank with the
937/// interrupted code's registers saved in `regs`.
938#[no_mangle]
939extern "C" fn __psx_diag_tick(regs: *const u32, epc: u32) {
940    // SAFETY: the handler runs with interrupts off on one thread, so nothing else touches WATCH.
941    unsafe {
942        let w = &raw mut WATCH;
943        let b: *const Block = &raw const PSX_DIAG;
944        let mut sig = diag::get(&raw const (*b).gp1_writes);
945        let kicks = (&raw const (*b).dma_kicks).cast::<u32>();
946        sig = sig.wrapping_add(diag::get(kicks.add(2)).wrapping_mul(3));
947        sig = sig.wrapping_add(diag::get(&raw const (*b).cd_sectors).wrapping_mul(5));
948        sig = sig.wrapping_add(diag::get(&raw const (*b).cd_cmds).wrapping_mul(7));
949        sig = sig.wrapping_add(crate::interrupts::present_kick_count().wrapping_mul(11));
950        if sig != (*w).last_sig {
951            (*w).last_sig = sig;
952            (*w).quiet = 0;
953            return;
954        }
955        (*w).quiet = (*w).quiet.wrapping_add(1);
956        if (*w).quiet < (&raw const STALL_LIMIT).read_volatile() {
957            return;
958        }
959        // Once stalled, take the screen on the first frame, then refresh every fourth.
960        if (*w).shown == 0 {
961            (*w).shown = 1;
962            take_screen();
963        } else if (*w).quiet & 3 != 0 {
964            return;
965        }
966    }
967    panel(Reason::Stall, regs, epc);
968}
969
970/// The exception handler's fatal halt: draw the panel for good.
971#[no_mangle]
972extern "C" fn __psx_diag_fault(regs: *const u32, epc: u32) -> ! {
973    take_screen();
974    loop {
975        panel(Reason::Fault, regs, epc);
976        // Pace on the VBlank flag, which still latches with interrupts off.
977        let mut n = 0u32;
978        while rd(I_STAT) & 1 == 0 && n < 2_000_000 {
979            n += 1;
980        }
981        wr(I_STAT, !1u32);
982    }
983}
984
985/// Clear the CPU's interrupt-enable bit, so the VBlank handler cannot run on the panel's
986/// stack while it draws.
987fn interrupts_off() {
988    // SAFETY: reads, clears bit 0 and writes back COP0 Status; the `nop` after the read covers
989    // the MFC0 load delay.
990    unsafe {
991        core::arch::asm!(
992            "mfc0 {t}, $12",
993            "nop",
994            "srl  {t}, {t}, 1",
995            "sll  {t}, {t}, 1",
996            "mtc0 {t}, $12",
997            "nop",
998            t = out(reg) _,
999            options(nostack),
1000        );
1001    }
1002}
1003
1004extern "C" fn panic_entry(info: *const u8) -> ! {
1005    interrupts_off();
1006    take_screen();
1007    let regs = &raw const __psx_diag_regs;
1008    loop {
1009        // SAFETY: `regs` is the register save area; word 31 is the saved return address.
1010        panel(Reason::Panic, regs.cast::<u32>(), unsafe {
1011            regs.cast::<u32>().add(31).read_volatile()
1012        });
1013        let mut n = 0u32;
1014        while rd(I_STAT) & 1 == 0 && n < 2_000_000 {
1015            n += 1;
1016        }
1017        wr(I_STAT, !1u32);
1018        let _ = info;
1019    }
1020}
1021
1022/// Record a panic's message and location, then show the panel; never returns.
1023/// Called by psx-rt's panic handler on diagnostic builds.
1024pub(crate) fn panic_panel(info: &core::panic::PanicInfo<'_>) -> ! {
1025    // SAFETY: the program is dead after this call; nothing else writes these.
1026    unsafe {
1027        let msg = (&raw mut PANIC_MSG).cast::<u8>();
1028        let mut w = MsgWriter { at: msg, len: 0 };
1029        use core::fmt::Write;
1030        let _ = write!(w, "{}", info.message());
1031        w.finish();
1032        let file = (&raw mut PANIC_FILE).cast::<u8>();
1033        if let Some(loc) = info.location() {
1034            let name = loc.file().as_bytes();
1035            // Keep the tail of a long path: the end names the file.
1036            let start = name.len().saturating_sub(47);
1037            let mut i = 0;
1038            while start + i < name.len() && i < 47 {
1039                file.add(i).write_volatile(name[start + i]);
1040                i += 1;
1041            }
1042            file.add(i).write_volatile(0);
1043            (&raw mut PANIC_LINE).write_volatile(loc.line());
1044        }
1045        (&raw mut PANIC_SET).write_volatile(1);
1046        // The stack and return address the panic ran on, so the panel can walk the call chain.
1047        let (sp, ra): (u32, u32);
1048        core::arch::asm!("move {}, $sp", "move {}, $ra", out(reg) sp, out(reg) ra, options(nomem, nostack));
1049        let regs = (&raw mut __psx_diag_regs).cast::<u32>();
1050        regs.add(29).write_volatile(sp);
1051        regs.add(31).write_volatile(ra);
1052        panic_entry(core::ptr::null())
1053    }
1054}
1055
1056struct MsgWriter {
1057    at: *mut u8,
1058    len: usize,
1059}
1060
1061impl MsgWriter {
1062    fn finish(&mut self) {
1063        // SAFETY: `len` < 120, inside the buffer.
1064        unsafe { self.at.add(self.len).write_volatile(0) };
1065    }
1066}
1067
1068impl core::fmt::Write for MsgWriter {
1069    fn write_str(&mut self, s: &str) -> core::fmt::Result {
1070        for &b in s.as_bytes() {
1071            if self.len < 119 {
1072                // SAFETY: `len` < 119, inside the buffer.
1073                unsafe { self.at.add(self.len).write_volatile(b) };
1074                self.len += 1;
1075            }
1076        }
1077        Ok(())
1078    }
1079}