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

psx_io/
gpu.rs

1//! GPU MMIO: `GP0`, `GP1`, `GPUREAD`, `GPUSTAT`.
2//!
3//! Thin wrappers over [`crate::read_u32`] / [`crate::write_u32`] that use
4//! the register addresses from `psx-hw`. Each helper commits exactly
5//! one MMIO access; higher-level SDK code composes them into commands.
6
7use psx_hw::gpu::{GpuStat, GP0, GP1, GPUREAD, GPUSTAT};
8
9#[cfg(any(feature = "present-queue", test))]
10mod handoff;
11#[cfg(any(feature = "present-queue", test))]
12pub use handoff::{
13    arm_direct_access_guard, is_recording, run_direct_access_guard, set_direct_access_guard,
14    start_recording_raw, ActiveRecording, CommandRecording, RecordingOverflow,
15    RECORDING_NODE_WORDS,
16};
17#[cfg(any(feature = "present-queue", test))]
18pub use handoff::{pause_recording, RecordingPause};
19
20/// Returned by [`pause_recording`]. Without the `present-queue` feature
21/// nothing can record, so it holds nothing and does nothing.
22#[cfg(not(any(feature = "present-queue", test)))]
23#[must_use = "the recording resumes as soon as this is dropped"]
24#[derive(Debug)]
25pub struct RecordingPause(());
26
27/// Pause any open command recording until the returned guard is dropped,
28/// so the command writes in between reach the port; psx-vram's uploads
29/// take one. Without the `present-queue` feature it compiles to nothing.
30#[cfg(not(any(feature = "present-queue", test)))]
31#[inline(always)]
32pub fn pause_recording() -> RecordingPause {
33    RecordingPause(())
34}
35
36/// Run the direct-access guard if a queued frame armed it. Without the
37/// `present-queue` feature nothing can arm it, so it compiles to nothing.
38#[cfg(not(any(feature = "present-queue", test)))]
39#[inline(always)]
40pub fn run_direct_access_guard() {}
41
42/// Push a drawing or VRAM command word, or one of its parameters, to the
43/// GPU's command port (`GP0`). Pairs with the word builders in
44/// `psx_hw::gpu::gp0`: `write_command(gp0::draw_mode(...))`.
45///
46/// With the `present-queue` feature, the word goes into the open command
47/// recording instead, if there is one, and an armed direct-access guard runs
48/// before the port write.
49#[doc(alias = "GP0")]
50#[inline(always)]
51pub fn write_command(word: u32) {
52    #[cfg(any(feature = "present-queue", test))]
53    if handoff::is_slow() {
54        handoff::write_command_slow(word);
55        return;
56    }
57    // SAFETY: GP0 (`psx_hw::gpu::GP0`) is the GPU's aligned 32-bit command/data port on every PS1. Any
58    // word is a legal write: the GPU parses it as a command or parameter, with no effect on
59    // CPU-visible memory.
60    unsafe { crate::write_u32(GP0, word) }
61}
62
63/// [`write_command`] straight to the port: never recorded, never behind the
64/// direct-access guard. For code that has already made the port safe, such
65/// as the present queue's stall recovery, which the guard itself runs.
66/// Without the `present-queue` feature it is the same store as [`write_command`].
67#[inline(always)]
68pub fn write_command_unguarded(word: u32) {
69    // SAFETY: GP0 (`psx_hw::gpu::GP0`) is the GPU's aligned 32-bit command/data port on every PS1. Any
70    // word is a legal write: the GPU parses it as a command or parameter, with no effect on
71    // CPU-visible memory.
72    unsafe { crate::write_u32(GP0, word) }
73}
74
75/// Write a display-control command (reset, display mode, display area,
76/// DMA direction) to the GPU's control port (`GP1`).
77///
78/// With the `present-queue` feature an armed direct-access guard runs first,
79/// unless a command recording is open (display control is never recorded).
80#[doc(alias = "GP1")]
81#[inline(always)]
82pub fn write_display_control(word: u32) {
83    #[cfg(any(feature = "present-queue", test))]
84    if handoff::is_slow() {
85        handoff::write_display_control_slow(word);
86        return;
87    }
88    crate::diag::gp1_write();
89    // SAFETY: GP1 (`psx_hw::gpu::GP1`) is the GPU's aligned 32-bit control port on every PS1; any word is
90    // a legal write and only changes GPU state.
91    unsafe { crate::write_u32(GP1, word) }
92}
93
94/// The function a display flip waits in, installed by the runtime that owns the
95/// VBlank clock (`psx_rt::interrupts::install_vblank_counter`).
96static mut FLIP_PACER: Option<fn()> = None;
97
98/// Install (or with `None` remove) the pacer [`pace_flip`] calls. Called by
99/// psx-rt; a program without that runtime never has one and flips unpaced.
100pub fn set_flip_pacer(pacer: Option<fn()>) {
101    // SAFETY: a volatile aligned store of a plain function pointer to a private static; the only
102    // reader is `pace_flip`, which runs in the same foreground thread.
103    unsafe { core::ptr::write_volatile(&raw mut FLIP_PACER, pacer) }
104}
105
106/// Wait, if the runtime says so, until a display flip is allowed (the
107/// presentation cap, `psx_tick::PresentCap`), and count the flip. Call it
108/// immediately before writing a GP1(05h) display-start word directly; a no-op
109/// without a pacer.
110#[inline]
111pub fn pace_flip() {
112    // SAFETY: a volatile aligned read of the private static written by `set_flip_pacer`.
113    if let Some(pacer) = unsafe { core::ptr::read_volatile(&raw const FLIP_PACER) } {
114        pacer();
115    }
116}
117
118/// [`write_display_control`] straight to the port, past the direct-access
119/// guard; see [`write_command_unguarded`].
120#[inline(always)]
121pub fn write_display_control_unguarded(word: u32) {
122    // SAFETY: GP1 (`psx_hw::gpu::GP1`) is the GPU's aligned 32-bit control port on every PS1; any word is
123    // a legal write and only changes GPU state.
124    unsafe { crate::write_u32(GP1, word) }
125}
126
127/// Read the GPU status register.
128#[doc(alias = "GPUSTAT")]
129#[inline(always)]
130pub fn status() -> GpuStat {
131    // SAFETY: GPUSTAT (`psx_hw::gpu::GP1` on read) is the GPU's aligned 32-bit status register; reading it
132    // has no side effects.
133    GpuStat::from_bits_retain(unsafe { crate::read_u32(GPUSTAT) })
134}
135
136/// Read the GPU's response latch: VRAM-to-CPU transfer data or a GP1(10h)
137/// info reply.
138#[doc(alias = "GPUREAD")]
139#[inline(always)]
140pub fn read_data() -> u32 {
141    // SAFETY: GPUREAD (`psx_hw::gpu::GP0` on read) is the GPU's aligned 32-bit response latch. A read may
142    // advance a VRAM-to-CPU transfer, which is its purpose, and touches no CPU memory.
143    unsafe { crate::read_u32(GPUREAD) }
144}
145
146/// Spin until the GPU is ready to accept a new command word.
147///
148/// Polls `GPUSTAT.READY_CMD`. On real hardware this bit is briefly
149/// cleared while the GPU is busy ingesting a multi-word packet; our
150/// emulator forces it on, so the loop is essentially a single read.
151/// Do not use this between GP0(0xA0) image payload words: after the
152/// transfer setup packet, the GPU is waiting for data, not a new
153/// normal command.
154#[inline]
155pub fn wait_command_ready() {
156    wait_ready(GpuStat::READY_CMD);
157}
158
159/// Spin budget for one GPUSTAT ready-wait. Long enough for the slowest
160/// legitimate primitive, short enough that a stuck GPU hands control
161/// back well inside a frame.
162pub const READY_SPINS: u32 = 500_000;
163
164/// Bounded ready-wait with recovery.
165///
166/// A GPU left mid-command never re-asserts its ready bits, so a bare
167/// `while !ready {}` hangs forever. That is not hypothetical: aborting a
168/// wedged linked-list DMA (see `psx_io::dma::abort`) stops the walker
169/// partway through a packet, and the GPU then sits waiting for command
170/// words that will never arrive. On timeout, GP1(01h) resets the command
171/// buffer, which is the documented way to discard that partial command
172/// and make the GPU accept work again.
173fn wait_ready(flag: GpuStat) {
174    #[cfg(any(feature = "present-queue", test))]
175    if handoff::is_recording() {
176        return;
177    }
178    let mut spins = 0u32;
179    let diag_site = if flag == GpuStat::READY_CMD {
180        crate::diag::site::GPU_READY_CMD
181    } else {
182        crate::diag::site::GPU_READY_DMA
183    };
184    crate::diag::wait_begin(diag_site, 0);
185    while !status().contains(flag) {
186        if spins >= READY_SPINS {
187            crate::diag::wait_timeout(diag_site, 0, READY_SPINS);
188            count_command_reset();
189            write_display_control(psx_hw::gpu::gp1::RESET_CMD_BUFFER);
190            return;
191        }
192        spins += 1;
193    }
194    crate::diag::wait_end();
195}
196
197/// GP1(01h) resets [`wait_command_ready`] and [`wait_dma_ready`] have issued
198/// after a ready bit stayed low for [`READY_SPINS`] polls.
199///
200/// In `.data`, not `.bss`, so a bare chain-loader image that nothing zeroes a
201/// `.bss` for counts from zero (see `irq::POLLING_KEEP`).
202#[cfg_attr(target_arch = "mips", link_section = ".data")]
203static mut COMMAND_RESETS: u32 = 0;
204
205#[cold]
206fn count_command_reset() {
207    // SAFETY: volatile aligned accesses to this private static; only this
208    // function writes it and the program is single threaded (no handler
209    // touches it).
210    unsafe {
211        let count = core::ptr::addr_of_mut!(COMMAND_RESETS);
212        count.write_volatile(count.read_volatile().wrapping_add(1));
213    }
214}
215
216/// How many times a ready-wait has timed out and reset the GPU's command
217/// buffer since boot: a count of GPU hangs the SDK recovered from.
218pub fn command_reset_count() -> u32 {
219    // SAFETY: a volatile aligned read of a private static.
220    unsafe { core::ptr::addr_of!(COMMAND_RESETS).read_volatile() }
221}
222
223/// Spin until the GPU can start a DMA block transfer.
224#[inline]
225pub fn wait_dma_ready() {
226    wait_ready(GpuStat::READY_DMA_RECV);
227}
228
229/// Poll command readiness without resetting the GPU on timeout.
230/// Reads once, then retries at most `spin_limit` times.
231#[inline]
232pub fn try_wait_command_ready(spin_limit: u32) -> bool {
233    try_wait_ready(GpuStat::READY_CMD, spin_limit)
234}
235/// Poll DMA receive readiness without resetting the GPU on timeout.
236#[inline]
237pub fn try_wait_dma_ready(spin_limit: u32) -> bool {
238    try_wait_ready(GpuStat::READY_DMA_RECV, spin_limit)
239}
240fn try_wait_ready(flag: GpuStat, spin_limit: u32) -> bool {
241    #[cfg(any(feature = "present-queue", test))]
242    if handoff::is_recording() {
243        return true;
244    }
245    poll_ready(spin_limit, || status().contains(flag))
246}
247
248/// Renamed to [`write_command`].
249#[deprecated(note = "renamed to `write_command`")]
250#[inline(always)]
251pub fn write_gp0(word: u32) {
252    write_command(word)
253}
254
255/// Renamed to [`write_display_control`].
256#[deprecated(note = "renamed to `write_display_control`")]
257#[inline(always)]
258pub fn write_gp1(word: u32) {
259    write_display_control(word)
260}
261
262/// Renamed to [`status`].
263#[deprecated(note = "renamed to `status`")]
264#[inline(always)]
265pub fn gpustat() -> GpuStat {
266    status()
267}
268
269/// Renamed to [`wait_command_ready`].
270#[deprecated(note = "renamed to `wait_command_ready`")]
271#[inline(always)]
272pub fn wait_cmd_ready() {
273    wait_command_ready()
274}
275
276fn poll_ready(spin_limit: u32, mut ready: impl FnMut() -> bool) -> bool {
277    let mut remaining = spin_limit;
278    loop {
279        if ready() {
280            return true;
281        }
282        if remaining == 0 {
283            return false;
284        }
285        remaining -= 1;
286    }
287}
288#[cfg(test)]
289mod tests {
290    use super::*;
291    #[test]
292    fn readiness_budget_includes_initial_probe() {
293        for limit in 0..5 {
294            let mut reads = 0;
295            assert!(!poll_ready(limit, || {
296                reads += 1;
297                false
298            }));
299            assert_eq!(reads, limit + 1);
300        }
301        let mut reads = 0;
302        assert!(poll_ready(2, || {
303            reads += 1;
304            reads == 3
305        }));
306        assert_eq!(reads, 3);
307    }
308}