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

psx_io/
diag.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2//! Console diagnostics: the counters a stop-panel prints.
3//!
4//! Built only with the `console-diag` feature. Without it every function here
5//! is an empty inline and the block does not exist, so a shipping image is
6//! byte-for-byte what it was. With it, the SDK's own bounded waits, CD command
7//! writes, sector pops and DMA kicks leave their last state in one
8//! `static` block, [`BLOCK`], that `psx_rt::diag` reads when a program stops
9//! (a fault, a panic, or no progress for many frames) and paints on screen,
10//! so one photo of a console shows where it stopped.
11//!
12//! Nothing here touches hardware; every store is a plain volatile word store
13//! to a private static, safe from the foreground and from the VBlank handler.
14
15/// Wait sites recorded in [`Block::wait_cur`] and [`Block::wait_last`].
16pub mod site {
17    /// `gpu::wait_command_ready` (GPUSTAT bit 26).
18    pub const GPU_READY_CMD: u32 = 1;
19    /// `gpu::wait_dma_ready` (GPUSTAT bit 28).
20    pub const GPU_READY_DMA: u32 = 2;
21    /// `dma::wait_done`; the channel number is added (3 to 9).
22    pub const DMA_DONE: u32 = 3;
23    /// The CD reader waiting for a command response; the expected flag is in
24    /// the high byte of the recorded value.
25    pub const CD_RESPONSE: u32 = 11;
26    /// The CD reader waiting for the next data sector.
27    pub const CD_SECTOR: u32 = 12;
28    /// The CD reader waiting for the data FIFO to fill.
29    pub const CD_FIFO: u32 = 13;
30}
31
32/// The diagnostics block. Every field is a plain word; the panel reads them
33/// with volatile loads.
34#[repr(C)]
35pub struct Block {
36    /// [`MAGIC`] once any hook has run.
37    pub magic: u32,
38    /// GP1 writes seen (one per presented frame in most programs).
39    pub gp1_writes: u32,
40    /// DMA kicks per channel, `dma::start`.
41    pub dma_kicks: [u32; 7],
42    /// `dma::wait_done` budgets that ran out.
43    pub dma_wait_fail: u32,
44    /// Channel of the last such failure.
45    pub dma_wait_ch: u32,
46    /// GPUSTAT ready-waits that timed out (and reset the GPU's command buffer).
47    pub gpu_wait_fail: u32,
48    /// Wait in progress now: site in the low byte, aux in the next, 0 for none.
49    pub wait_cur: u32,
50    /// The last wait that spun out: site, aux like `wait_cur`.
51    pub wait_last: u32,
52    /// Spin budget of that wait.
53    pub wait_last_spins: u32,
54    /// Waits that spun out.
55    pub wait_timeouts: u32,
56    /// Last CD command byte written.
57    pub cd_cmd: u32,
58    /// CD commands written.
59    pub cd_cmds: u32,
60    /// Last non-zero CD IRQ flag read.
61    pub cd_irq_seen: u32,
62    /// Last CD IRQ bits acknowledged.
63    pub cd_irq_acked: u32,
64    /// INT5 (drive error) responses.
65    pub cd_int5: u32,
66    /// Status byte of the last INT5.
67    pub cd_int5_status: u32,
68    /// Error byte of the last INT5.
69    pub cd_int5_code: u32,
70    /// CD waits that spun out.
71    pub cd_timeouts: u32,
72    /// `cause<<24 | status<<16 | command<<8 | flag` of the last timeout.
73    pub cd_timeout_info: u32,
74    /// Sectors popped from the data FIFO.
75    pub cd_sectors: u32,
76    /// Last absolute LBA a read was started at (after the disc-base shift).
77    pub cd_lba: u32,
78    /// Reads started (`start_read`): more than the chunks asked for means retries.
79    pub cd_starts: u32,
80    /// `read_sector` calls that failed.
81    pub cd_read_fail: u32,
82    /// The reader's own failure snapshot at the last failure.
83    pub cd_fail_word: u32,
84    /// Linked lists scanned at kick time.
85    pub ll_scans: u32,
86    /// Nodes seen in the last scan.
87    pub ll_nodes: u32,
88    /// Nodes over 16 payload words, all scans (silicon loses words from longer nodes).
89    pub ll_bad: u32,
90    /// Largest payload word count seen.
91    pub ll_max: u32,
92    /// Address of the first oversized node seen.
93    pub ll_bad_addr: u32,
94    /// Instruction-cache flushes (`psx_rt::cache`), each behind the DMA gate.
95    pub flushes: u32,
96    /// Flushes that found a DMA channel busy on entry and waited.
97    pub flush_waits: u32,
98    /// Times a flush backed out because a walk was kicked between its idle check and its mask.
99    pub flush_retries: u32,
100    /// Flushes whose wait for an idle bus ran out (the flush went ahead).
101    pub flush_timeouts: u32,
102    /// Most busy polls one flush made.
103    pub flush_max_spins: u32,
104    /// DMA CHCR 0 to 6 as the last flush found them on entry.
105    pub flush_chcr: [u32; 7],
106    /// GPUSTAT on entry to the last flush.
107    pub flush_gpustat: u32,
108    /// COP0 Status on entry to the last flush.
109    pub flush_sr: u32,
110    /// The cache control register on entry to the last flush.
111    pub flush_cc: u32,
112    /// Free-form step id set by the program ([`step`]).
113    pub step_id: u32,
114    /// Free-form step text, NUL padded.
115    pub step_text: [u8; 24],
116}
117
118/// Written to [`Block::magic`] by the first hook.
119pub const MAGIC: u32 = 0x5053_4447;
120
121/// The block. Read it with volatile loads.
122#[cfg(feature = "console-diag")]
123#[no_mangle]
124pub static mut PSX_DIAG: Block = Block {
125    magic: 0,
126    gp1_writes: 0,
127    dma_kicks: [0; 7],
128    dma_wait_fail: 0,
129    dma_wait_ch: 0,
130    gpu_wait_fail: 0,
131    wait_cur: 0,
132    wait_last: 0,
133    wait_last_spins: 0,
134    wait_timeouts: 0,
135    cd_cmd: 0,
136    cd_cmds: 0,
137    cd_irq_seen: 0,
138    cd_irq_acked: 0,
139    cd_int5: 0,
140    cd_int5_status: 0,
141    cd_int5_code: 0,
142    cd_timeouts: 0,
143    cd_timeout_info: 0,
144    cd_sectors: 0,
145    cd_lba: 0,
146    cd_starts: 0,
147    cd_read_fail: 0,
148    cd_fail_word: 0,
149    ll_scans: 0,
150    ll_nodes: 0,
151    ll_bad: 0,
152    ll_max: 0,
153    ll_bad_addr: 0,
154    flushes: 0,
155    flush_waits: 0,
156    flush_retries: 0,
157    flush_timeouts: 0,
158    flush_max_spins: 0,
159    flush_chcr: [0; 7],
160    flush_gpustat: 0,
161    flush_sr: 0,
162    flush_cc: 0,
163    step_id: 0,
164    step_text: [0; 24],
165};
166
167#[cfg(feature = "console-diag")]
168macro_rules! field {
169    ($f:ident) => {
170        // SAFETY: a raw pointer to a field of a private static; nothing is read or written here.
171        unsafe { &raw mut PSX_DIAG.$f }
172    };
173}
174
175#[cfg(feature = "console-diag")]
176#[inline(always)]
177fn bump(p: *mut u32) {
178    // SAFETY: a private static word; the program is single threaded and the only other reader is
179    // the panel, which runs when the program has stopped.
180    unsafe { p.write_volatile(p.read_volatile().wrapping_add(1)) }
181}
182
183#[cfg(feature = "console-diag")]
184#[inline(always)]
185fn set(p: *mut u32, v: u32) {
186    // SAFETY: as in `bump`.
187    unsafe { p.write_volatile(v) }
188}
189
190/// A raw read of one word of the block, for the panel.
191///
192/// # Safety
193/// `p` must point at a word of [`PSX_DIAG`].
194#[cfg(feature = "console-diag")]
195#[inline(always)]
196pub unsafe fn get(p: *const u32) -> u32 {
197    // SAFETY: as in `bump`; the caller passes a pointer into the block.
198    unsafe { p.read_volatile() }
199}
200
201/// Mark that the block is live.
202#[cfg(feature = "console-diag")]
203#[inline(always)]
204fn touch() {
205    set(field!(magic), MAGIC);
206}
207
208/// A `dma::start` on channel `ch` (0 to 6).
209#[inline(always)]
210pub fn dma_kick(ch: u32) {
211    #[cfg(feature = "console-diag")]
212    {
213        touch();
214        if ch < 7 {
215            // SAFETY: `ch` is in range, and the pointer stays inside the static.
216            bump(unsafe { (&raw mut PSX_DIAG.dma_kicks).cast::<u32>().add(ch as usize) });
217        }
218    }
219    #[cfg(not(feature = "console-diag"))]
220    let _ = ch;
221}
222
223/// A write to GP1.
224#[inline(always)]
225pub fn gp1_write() {
226    #[cfg(feature = "console-diag")]
227    bump(field!(gp1_writes));
228}
229
230/// A wait begins. `aux` is a small extra id (a channel, an expected flag).
231#[inline(always)]
232pub fn wait_begin(site: u32, aux: u32) {
233    #[cfg(feature = "console-diag")]
234    {
235        touch();
236        set(field!(wait_cur), site | (aux << 8));
237    }
238    #[cfg(not(feature = "console-diag"))]
239    let _ = (site, aux);
240}
241
242/// The wait that [`wait_begin`] opened ended normally.
243#[inline(always)]
244pub fn wait_end() {
245    #[cfg(feature = "console-diag")]
246    set(field!(wait_cur), 0);
247}
248
249/// The wait that [`wait_begin`] opened spun out after `spins` polls.
250#[inline(always)]
251pub fn wait_timeout(site: u32, aux: u32, spins: u32) {
252    #[cfg(feature = "console-diag")]
253    {
254        set(field!(wait_cur), 0);
255        set(field!(wait_last), site | (aux << 8));
256        set(field!(wait_last_spins), spins);
257        bump(field!(wait_timeouts));
258        if site == site::DMA_DONE {
259            bump(field!(dma_wait_fail));
260            set(field!(dma_wait_ch), aux);
261        } else if site <= site::GPU_READY_DMA {
262            bump(field!(gpu_wait_fail));
263        }
264    }
265    #[cfg(not(feature = "console-diag"))]
266    let _ = (site, aux, spins);
267}
268
269/// A CD command byte was written.
270#[inline(always)]
271pub fn cd_command(command: u8) {
272    #[cfg(feature = "console-diag")]
273    {
274        touch();
275        set(field!(cd_cmd), command as u32);
276        bump(field!(cd_cmds));
277    }
278    #[cfg(not(feature = "console-diag"))]
279    let _ = command;
280}
281
282/// A non-zero CD IRQ flag was read.
283#[inline(always)]
284pub fn cd_irq_seen(flag: u8) {
285    #[cfg(feature = "console-diag")]
286    if flag != 0 {
287        set(field!(cd_irq_seen), flag as u32);
288    }
289    #[cfg(not(feature = "console-diag"))]
290    let _ = flag;
291}
292
293/// CD IRQ bits were acknowledged.
294#[inline(always)]
295pub fn cd_irq_acked(bits: u8) {
296    #[cfg(feature = "console-diag")]
297    set(field!(cd_irq_acked), bits as u32);
298    #[cfg(not(feature = "console-diag"))]
299    let _ = bits;
300}
301
302/// The drive answered a command with INT5.
303#[inline(always)]
304pub fn cd_error(status: u8, code: u8) {
305    #[cfg(feature = "console-diag")]
306    {
307        bump(field!(cd_int5));
308        set(field!(cd_int5_status), status as u32);
309        set(field!(cd_int5_code), code as u32);
310    }
311    #[cfg(not(feature = "console-diag"))]
312    let _ = (status, code);
313}
314
315/// A CD wait spun out; `info` is the reader's snapshot word.
316#[inline(always)]
317pub fn cd_timeout(info: u32) {
318    #[cfg(feature = "console-diag")]
319    {
320        bump(field!(cd_timeouts));
321        set(field!(cd_timeout_info), info);
322    }
323    #[cfg(not(feature = "console-diag"))]
324    let _ = info;
325}
326
327/// One sector was popped from the data FIFO.
328#[inline(always)]
329pub fn cd_sector() {
330    #[cfg(feature = "console-diag")]
331    bump(field!(cd_sectors));
332}
333
334/// A read was started at absolute `lba`.
335#[inline(always)]
336pub fn cd_start(lba: u32) {
337    #[cfg(feature = "console-diag")]
338    {
339        bump(field!(cd_starts));
340        set(field!(cd_lba), lba);
341    }
342    #[cfg(not(feature = "console-diag"))]
343    let _ = lba;
344}
345
346/// `read_sector` failed; `word` is the reader's snapshot.
347#[inline(always)]
348pub fn cd_read_failed(word: u32) {
349    #[cfg(feature = "console-diag")]
350    {
351        bump(field!(cd_read_fail));
352        set(field!(cd_fail_word), word);
353    }
354    #[cfg(not(feature = "console-diag"))]
355    let _ = word;
356}
357
358/// An instruction-cache flush has the bus quiet and is about to change the cache: record what it
359/// found. `chcr` are the seven DMA control registers, in channel order.
360#[inline(always)]
361pub fn flush_enter(chcr: [u32; 7], gpustat: u32, sr: u32, cc: u32) {
362    #[cfg(feature = "console-diag")]
363    {
364        touch();
365        bump(field!(flushes));
366        // SAFETY: `flush_chcr` is a 7-word array in the static; the writes stay inside it.
367        let dst = unsafe { (&raw mut PSX_DIAG.flush_chcr).cast::<u32>() };
368        let mut i = 0;
369        while i < 7 {
370            // SAFETY: `i` < 7, inside `flush_chcr`.
371            unsafe { dst.add(i).write_volatile(chcr[i]) };
372            i += 1;
373        }
374        set(field!(flush_gpustat), gpustat);
375        set(field!(flush_sr), sr);
376        set(field!(flush_cc), cc);
377    }
378    #[cfg(not(feature = "console-diag"))]
379    let _ = (chcr, gpustat, sr, cc);
380}
381
382/// An instruction-cache flush's gate has finished: whether a channel was busy on entry, how many
383/// times it backed out, the busy polls it made, and whether its bound ran out.
384#[inline(always)]
385pub fn flush_exit(busy_at_entry: bool, retries: u32, spins: u32, timed_out: bool) {
386    #[cfg(feature = "console-diag")]
387    {
388        if busy_at_entry {
389            bump(field!(flush_waits));
390        }
391        if retries != 0 {
392            let p = field!(flush_retries);
393            // SAFETY: `p` points into the block.
394            set(p, unsafe { get(p) }.wrapping_add(retries));
395        }
396        if timed_out {
397            bump(field!(flush_timeouts));
398        }
399        let max = field!(flush_max_spins);
400        // SAFETY: `max` points into the block.
401        if spins > unsafe { get(max) } {
402            set(max, spins);
403        }
404    }
405    #[cfg(not(feature = "console-diag"))]
406    let _ = (busy_at_entry, retries, spins, timed_out);
407}
408
409/// True when `pc` is not an address code can run from: main RAM through KSEG0 or KSEG1 (the
410/// kernel area included), or the BIOS ROM. A jump into anything else went somewhere wild.
411pub const fn is_wild_pc(pc: u32) -> bool {
412    let ram = (pc >= 0x8000_0000 && pc < 0x8020_0000) || (pc >= 0xa000_0000 && pc < 0xa020_0000);
413    let rom = pc >= 0xbfc0_0000 && pc < 0xbfc8_0000;
414    !(ram || rom)
415}
416
417/// The instruction word whose `j` target is `pc` (top four bits of `pc` taken from the jump's own
418/// address region): `0x08000000 | pc >> 2` in its 26-bit field. A CPU that jumped to a wild `pc`
419/// fetched such a word from somewhere; if the word reads as a GPU list header, the fetch got
420/// DMA traffic.
421pub const fn jump_word_for(pc: u32) -> u32 {
422    0x0800_0000 | ((pc >> 2) & 0x03ff_ffff)
423}
424
425/// Name the step the program has reached, for the panel: `id` and up to 24
426/// ASCII bytes of `text`.
427#[inline(never)]
428pub fn step(id: u32, text: &str) {
429    #[cfg(feature = "console-diag")]
430    {
431        touch();
432        set(field!(step_id), id);
433        // SAFETY: a raw pointer to a field of a private static; nothing is read or written here.
434        let dst = unsafe { (&raw mut PSX_DIAG.step_text).cast::<u8>() };
435        let bytes = text.as_bytes();
436        let mut i = 0;
437        while i < 24 {
438            let b = if i < bytes.len() { bytes[i] } else { 0 };
439            // SAFETY: `i < 24`, inside `step_text`.
440            unsafe { dst.add(i).write_volatile(b) };
441            i += 1;
442        }
443    }
444    #[cfg(not(feature = "console-diag"))]
445    let _ = (id, text);
446}
447
448/// Stop here on purpose: execute BREAK so the console-diag exception handler takes the screen
449/// and shows the panel (with the last [`step`]) instead of the program going on.
450#[inline(never)]
451pub fn stop() {
452    #[cfg(all(feature = "console-diag", target_arch = "mips"))]
453    // SAFETY: BREAK raises the exception the panel is built to catch.
454    unsafe {
455        core::arch::asm!("break 0");
456    }
457}
458
459/// [`step`] with a tag and two numbers printed as hex: `"<tag> <a:8 hex> <b:8 hex>"`, the tag
460/// cut to 6 bytes, so a failure site can say which file/chunk and which result in 24 bytes.
461#[inline(never)]
462pub fn step_hex(id: u32, tag: &str, a: u32, b: u32) {
463    #[cfg(feature = "console-diag")]
464    {
465        let mut text = [b' '; 24];
466        let t = tag.as_bytes();
467        let mut i = 0;
468        while i < 6 && i < t.len() {
469            text[i] = t[i];
470            i += 1;
471        }
472        let digits = b"0123456789ABCDEF";
473        let mut n = 0;
474        while n < 8 {
475            text[7 + n] = digits[((a >> (28 - 4 * n)) & 15) as usize];
476            text[16 + n] = digits[((b >> (28 - 4 * n)) & 15) as usize];
477            n += 1;
478        }
479        // SAFETY: only ASCII bytes were written.
480        step(id, unsafe { core::str::from_utf8_unchecked(&text) });
481    }
482    #[cfg(not(feature = "console-diag"))]
483    let _ = (id, tag, a, b);
484}
485
486/// Walk the GPU linked list that starts at `head` (a physical or KSEG address) and record
487/// every node over 16 payload words. The walk is bounded and stays inside main RAM.
488#[inline(never)]
489pub fn ll_scan(head: u32) {
490    #[cfg(feature = "console-diag")]
491    {
492        const RAM_MASK: u32 = 0x001f_fffc;
493        touch();
494        bump(field!(ll_scans));
495        let mut addr = head & RAM_MASK;
496        let mut nodes = 0u32;
497        while nodes < 200_000 {
498            // SAFETY: `addr` is masked into main RAM, 4-byte aligned; the tag word is plain memory.
499            let tag = unsafe { core::ptr::read_volatile((0x8000_0000 | addr) as *const u32) };
500            let words = tag >> 24;
501            if words > 16 {
502                let bad = field!(ll_bad);
503                // SAFETY: `bad` points into the block.
504                if unsafe { get(bad) } == 0 {
505                    set(field!(ll_bad_addr), addr);
506                }
507                bump(field!(ll_bad));
508            }
509            let max = field!(ll_max);
510            // SAFETY: `max` points into the block.
511            if words > unsafe { get(max) } {
512                set(field!(ll_max), words);
513            }
514            nodes += 1;
515            if tag & 0x0080_0000 != 0 {
516                break;
517            }
518            addr = tag & RAM_MASK;
519        }
520        set(field!(ll_nodes), nodes);
521    }
522    #[cfg(not(feature = "console-diag"))]
523    let _ = head;
524}
525
526#[cfg(test)]
527mod tests {
528    use super::*;
529
530    #[test]
531    fn code_addresses_are_not_wild_and_the_bus_error_pc_is() {
532        assert!(!is_wild_pc(0x8001_0000));
533        assert!(!is_wild_pc(0x8000_0080));
534        assert!(!is_wild_pc(0xa00a_2b4c));
535        assert!(!is_wild_pc(0xbfc0_1944));
536        // The console fault of 2026-10-22: PC B428AD34.
537        assert!(is_wild_pc(0xb428_ad34));
538        assert!(is_wild_pc(0x0000_0000));
539        assert!(is_wild_pc(0x8020_0000));
540        assert!(is_wild_pc(0xbfc8_0000));
541    }
542
543    #[test]
544    fn the_wild_pc_decodes_to_the_jump_word_that_was_fetched() {
545        // The word read as a GPU list header was count 9, next 0x0A2B4D, against MADR 0x0A2B4C.
546        assert_eq!(jump_word_for(0xb428_ad34), 0x090a_2b4d);
547        assert_eq!(jump_word_for(0x8001_0000) >> 26, 2, "opcode J");
548    }
549
550    #[test]
551    fn the_flush_hooks_are_callable_without_the_feature() {
552        flush_enter([0; 7], 0, 0, 0);
553        flush_exit(true, 1, 2, false);
554    }
555}