psx_cdstream/console.rs
1//! The console side: the real drive, the one global [`Engine`], and the
2//! exception wrapper that feeds it.
3//!
4//! Everything here is for the target. (It also compiles under `cfg(doc)` so
5//! the documentation shows it; none of it may run on the host.)
6//!
7//! # Interrupt path
8//!
9//! The wrapper sits in the general exception vector in front of psx-rt's
10//! handler, or in front of another wrapper that leads there (the pad engine's),
11//! whichever was in the vector when [`install`] ran. For an interrupt with the CD source pending it saves the
12//! interrupted CPU context, switches to a private 768-byte stack, calls the
13//! engine for one sector or one response, restores the context, and jumps to
14//! psx-rt's handler either way, so the VBlank counter, the display flip and
15//! the fault handling run exactly as before. Anything else goes straight
16//! through. The wrapper never touches the interrupted stack, which is what
17//! makes it safe with a scratchpad stack; [`install`] declares it so
18//! (`psx_rt::interrupts::declare_stack_safe_handler`).
19//!
20//! # Foreground path
21//!
22//! Every foreground call closes the CD source in `I_MASK` first, so the
23//! handler cannot run while the engine is being touched, and opens it again
24//! afterwards if the engine wants it open.
25
26use crate::engine::{Config, Engine, LeaseState, Owner, Phase, StreamStats};
27use crate::hw::CdHw;
28use crate::request::{Request, RequestState, SubmitError, Ticket};
29use core::cell::UnsafeCell;
30use psx_hw::cd::{index_status, irq as flag};
31use psx_hw::irq::source;
32use psx_io::irq;
33use psx_io::periph::Cd;
34use psx_io::timers::{self, Timer};
35
36/// CD interrupt source bit in `I_STAT` and `I_MASK`.
37const CD_BIT: u32 = 1 << source::CDROM;
38/// Status reads to wait for room in the parameter FIFO.
39const PARAM_POLLS: u32 = 32;
40/// Status reads to wait for the data FIFO to fill after a sector interrupt.
41const FIFO_POLLS: u32 = 256;
42/// Bytes of private stack the handler runs on.
43///
44/// The deepest call measured used 248 bytes (a Half-Life run of five weapon
45/// switches in the emulator, every sector popped by the handler, with the stack
46/// painted by [`install`]); the pad engine's comparable handler gets the same 768.
47/// RAM matters to the games that fit tight, and 2 KiB of it sat unused.
48pub const HANDLER_STACK_BYTES: usize = 768;
49/// Fill byte of the handler stack, to measure how much of it was used.
50const STACK_FILL: u8 = 0xa5;
51
52// -------------------------------------------------------------------- drive
53
54/// The CD-ROM controller, through the SDK's register steps.
55pub struct Mmio {
56 time_handler: bool,
57}
58
59impl Mmio {
60 const fn new() -> Self {
61 Mmio {
62 time_handler: false,
63 }
64 }
65}
66
67/// The controller token. The transport owns the controller whenever the
68/// engine runs, which is what [`install`] took the real token for.
69fn token() -> Cd {
70 // SAFETY: a token is a logic guard (see `psx_io::periph`). `install`
71 // holds the real one for as long as the engine may touch the
72 // controller, and hands it back only when the engine is detached or
73 // leased out.
74 unsafe { Cd::steal() }
75}
76
77impl CdHw for Mmio {
78 const TRACE: bool = cfg!(feature = "trace");
79
80 fn issue(&mut self, command: u8, params: &[u8]) -> bool {
81 let mut cd = token();
82 cd.set_irq_enable_mask(0);
83 cd.acknowledge_all_and_reset_parameters();
84 cd.discard_response();
85 cd.reset_parameter_fifo();
86 for ¶m in params {
87 if !cd.wait_parameter_room(PARAM_POLLS) {
88 return false;
89 }
90 cd.send_parameter_byte(param);
91 }
92 cd.send_command_byte(command);
93 cd.set_irq_enable_mask(flag::ALL);
94 true
95 }
96
97 fn interrupt_code(&mut self) -> u8 {
98 token().irq_flag_value()
99 }
100
101 fn error_response(&mut self) -> (u8, u8) {
102 let mut cd = token();
103 let status = cd.read_response_byte();
104 (status, cd.read_response_byte())
105 }
106
107 fn discard_response(&mut self) {
108 token().discard_response();
109 }
110
111 fn acknowledge(&mut self, bits: u8) {
112 token().acknowledge_irq(bits);
113 }
114
115 fn silence_output(&mut self) {
116 token().set_irq_enable_mask(0);
117 }
118
119 fn drop_data_request(&mut self) {
120 token().clear_data_request();
121 }
122
123 unsafe fn pop_sector(&mut self, destination: *mut u32, store_words: usize) -> bool {
124 let mut cd = token();
125 cd.request_data();
126 let mut ready = false;
127 for _ in 0..FIFO_POLLS {
128 if cd.status_register() & index_status::DATA_FIFO_NOT_EMPTY != 0 {
129 ready = true;
130 break;
131 }
132 }
133 if !ready {
134 return false;
135 }
136 for word in 0..crate::SECTOR_WORDS as usize {
137 let b0 = u32::from(cd.read_data_byte());
138 let b1 = u32::from(cd.read_data_byte());
139 let b2 = u32::from(cd.read_data_byte());
140 let b3 = u32::from(cd.read_data_byte());
141 if word < store_words {
142 // SAFETY: the caller guarantees `destination` is valid for
143 // `store_words` word writes (`CdHw::pop_sector`'s contract).
144 unsafe {
145 destination
146 .add(word)
147 .write_volatile(b0 | b1 << 8 | b2 << 16 | b3 << 24);
148 }
149 }
150 }
151 true
152 }
153
154 fn set_source_enabled(&mut self, enabled: bool) {
155 // Only the mask bit: a flag that arrived while the source was closed
156 // must still be pending when it opens, or its sector is lost. (An
157 // acknowledge of the CPU-side bit here dropped sectors in the first
158 // emulator run, because the foreground closes the source around
159 // every call.) Stale bits are cleared by `attach` and by the
160 // preamble of every command.
161 //
162 // psx-rt's handler would acknowledge a CD interrupt that reaches it
163 // pending, behind another wrapper's handler or this one's, so the
164 // source is claimed while it is open, when this wrapper is the one
165 // servicing it. Closed, nobody here services it and the claim is
166 // dropped: code that opens the source itself (a polled read, audio
167 // playback) then has its strays acknowledged by psx-rt as before,
168 // instead of an exception taken again for ever.
169 if enabled {
170 psx_rt::interrupts::claim_interrupt_sources(CD_BIT);
171 irq::set_mask(irq::mask() | CD_BIT);
172 } else {
173 irq::set_mask(irq::mask() & !CD_BIT);
174 psx_rt::interrupts::release_interrupt_sources(CD_BIT);
175 }
176 }
177
178 fn vblank_count(&mut self) -> u32 {
179 psx_rt::interrupts::vblank_count()
180 }
181
182 fn clock(&mut self) -> u16 {
183 if self.time_handler {
184 timers::counter(Timer::Timer2)
185 } else {
186 0
187 }
188 }
189
190 #[cfg(feature = "trace")]
191 fn trace(&mut self, word: u32) {
192 // SAFETY: the ring is written only here, from the handler or from
193 // a foreground section with the CD source closed, so the two never
194 // overlap; readers (tools) only look.
195 unsafe {
196 let n = core::ptr::read_volatile(&raw const PSX_CD_TRACE_N);
197 core::ptr::write_volatile(&raw mut PSX_CD_TRACE_N, n.wrapping_add(1));
198 let slot = (&raw mut PSX_CD_TRACE)
199 .cast::<u32>()
200 .add((n & 127) as usize);
201 core::ptr::write_volatile(slot, word);
202 }
203 }
204}
205
206// ------------------------------------------------------------------- state
207
208struct Global(UnsafeCell<Engine<Mmio>>);
209
210// SAFETY: the engine is reached from one CPU only, from the foreground with
211// the CD source closed or from the interrupt handler, never both at once.
212unsafe impl Sync for Global {}
213
214static ENGINE: Global = Global(UnsafeCell::new(Engine::new(Mmio::new(), Config::DEFAULT)));
215
216/// The controller token while the transport holds it.
217struct TokenSlot(UnsafeCell<Option<Cd>>);
218
219// SAFETY: touched from the foreground only, and only inside `with_engine`
220// sections or before the handler can run, never from the handler.
221unsafe impl Sync for TokenSlot {}
222
223impl TokenSlot {
224 fn is_held(&self) -> bool {
225 // SAFETY: foreground-only access, one thread of control (see `Sync`).
226 unsafe { (*self.0.get()).is_some() }
227 }
228
229 fn put(&self, cd: Cd) {
230 // SAFETY: as `is_held`.
231 unsafe { *self.0.get() = Some(cd) };
232 }
233
234 fn take(&self) -> Option<Cd> {
235 // SAFETY: as `is_held`.
236 unsafe { (*self.0.get()).take() }
237 }
238}
239
240static TOKEN: TokenSlot = TokenSlot(UnsafeCell::new(None));
241
242#[repr(C, align(16))]
243struct Stack([u8; HANDLER_STACK_BYTES]);
244
245/// The handler's private stack, painted with `0xa5` by [`install`] so a tool
246/// can see how much of it a run used ([`handler_stack_unused_bytes`] does the
247/// same from inside).
248#[no_mangle]
249static mut PSX_CD_IRQ_STACK: Stack = Stack([0; HANDLER_STACK_BYTES]);
250/// Where the wrapper saves the interrupted context.
251#[no_mangle]
252static mut PSX_CD_IRQ_CONTEXT: [u32; 34] = [0; 34];
253/// The handler the wrapper hands every exception on to: whatever the vector
254/// led to when [`install`] first ran (psx-rt's, or another wrapper such as the
255/// pad engine's), so the wrappers can be installed in either order. Zero until
256/// then.
257#[no_mangle]
258static mut PSX_CD_NEXT_HANDLER: u32 = 0;
259/// `psx_rt::interrupts::vector_epoch` when the wrapper was put in the vector.
260#[cfg(target_arch = "mips")]
261static mut PSX_CD_EPOCH: u32 = 0;
262
263/// The counters, as one block for tools that read guest memory:
264/// [`StreamStats`] with its field order. Updated after every interrupt and
265/// every foreground call.
266#[no_mangle]
267pub static mut PSX_CD_STATS: StreamStats = StreamStats {
268 irq_count: 0,
269 sectors: 0,
270 discarded_sectors: 0,
271 max_irq_ticks: 0,
272 phase: 0,
273 error: 0,
274 requests_done: 0,
275 requests_cancelled: 0,
276 requests_failed: 0,
277 chained: 0,
278 resumed: 0,
279 rejected: 0,
280};
281
282/// The last 128 controller events (feature `trace`):
283/// `kind << 24 | phase << 16 | (flag or command) << 8 | received & 0xff`.
284#[cfg(feature = "trace")]
285#[no_mangle]
286pub static mut PSX_CD_TRACE: [u32; 128] = [0; 128];
287/// Events recorded so far (feature `trace`); the next slot is `n & 127`.
288#[cfg(feature = "trace")]
289#[no_mangle]
290pub static mut PSX_CD_TRACE_N: u32 = 0;
291
292/// Copy the counters into `PSX_CD_STATS`. Out of line: every wrapper and the
293/// handler end with this, and inlined it was a dozen loads and stores in each.
294#[inline(never)]
295fn publish(engine: &Engine<Mmio>) {
296 // SAFETY: a plain store of a `repr(C)` block that only this module
297 // writes; tools read it from outside the program.
298 unsafe { core::ptr::write_volatile(&raw mut PSX_CD_STATS, engine.stats()) }
299}
300
301/// Start of a foreground section: close the CD source before the engine
302/// reference exists, so the handler cannot be running (or start) while this
303/// one is live. Out of line so each wrapper carries a call, not the sequence.
304#[inline(never)]
305fn enter() -> &'static mut Engine<Mmio> {
306 let mask = irq::mask();
307 irq::set_mask(mask & !CD_BIT);
308 // Closed, nothing here services the source: the claim goes until `leave`
309 // opens it again.
310 psx_rt::interrupts::release_interrupt_sources(CD_BIT);
311 // SAFETY: the source is closed, so the handler (the only other user of
312 // the engine) cannot run until `leave` reopens it, and no other
313 // foreground reference exists because the CPU has one thread of control.
314 let engine = unsafe { &mut *ENGINE.0.get() };
315 engine.note_source_closed();
316 engine
317}
318
319/// End of a foreground section: reopen the source if the engine wants it and
320/// publish the counters.
321#[inline(never)]
322fn leave(engine: &mut Engine<Mmio>) {
323 engine.sync_source();
324 publish(engine);
325}
326
327/// Run `f` on the engine with the CD source closed, then publish the
328/// counters and reopen the source if the engine wants it.
329///
330/// The section's entry and exit are calls, which the compiler cannot move
331/// the engine accesses across (both touch `I_MASK` through volatile stores).
332#[inline(always)]
333fn with_engine<R>(f: impl FnOnce(&mut Engine<Mmio>) -> R) -> R {
334 let engine = enter();
335 let result = f(engine);
336 leave(engine);
337 result
338}
339
340// -------------------------------------------------------------- the wrapper
341
342#[cfg(target_arch = "mips")]
343core::arch::global_asm!(
344 r#"
345 .set noreorder
346 .set noat
347 .section .text.psx_cdstream_irq
348 .globl psx_cdstream_exception_wrapper
349psx_cdstream_exception_wrapper:
350 # Not an interrupt: straight through.
351 mfc0 $26, $13
352 nop
353 andi $26, $26, 0x007c
354 bnez $26, 9f
355 nop
356 # An interrupt, but is the CD source one of the pending, enabled ones?
357 lui $26, {io_hi}
358 lw $27, {i_stat}($26)
359 lw $26, {i_mask}($26)
360 nop
361 and $27, $27, $26
362 andi $27, $27, {cd_bit}
363 beqz $27, 9f
364 nop
365 # Save the interrupted context (everything but $k0/$k1) in our own block.
366 lui $26, %hi({context})
367 addiu $26, $26, %lo({context})
368 sw $1, 0($26)
369 sw $2, 4($26)
370 sw $3, 8($26)
371 sw $4, 12($26)
372 sw $5, 16($26)
373 sw $6, 20($26)
374 sw $7, 24($26)
375 sw $8, 28($26)
376 sw $9, 32($26)
377 sw $10, 36($26)
378 sw $11, 40($26)
379 sw $12, 44($26)
380 sw $13, 48($26)
381 sw $14, 52($26)
382 sw $15, 56($26)
383 sw $16, 60($26)
384 sw $17, 64($26)
385 sw $18, 68($26)
386 sw $19, 72($26)
387 sw $20, 76($26)
388 sw $21, 80($26)
389 sw $22, 84($26)
390 sw $23, 88($26)
391 sw $24, 92($26)
392 sw $25, 96($26)
393 sw $28, 100($26)
394 sw $29, 104($26)
395 sw $30, 108($26)
396 sw $31, 112($26)
397 mfhi $27
398 sw $27, 116($26)
399 mflo $27
400 sw $27, 120($26)
401 # Our own stack; the interrupted one is never written.
402 lui $29, %hi({stack}+{stack_bytes})
403 addiu $29, $29, %lo({stack}+{stack_bytes})
404 addiu $29, $29, -16
405 jal {handler}
406 nop
407 lui $26, %hi({context})
408 addiu $26, $26, %lo({context})
409 lw $27, 116($26)
410 nop
411 mthi $27
412 lw $27, 120($26)
413 nop
414 mtlo $27
415 lw $1, 0($26)
416 lw $2, 4($26)
417 lw $3, 8($26)
418 lw $4, 12($26)
419 lw $5, 16($26)
420 lw $6, 20($26)
421 lw $7, 24($26)
422 lw $8, 28($26)
423 lw $9, 32($26)
424 lw $10, 36($26)
425 lw $11, 40($26)
426 lw $12, 44($26)
427 lw $13, 48($26)
428 lw $14, 52($26)
429 lw $15, 56($26)
430 lw $16, 60($26)
431 lw $17, 64($26)
432 lw $18, 68($26)
433 lw $19, 72($26)
434 lw $20, 76($26)
435 lw $21, 80($26)
436 lw $22, 84($26)
437 lw $23, 88($26)
438 lw $24, 92($26)
439 lw $25, 96($26)
440 lw $28, 100($26)
441 lw $29, 104($26)
442 lw $30, 108($26)
443 lw $31, 112($26)
444 nop
4459:
446 # The handler that was in the vector before this one: psx-rt's (VBlank,
447 # display flip, faults, strays, and the return), or another wrapper that
448 # leads there.
449 lui $26, %hi({next})
450 lw $26, %lo({next})($26)
451 nop
452 jr $26
453 nop
454 .set at
455 .set reorder
456 "#,
457 io_hi = const psx_hw::memory::io::BASE >> 16,
458 i_stat = const psx_hw::irq::I_STAT & 0xFFFF,
459 i_mask = const psx_hw::irq::I_MASK & 0xFFFF,
460 cd_bit = const CD_BIT,
461 stack = sym PSX_CD_IRQ_STACK,
462 stack_bytes = const HANDLER_STACK_BYTES,
463 context = sym PSX_CD_IRQ_CONTEXT,
464 next = sym PSX_CD_NEXT_HANDLER,
465 handler = sym psx_cdstream_interrupt,
466);
467
468// The wrapper reaches both registers with one `lui` of the I/O window and a
469// signed 16-bit offset.
470#[cfg(target_arch = "mips")]
471const _: () = {
472 let window = psx_hw::memory::io::BASE >> 16;
473 assert!(psx_hw::irq::I_STAT >> 16 == window && psx_hw::irq::I_MASK >> 16 == window);
474 assert!(psx_hw::irq::I_STAT & 0xffff < 0x8000 && psx_hw::irq::I_MASK & 0xffff < 0x8000);
475};
476
477#[cfg(target_arch = "mips")]
478extern "C" {
479 fn psx_cdstream_exception_wrapper();
480 #[link_name = "__psx_rt_exception_handler"]
481 fn psx_rt_exception_handler();
482}
483
484/// Called by the wrapper, on the private stack, with CPU interrupts off.
485#[no_mangle]
486extern "C" fn psx_cdstream_interrupt() {
487 // SAFETY: exception entry masks CPU interrupts, and every foreground
488 // access closes the CD source before it takes its reference, so this is
489 // the only live reference to the engine.
490 let engine = unsafe { &mut *ENGINE.0.get() };
491 engine.on_interrupt();
492 publish(engine);
493}
494
495// ------------------------------------------------------------------- set-up
496
497/// Take over the CD-ROM controller: put the exception wrapper in front of
498/// psx-rt's handler and start serving requests.
499///
500/// The controller must be idle and nobody else may use it from now on: if the
501/// boot code read with `SectorReader`, call `SectorReader::release` for the
502/// token and pass it here. The token comes back from [`uninstall`] (to read
503/// with the polled reader again) or [`take_audio_lease`] (to play audio).
504///
505/// If psx-rt's handler is not in the vector yet this installs it first
506/// (`install_vblank_counter`); call `install` after any code that installs it
507/// itself, since that call would overwrite the wrapper.
508///
509/// Returns the token if the transport is already installed.
510///
511/// With [`Config::time_handler`] the transport takes Timer 2 for itself.
512pub fn install(cd: Cd, config: Config) -> Result<(), Cd> {
513 if TOKEN.is_held() {
514 return Err(cd);
515 }
516 TOKEN.put(cd);
517 let mask = irq::mask();
518 irq::set_mask(mask & !CD_BIT);
519 if !psx_rt::interrupts::is_stack_safe_handler_installed() {
520 psx_rt::interrupts::install_vblank_counter();
521 }
522 if config.time_handler {
523 // System clock / 8, free running, no interrupt: wraps after about
524 // 15.5 ms.
525 timers::set_mode(Timer::Timer2, psx_hw::timers::mode::clock_source(2));
526 }
527 paint_stack();
528 install_vector();
529 with_engine(|engine| {
530 engine.hw_mut().time_handler = config.time_handler;
531 engine.configure(config);
532 engine.attach();
533 });
534 Ok(())
535}
536
537fn paint_stack() {
538 // SAFETY: the handler cannot run (the source is closed) and nothing else
539 // uses this stack; plain volatile stores over a static this module owns.
540 unsafe {
541 let stack = (&raw mut PSX_CD_IRQ_STACK).cast::<u8>();
542 for i in 0..HANDLER_STACK_BYTES {
543 stack.add(i).write_volatile(STACK_FILL);
544 }
545 }
546}
547
548#[cfg(target_arch = "mips")]
549fn install_vector() {
550 const EXCEPTION_VECTOR: *mut u32 = 0x8000_0080 as *mut u32;
551 const J_OPCODE: u32 = 0x0800_0000;
552 const J_MASK: u32 = 0xfc00_0000;
553 let wrapper = psx_cdstream_exception_wrapper as *const () as usize as u32;
554 // SAFETY: the general exception vector is two words of kernel RAM. The
555 // handler it leads to now is kept in a static the wrapper reads, before the
556 // vector is rewritten; it is psx-rt's unless something chained in front of
557 // psx-rt (the pad engine's wrapper) is there, and anything that is not a
558 // `j` is replaced by psx-rt's as before. A wrapper that has been installed
559 // since psx-rt last reset the vector is not put in front again: it is already in the chain, and
560 // writing the vector would drop whatever was installed since. The wrapper
561 // switches stacks before it stores anything and hands over with `$sp` as
562 // it found it. The instruction cache is flushed so the CPU fetches the new
563 // words, and the wrapper is declared stack-safe so scratchpad stacks stay
564 // allowed.
565 unsafe {
566 // psx-rt's handler going back into the vector (anything that calls
567 // `install_vblank_counter`) drops this wrapper from the chain; the
568 // epoch says whether that has happened since.
569 let epoch = psx_rt::interrupts::vector_epoch();
570 if core::ptr::read_volatile(&raw const PSX_CD_NEXT_HANDLER) != 0
571 && core::ptr::read_volatile(&raw const PSX_CD_EPOCH) == epoch
572 {
573 return;
574 }
575 core::ptr::write_volatile(&raw mut PSX_CD_EPOCH, epoch);
576 let current = core::ptr::read_volatile(EXCEPTION_VECTOR);
577 let next = if current & J_MASK == J_OPCODE {
578 ((current & !J_MASK) << 2) | 0x8000_0000
579 } else {
580 psx_rt_exception_handler as *const () as usize as u32
581 };
582 core::ptr::write_volatile(&raw mut PSX_CD_NEXT_HANDLER, next);
583 core::ptr::write_volatile(EXCEPTION_VECTOR, J_OPCODE | ((wrapper >> 2) & 0x03ff_ffff));
584 core::ptr::write_volatile(EXCEPTION_VECTOR.add(1), 0);
585 psx_rt::cache::flush_instruction_cache();
586 psx_rt::interrupts::declare_stack_safe_handler(psx_cdstream_exception_wrapper);
587 }
588}
589
590#[cfg(not(target_arch = "mips"))]
591fn install_vector() {}
592
593/// Give the controller back to polled code. Succeeds only when the transport
594/// is idle with nothing queued; call [`cancel_all`] and poll [`is_idle`]
595/// first. The wrapper stays in the exception vector (a few instructions per
596/// exception) but the CD source is closed.
597pub fn uninstall() -> Option<Cd> {
598 let detached = with_engine(Engine::detach);
599 if !detached {
600 return None;
601 }
602 TOKEN.take()
603}
604
605/// Put the transport in the exception vector if it is not there, taking the
606/// controller token itself. For a program that reads with the polled
607/// `SectorReader` and hands only some reads (a streamed asset the frame loop must
608/// not wait for) to the transport: call it before each such read and nothing else
609/// needs tracking.
610///
611/// Idempotent. `install_vblank_counter` puts psx-rt's handler back in the vector,
612/// which drops the wrapper; this notices (by [`psx_rt::interrupts::vector_epoch`])
613/// and installs again, which a program that calls `install_vblank_counter` for
614/// every scene (Half-Life does, for every map) must do. Returns `false` when it
615/// could not: a read is in flight or queued while the vector was reset, or an
616/// audio lease holds the controller. Polled commands may run whenever no request
617/// is queued or active and [`is_idle`] reads true: with
618/// [`IrqMaskPolicy::OnlyWhileBusy`] the CD interrupt source is closed then.
619#[must_use]
620pub fn ensure_installed(config: Config) -> bool {
621 if TOKEN.is_held() {
622 // SAFETY: a plain read of a word only this module writes.
623 let installed = unsafe { core::ptr::read_volatile(&raw const PSX_CD_EPOCH) };
624 if installed == psx_rt::interrupts::vector_epoch() {
625 return true;
626 }
627 if uninstall().is_none() {
628 return false;
629 }
630 } else if owner() == Owner::Audio {
631 return false;
632 }
633 // SAFETY: a token is a logic guard (see `psx_io::periph`). The caller keeps
634 // polled commands away from the controller while a request is queued or
635 // active, which is the only time the transport programs it.
636 let cd = unsafe { Cd::steal() };
637 install(cd, config).is_ok()
638}
639
640/// Cancel every read and wait, for at most `max_vblanks` VBlanks, until the drive
641/// has stopped and nothing is queued. `true` once it has: polled commands can follow.
642///
643/// Cancelling takes effect at the next sector (the handler drops it and pauses the
644/// drive itself), so this normally returns within a few milliseconds; a console
645/// Pause after a long read can take a few frames. The wait also gives up after a
646/// fixed number of polls, so a stopped VBlank clock cannot hang it.
647#[must_use]
648pub fn stop_and_wait(max_vblanks: u32) -> bool {
649 cancel_all();
650 let start = psx_rt::interrupts::vblank_count();
651 let mut polls = 0u32;
652 loop {
653 if is_idle() && queued_count() == 0 {
654 return true;
655 }
656 polls += 1;
657 if polls >= STOP_POLLS
658 || psx_rt::interrupts::vblank_count().wrapping_sub(start) >= max_vblanks
659 {
660 return false;
661 }
662 }
663}
664
665/// Polls of [`is_idle`] before [`stop_and_wait`] gives up whatever the VBlank clock says.
666const STOP_POLLS: u32 = 1 << 18;
667
668// ------------------------------------------------------------ the foreground
669
670/// Change the configuration; it applies from the next event. See
671/// [`Engine::configure`]. ([`Config::time_handler`] is only read by
672/// [`install`].)
673pub fn configure(config: Config) {
674 with_engine(|engine| engine.configure(config));
675}
676
677/// Start the longest-handler measurement over. See
678/// [`Engine::reset_max_irq_ticks`].
679pub fn reset_max_irq_ticks() {
680 with_engine(Engine::reset_max_irq_ticks);
681}
682
683/// Queue a read. See [`Engine::submit`].
684pub fn submit(request: Request) -> Result<Ticket, SubmitError> {
685 with_engine(|engine| engine.submit(request))
686}
687
688/// Cancel a read. See [`Engine::cancel`].
689pub fn cancel(ticket: Ticket) -> bool {
690 with_engine(|engine| engine.cancel(ticket))
691}
692
693/// Cancel everything. See [`Engine::cancel_all`].
694pub fn cancel_all() {
695 with_engine(Engine::cancel_all);
696}
697
698/// Where a read is. See [`Engine::state`].
699pub fn state(ticket: Ticket) -> RequestState {
700 with_engine(|engine| engine.state(ticket))
701}
702
703/// Check for a stalled transfer. See [`Engine::service`].
704pub fn service() {
705 with_engine(Engine::service);
706}
707
708/// Whether the drive is stopped and no read holds it.
709pub fn is_idle() -> bool {
710 with_engine(|engine| engine.is_idle())
711}
712
713/// Reads waiting behind the active one.
714pub fn queued_count() -> usize {
715 with_engine(|engine| engine.queued_count())
716}
717
718/// Who may program the controller.
719pub fn owner() -> Owner {
720 with_engine(|engine| engine.owner())
721}
722
723/// The controller phase.
724pub fn phase() -> Phase {
725 with_engine(|engine| engine.phase())
726}
727
728/// A copy of the counters.
729pub fn stats() -> StreamStats {
730 with_engine(|engine| engine.stats())
731}
732
733// -------------------------------------------------------------------- audio
734
735/// Ask for the drive on behalf of CD-DA or XA playback. See
736/// [`Engine::request_audio_lease`]; once this reads `Granted`, collect the
737/// controller token with [`take_audio_lease`].
738pub fn request_audio_lease() -> LeaseState {
739 with_engine(|engine| engine.request_audio_lease())
740}
741
742/// Where the lease stands.
743pub fn lease_state() -> LeaseState {
744 with_engine(|engine| engine.lease_state())
745}
746
747/// The controller token, once the lease is granted (and not yet taken). The
748/// audio code programs the controller through it until it hands it back with
749/// [`release_audio_lease`]; the CD interrupt source stays closed meanwhile.
750pub fn take_audio_lease() -> Option<Cd> {
751 with_engine(|engine| {
752 if engine.lease_state() != LeaseState::Granted {
753 return None;
754 }
755 TOKEN.take()
756 })
757}
758
759/// End the lease: hand the controller back after the audio code has ended
760/// playback with Pause (not Stop). Gives the token back if there was no
761/// lease to end.
762pub fn release_audio_lease(cd: Cd) -> Result<(), Cd> {
763 with_engine(|engine| {
764 if engine.owner() != Owner::Audio {
765 return Err(cd);
766 }
767 TOKEN.put(cd);
768 engine.release_audio_lease();
769 Ok(())
770 })
771}
772
773/// Take the drive for audio only if it is free right now, in one step: the
774/// controller token if the lease was granted, `None` if a read is in flight.
775/// Nothing is left pending and the read is not aborted, so a read submitted
776/// afterwards is never parked behind a lease granted later. See
777/// [`Engine::try_audio_lease`]; end the lease with [`release_audio_lease`].
778pub fn try_take_audio_lease() -> Option<Cd> {
779 with_engine(|engine| {
780 if engine.try_audio_lease() {
781 TOKEN.take()
782 } else {
783 None
784 }
785 })
786}
787
788/// Withdraw a lease that was asked for and has not been granted. Returns
789/// whether one was pending. See [`Engine::withdraw_audio_lease`].
790pub fn withdraw_audio_lease() -> bool {
791 with_engine(Engine::withdraw_audio_lease)
792}
793
794// --------------------------------------------------------------- diagnostics
795
796/// Bytes of the handler's private stack never touched since [`install`]
797/// painted it. The handler's own frames plus the saved-context area must fit
798/// in the rest; a value near 0 means it overflowed.
799pub fn handler_stack_unused_bytes() -> usize {
800 let mut unused = 0;
801 // SAFETY: plain volatile reads of a static this module owns.
802 unsafe {
803 let stack = (&raw const PSX_CD_IRQ_STACK).cast::<u8>();
804 while unused < HANDLER_STACK_BYTES && stack.add(unused).read_volatile() == STACK_FILL {
805 unused += 1;
806 }
807 }
808 unused
809}