psx_io/gpu/handoff.rs
1//! Command recording and the direct-access guard: what lets a frame's GPU
2//! work be handed to a queue (`psx_rt::present`) instead of the ports.
3//!
4//! Built only with the `present-queue` feature. Without it the port writes
5//! in [`super`] compile to a single store, as before.
6//!
7//! - **Recording.** While the [`ActiveRecording`] that
8//! [`start_recording_raw`] returns is alive, [`super::write_command`]
9//! appends to a caller buffer laid out as DMA linked-list nodes instead of
10//! writing the port, and the ready-waits return at once. Immediate drawing
11//! (every psx-gpu `draw_*`, every HUD helper) can then be replayed later by
12//! one DMA walk. [`ActiveRecording::end`] consumes the guard, so a
13//! recording cannot be ended twice, and a closed recording never reopens:
14//! neither a late [`RecordingPause`] nor the deprecated [`end_recording`]
15//! touches the buffer of a recording that is no longer open.
16//! - **Direct-access guard.** Once armed ([`arm_direct_access_guard`]), the
17//! first direct command or display-control write, or GPU DMA address
18//! store, runs the registered guard function first, which waits until no
19//! queued walk can collide with the access.
20//!
21//! Both states share one flag, so a plain port write costs one extra load
22//! and branch while the feature is on.
23
24use core::ptr::{addr_of, addr_of_mut, read_volatile, write_volatile};
25
26/// Payload words per recorded linked-list node. Silicon (hardware-tests
27/// v1.24) loses words from DMA nodes longer than 16 while drawing.
28pub const RECORDING_NODE_WORDS: u32 = 16;
29
30/// The one command recording. The buffer pointers are meaningful only while
31/// `open` is set; closing clears `open` and `active` before anything else,
32/// so no path reaches a buffer whose recording has ended.
33struct Recording {
34 /// Between a start and the close of that recording.
35 open: bool,
36 /// Open and not paused: what [`is_recording`] reports.
37 active: bool,
38 /// Counts starts, so a guard or pause knows whether the open recording
39 /// is still the one it was made for.
40 generation: u32,
41 overflowed: bool,
42 head: *mut u32,
43 node: *mut u32,
44 node_words: u32,
45 next: *mut u32,
46 end: *mut u32,
47}
48
49// The recording state is in `.data`, not `.bss`, so a bare chain-loader image
50// that nothing zeroes a `.bss` for (it still writes the GPU ports with this
51// feature on) starts with no open recording and the guard disarmed. See
52// `irq::POLLING_KEEP`; guest-only for the same reason.
53#[cfg_attr(target_arch = "mips", link_section = ".data")]
54static mut RECORDING: Recording = Recording {
55 open: false,
56 active: false,
57 generation: 0,
58 overflowed: false,
59 head: core::ptr::null_mut(),
60 node: core::ptr::null_mut(),
61 node_words: 0,
62 next: core::ptr::null_mut(),
63 end: core::ptr::null_mut(),
64};
65
66/// Set while recording or while the guard is armed: the rare state the port
67/// writes test with one load before their plain store.
68#[cfg_attr(target_arch = "mips", link_section = ".data")]
69static mut SLOW: bool = false;
70#[cfg_attr(target_arch = "mips", link_section = ".data")]
71static mut GUARD_ARMED: bool = false;
72#[cfg_attr(target_arch = "mips", link_section = ".data")]
73static mut GUARD: Option<fn()> = None;
74
75#[inline(always)]
76pub(super) fn is_slow() -> bool {
77 // SAFETY: a volatile read of a `bool` static; the program is single
78 // threaded and the VBlank handler never touches it.
79 unsafe { read_volatile(addr_of!(SLOW)) }
80}
81
82fn refresh_slow() {
83 // SAFETY: volatile reads and a write of `bool` statics owned by this
84 // module; the program is single threaded and no interrupt handler
85 // touches them.
86 unsafe {
87 let slow =
88 read_volatile(addr_of!(RECORDING.active)) || read_volatile(addr_of!(GUARD_ARMED));
89 write_volatile(addr_of_mut!(SLOW), slow);
90 }
91}
92
93fn set_recording_active(active: bool) {
94 // SAFETY: a volatile write of a `bool` static owned by this module.
95 unsafe { write_volatile(addr_of_mut!(RECORDING.active), active) };
96 refresh_slow();
97}
98
99/// The slow half of [`super::write_command`]: record the word, or run the
100/// guard before the port write. Out of line and cold, so each write site
101/// carries only the flag load and branch.
102#[cold]
103#[inline(never)]
104pub(super) fn write_command_slow(word: u32) {
105 if is_recording() {
106 record_word(word);
107 return;
108 }
109 run_direct_access_guard();
110 super::write_command_unguarded(word);
111}
112
113/// The slow half of [`super::write_display_control`]: run the guard unless a
114/// recording is open (display control is never recorded), then write the
115/// port.
116#[cold]
117#[inline(never)]
118pub(super) fn write_display_control_slow(word: u32) {
119 if !is_recording() {
120 run_direct_access_guard();
121 }
122 super::write_display_control_unguarded(word);
123}
124
125/// A command stream recorded by [`start_recording_raw`]: DMA linked-list
126/// nodes that end the list until [`link_to`](Self::link_to) chains them
127/// onward.
128#[derive(Debug)]
129pub struct CommandRecording {
130 head: *mut u32,
131 tail: *mut u32,
132 words: usize,
133}
134
135impl CommandRecording {
136 /// First node, the address a chain links to or a DMA walk starts at.
137 #[inline]
138 pub fn head(&self) -> *const u32 {
139 self.head
140 }
141
142 /// Words used in the buffer, node headers included.
143 #[inline]
144 pub fn len_words(&self) -> usize {
145 self.words
146 }
147
148 /// Point the last node at `next` (a node tag) instead of ending the list
149 /// there.
150 ///
151 /// # Safety
152 ///
153 /// The recording's buffer must still be live, and no walk of it may have
154 /// started.
155 #[inline]
156 pub unsafe fn link_to(&self, next: *const u32) {
157 // SAFETY: `tail` is the last node's tag inside the caller's buffer,
158 // which the caller keeps live and unwalked (this fn's `# Safety`).
159 unsafe {
160 *self.tail = (*self.tail & 0xff00_0000) | (next as u32 & 0x00ff_ffff);
161 }
162 }
163}
164
165/// The recording ran out of buffer, so it was discarded: a command cut short
166/// would make the GPU take the words after it as its parameters.
167#[derive(Clone, Copy, Debug, PartialEq, Eq)]
168pub struct RecordingOverflow;
169
170/// True while a recording is open and not paused by [`pause_recording`].
171#[inline(always)]
172pub fn is_recording() -> bool {
173 // SAFETY: a volatile read of a `bool` static owned by this module.
174 unsafe { read_volatile(addr_of!(RECORDING.active)) }
175}
176
177/// Open the recording on `buffer` and return its generation.
178///
179/// # Safety
180///
181/// As [`start_recording_raw`].
182unsafe fn open(buffer: *mut u32, words: usize) -> u32 {
183 // SAFETY: exclusive access to this module's static (single threaded, no
184 // handler touches it). `buffer.add(words)` stays inside or one past the
185 // caller's buffer (the caller's `# Safety`).
186 let generation = unsafe {
187 let recording = &mut *addr_of_mut!(RECORDING);
188 debug_assert!(!recording.open, "a recording is already open");
189 recording.generation = recording.generation.wrapping_add(1);
190 recording.open = true;
191 recording.overflowed = false;
192 recording.head = core::ptr::null_mut();
193 recording.node = core::ptr::null_mut();
194 recording.node_words = 0;
195 recording.next = buffer;
196 recording.end = buffer.add(words);
197 recording.generation
198 };
199 set_recording_active(true);
200 generation
201}
202
203/// True when the recording of `generation` is still the open one.
204fn is_open(generation: u32) -> bool {
205 // SAFETY: volatile reads of this module's static.
206 unsafe {
207 read_volatile(addr_of!(RECORDING.open))
208 && read_volatile(addr_of!(RECORDING.generation)) == generation
209 }
210}
211
212/// Close the open recording, if it is the one of `generation` (any open one
213/// for `None`), and terminate its last node. A recording that is already
214/// closed is left alone: `Ok(None)`, and no memory is touched.
215fn close(generation: Option<u32>) -> Result<Option<CommandRecording>, RecordingOverflow> {
216 // SAFETY: a volatile read of this module's static.
217 let open = unsafe { read_volatile(addr_of!(RECORDING.open)) };
218 if !open || generation.is_some_and(|generation| !is_open(generation)) {
219 return Ok(None);
220 }
221 set_recording_active(false);
222 // SAFETY: exclusive access to this module's static. The recording is
223 // open (checked above), so `node` and `head` point into the buffer its
224 // start's contract keeps live until it is closed, which is now; `next`
225 // is in the same buffer at or after `head`. The pointers are cleared
226 // before returning, so nothing reaches the buffer through them again.
227 unsafe {
228 let recording = &mut *addr_of_mut!(RECORDING);
229 recording.open = false;
230 let result = if recording.overflowed {
231 Err(RecordingOverflow)
232 } else if recording.node.is_null() {
233 Ok(None)
234 } else {
235 *recording.node = (recording.node_words << 24) | 0x00ff_ffff;
236 Ok(Some(CommandRecording {
237 head: recording.head,
238 tail: recording.node,
239 words: recording.next.offset_from(recording.head) as usize,
240 }))
241 };
242 recording.head = core::ptr::null_mut();
243 recording.node = core::ptr::null_mut();
244 recording.node_words = 0;
245 recording.next = core::ptr::null_mut();
246 recording.end = core::ptr::null_mut();
247 result
248 }
249}
250
251/// The open recording [`start_recording_raw`] returned. [`end`](Self::end)
252/// closes it and hands back the recorded nodes; dropping it closes it too,
253/// discarding the result.
254#[must_use = "dropping the recording ends it at once"]
255#[derive(Debug)]
256pub struct ActiveRecording {
257 generation: u32,
258}
259
260impl ActiveRecording {
261 /// Stop recording. `Ok(None)` when nothing was written.
262 pub fn end(self) -> Result<Option<CommandRecording>, RecordingOverflow> {
263 let generation = self.generation;
264 core::mem::forget(self);
265 close(Some(generation))
266 }
267}
268
269impl Drop for ActiveRecording {
270 fn drop(&mut self) {
271 let _ = close(Some(self.generation));
272 }
273}
274
275/// Record every [`super::write_command`] into `buffer` instead of the port,
276/// until the returned [`ActiveRecording`] is ended or dropped. The
277/// ready-waits return at once while recording.
278///
279/// Display-control writes and DMA are not recorded: do not change display
280/// state inside a recording, and upload images only through
281/// [`pause_recording`] (psx-vram's uploads do).
282///
283/// # Panics
284///
285/// In debug builds, if a recording is already open. Release builds close
286/// that one first, as dropping its guard would.
287///
288/// # Safety
289///
290/// `buffer` must be valid for `words` word writes and 4-byte aligned. It
291/// must stay live and unmodified (apart from [`CommandRecording::link_to`])
292/// until the recording is closed, which a leaked [`ActiveRecording`] never
293/// does, and after that until every walk of the recording has finished.
294#[doc(alias = "begin_recording_raw")]
295pub unsafe fn start_recording_raw(buffer: *mut u32, words: usize) -> ActiveRecording {
296 let _ = close(None);
297 // SAFETY: forwarded from this fn's `# Safety`.
298 let generation = unsafe { open(buffer, words) };
299 ActiveRecording { generation }
300}
301
302/// An open recording paused by [`pause_recording`]; it resumes where it left
303/// off when this is dropped, provided that recording is still open.
304#[must_use = "the recording resumes as soon as this is dropped"]
305#[derive(Debug)]
306pub struct RecordingPause {
307 /// Generation of the recording this paused, if it paused one.
308 resume: Option<u32>,
309}
310
311/// Pause any open recording until the returned guard is dropped, so command
312/// writes in between go to the port (behind the direct-access guard)
313/// instead of into the buffer. For VRAM uploads, which a recording cannot
314/// carry: a texture first drawn by a recorded HUD is uploaded at once,
315/// before the recording is walked, which is all a draw of it needs.
316#[inline]
317pub fn pause_recording() -> RecordingPause {
318 if !is_recording() {
319 return RecordingPause { resume: None };
320 }
321 set_recording_active(false);
322 // SAFETY: a volatile read of this module's static.
323 let generation = unsafe { read_volatile(addr_of!(RECORDING.generation)) };
324 RecordingPause {
325 resume: Some(generation),
326 }
327}
328
329impl Drop for RecordingPause {
330 #[inline]
331 fn drop(&mut self) {
332 // A recording closed (or replaced) while paused stays closed: its
333 // buffer may already be gone.
334 if let Some(generation) = self.resume {
335 if is_open(generation) {
336 set_recording_active(true);
337 }
338 }
339 }
340}
341
342#[inline(never)]
343fn record_word(word: u32) {
344 // SAFETY: exclusive access to this module's static. Every store lands
345 // at `next`, which the checks below keep below `end`, inside the buffer
346 // `begin_recording_raw`'s caller provided.
347 unsafe {
348 let recording = &mut *addr_of_mut!(RECORDING);
349 if recording.overflowed {
350 return;
351 }
352 if recording.node.is_null() || recording.node_words == RECORDING_NODE_WORDS {
353 // A new node needs its tag plus at least this word.
354 if (recording.end as usize).saturating_sub(recording.next as usize) < 8 {
355 recording.overflowed = true;
356 return;
357 }
358 let tag = recording.next;
359 if recording.node.is_null() {
360 recording.head = tag;
361 } else {
362 *recording.node = (recording.node_words << 24) | (tag as u32 & 0x00ff_ffff);
363 }
364 recording.node = tag;
365 recording.node_words = 0;
366 recording.next = tag.add(1);
367 } else if recording.next >= recording.end {
368 recording.overflowed = true;
369 return;
370 }
371 *recording.next = word;
372 recording.next = recording.next.add(1);
373 recording.node_words += 1;
374 }
375}
376
377/// Register the function that makes direct GPU access safe while a queued
378/// frame may be walking (`psx_rt::present` registers its `wait_idle`). It
379/// runs once, on the first direct command or display-control write or GPU
380/// DMA address store after [`arm_direct_access_guard`], and is then
381/// disarmed.
382pub fn set_direct_access_guard(guard: fn()) {
383 // SAFETY: a volatile write of this module's static.
384 unsafe { write_volatile(addr_of_mut!(GUARD), Some(guard)) };
385}
386
387/// Arm the guard: the GPU may be busy with work the CPU handed off, so the
388/// next direct access must wait for it first.
389pub fn arm_direct_access_guard() {
390 // SAFETY: a volatile write of a `bool` static owned by this module.
391 unsafe { write_volatile(addr_of_mut!(GUARD_ARMED), true) };
392 refresh_slow();
393}
394
395/// Run and disarm the guard if it is armed. Direct-access paths outside the
396/// port writes (GPU DMA setup) call it first.
397#[inline]
398pub fn run_direct_access_guard() {
399 // SAFETY: volatile accesses to this module's statics.
400 let armed = unsafe { read_volatile(addr_of!(GUARD_ARMED)) };
401 if armed {
402 run_armed_guard();
403 }
404}
405
406/// Disarm and run the guard: the rare half of [`run_direct_access_guard`],
407/// kept out of line so each GPU DMA start carries only the flag test.
408#[cold]
409#[inline(never)]
410fn run_armed_guard() {
411 // SAFETY: volatile accesses to this module's statics.
412 unsafe { write_volatile(addr_of_mut!(GUARD_ARMED), false) };
413 refresh_slow();
414 // SAFETY: as above.
415 if let Some(guard) = unsafe { read_volatile(addr_of!(GUARD)) } {
416 guard();
417 }
418}
419
420#[cfg(test)]
421mod tests {
422 extern crate std;
423
424 use super::super::{wait_command_ready, write_command};
425 use super::*;
426 use std::sync::{Mutex, MutexGuard};
427
428 /// The recording state is one global, so tests that touch it take turns.
429 fn serial() -> MutexGuard<'static, ()> {
430 static LOCK: Mutex<()> = Mutex::new(());
431 LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
432 }
433
434 /// Words land in nodes of at most 16 with tags linking each node to the
435 /// next and the last ending the list; waits do not block; an overflow
436 /// discards the whole recording; a paused stretch bypasses it.
437 #[test]
438 fn recording_lays_out_sixteen_word_nodes() {
439 let _serial = serial();
440 let mut buffer = [0u32; 64];
441 // Every access goes through this one pointer: a reference to
442 // `buffer` taken while the recording's pointers are in use would
443 // retire them (Tree Borrows).
444 let words = buffer.as_mut_ptr();
445 // SAFETY: in bounds of `buffer`, which outlives this closure's uses.
446 let word = |index: usize| unsafe { words.add(index).read() };
447 // SAFETY: `buffer` outlives the recording and is never walked.
448 let active = unsafe { start_recording_raw(words, 64) };
449 assert!(is_recording());
450 for word in 0..40u32 {
451 wait_command_ready();
452 write_command(0x1000 + word);
453 }
454 let recording = active.end().expect("fits").expect("words recorded");
455 assert!(!is_recording());
456 let base = words as u32;
457 assert_eq!(recording.head() as u32, base);
458 assert_eq!(word(0) >> 24, 16);
459 assert_eq!(word(0) & 0x00ff_ffff, (base + 17 * 4) & 0x00ff_ffff);
460 assert_eq!([word(1), word(2)], [0x1000, 0x1001]);
461 assert_eq!(word(17) >> 24, 16);
462 assert_eq!(word(34), (8 << 24) | 0x00ff_ffff);
463 assert_eq!(word(42), 0x1000 + 39);
464 assert_eq!(recording.len_words(), 43);
465 // SAFETY: `buffer` is live and never walked.
466 unsafe { recording.link_to(0x8001_2340 as *const u32) };
467 assert_eq!(word(34), (8 << 24) | 0x0001_2340);
468
469 let mut small = [0u32; 8];
470 // SAFETY: as above.
471 let active = unsafe { start_recording_raw(small.as_mut_ptr(), small.len()) };
472 for word in 0..10u32 {
473 write_command(word);
474 }
475 assert_eq!(active.end().unwrap_err(), RecordingOverflow);
476
477 let mut empty = [0u32; 4];
478 // SAFETY: as above.
479 let active = unsafe { start_recording_raw(empty.as_mut_ptr(), empty.len()) };
480 assert!(active.end().expect("no overflow").is_none());
481
482 let mut resumed = [0u32; 8];
483 // SAFETY: as above.
484 let active = unsafe { start_recording_raw(resumed.as_mut_ptr(), resumed.len()) };
485 write_command(0xaa);
486 {
487 let _pause = pause_recording();
488 assert!(!is_recording());
489 }
490 assert!(is_recording());
491 write_command(0xbb);
492 let recording = active.end().expect("fits").expect("words recorded");
493 assert_eq!(recording.len_words(), 3);
494 assert_eq!(&resumed[1..3], &[0xaa, 0xbb]);
495 assert!(!is_slow());
496 }
497
498 /// Starts a recording on a stack buffer, pauses it, ends it while
499 /// paused, and hands back the pause after the buffer is gone.
500 #[inline(never)]
501 fn pause_outliving_its_recording() -> RecordingPause {
502 let mut buffer = [0u32; 8];
503 // SAFETY: the recording is ended below, before `buffer` goes, and it
504 // is never walked.
505 let active = unsafe { start_recording_raw(buffer.as_mut_ptr(), buffer.len()) };
506 write_command(0xcafe);
507 let pause = pause_recording();
508 assert!(active.end().expect("fits").is_some());
509 pause
510 }
511
512 /// io-01: dropping a pause taken before its recording ended reopened
513 /// the closed recording, after which a safe `write_command` recorded
514 /// into the dead buffer. The closed recording now stays closed.
515 #[test]
516 fn a_pause_outliving_its_recording_does_not_reopen_it() {
517 let _serial = serial();
518 drop(pause_outliving_its_recording());
519 assert!(!is_recording());
520 assert!(!is_slow());
521 }
522
523 /// Dropping the guard without `end` closes the recording, and a pause
524 /// that belongs to an older recording never resumes a newer one.
525 #[test]
526 fn dropping_the_guard_closes_and_old_pauses_stay_inert() {
527 let _serial = serial();
528 let mut first = [0u32; 8];
529 // SAFETY: both recordings end inside this test, before their buffers
530 // go, and neither is walked.
531 let active = unsafe { start_recording_raw(first.as_mut_ptr(), first.len()) };
532 let pause = pause_recording();
533 drop(active);
534 assert!(!is_recording());
535
536 let mut second = [0u32; 8];
537 // SAFETY: as above.
538 let active = unsafe { start_recording_raw(second.as_mut_ptr(), second.len()) };
539 let inner = pause_recording();
540 drop(pause);
541 assert!(!is_recording(), "an older pause must not resume");
542 drop(inner);
543 assert!(is_recording());
544 write_command(0x55);
545 let recording = active.end().expect("fits").expect("words recorded");
546 assert_eq!(recording.len_words(), 2);
547 assert_eq!(second[1], 0x55);
548 assert!(!is_slow());
549 }
550}