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

psx_cdstream/
drain.rs

1//! Interrupt-serviced drain of a polled read.
2//!
3//! The polled [`SectorReader`](psx_io::cd::reader::SectorReader) starts a read
4//! (Setloc, ReadN) and then has to look at the controller every few
5//! milliseconds: the drive delivers a sector every 6.7 ms at double speed, keeps
6//! only a few, and hands over the newest when software is late. A frame loop that
7//! looks once per frame, and frames take 50 ms to 200 ms on a busy scene, loses
8//! most of a read that way.
9//!
10//! This module is the cheap fix for a program that already loads with the polled
11//! reader and wants one read to proceed while the frame loop runs: it takes over
12//! only the *popping*. The caller starts the read the way it always did
13//! (`prepare`, `start_read`), calls [`start`], and the CD interrupt handler pops
14//! each sector straight into the destination as it arrives. The caller looks at
15//! [`poll`] once a frame, and when it says [`DrainState::Done`] ends the read the
16//! way it always did (`stop`), with the polled reader's Pause protocol, which has
17//! been proved on a console. Nothing else about the drive changes.
18//!
19//! It is small on purpose, because the programs it is for are tight on RAM: no
20//! command state machine, no queue, no token. The handler, its exception wrapper
21//! and its private stack come to about 1.5 KB. The full transport in the crate
22//! root ([`install`](crate::install), [`submit`](crate::submit)) owns the whole
23//! drive, commands included, and is the one to use when every read can go
24//! through it. Do not use both in one program at the same time: each puts a
25//! wrapper in the exception vector and both would answer a CD interrupt.
26//!
27//! # What the program has to hold to
28//!
29//! - From [`start`] until [`poll`] reports something other than
30//!   [`DrainState::Running`], or [`cancel`], nothing else touches the CD
31//!   controller: no polled command, no polled read.
32//! - The destination is not read or written by anything else until then.
33//! - After `Done` or `Failed` the program ends the read with the polled
34//!   reader's `stop` and calls [`cancel`] (or [`start`] again).
35//! - `install_vblank_counter` takes psx-rt's handler back and drops the
36//!   wrapper; [`start`] puts it in again when it notices, so a program that
37//!   calls it for every scene needs nothing else.
38
39use core::cell::UnsafeCell;
40use psx_hw::cd::{index_status, irq as flag};
41use psx_hw::irq::source;
42use psx_io::irq;
43use psx_io::periph::Cd;
44
45use crate::request::{Request, SECTOR_WORDS};
46
47/// CD interrupt source bit in `I_STAT` and `I_MASK`.
48const CD_BIT: u32 = 1 << source::CDROM;
49/// Status reads to wait for the data FIFO to fill after a sector interrupt.
50const FIFO_POLLS: u32 = 256;
51/// Bytes of private stack the handler runs on. The handler is a flat loop with
52/// a small frame: the deepest call measured used 112 bytes (Half-Life, five
53/// weapon switches in the emulator, stack painted by [`start`]).
54pub const DRAIN_STACK_BYTES: usize = 384;
55/// Fill byte of the handler stack, to measure how much of it was used.
56const STACK_FILL: u8 = 0xa5;
57
58/// Where a drain stands.
59#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60#[non_exhaustive]
61pub enum DrainState {
62    /// Nothing was started, or the last drain was cancelled.
63    Idle,
64    /// Sectors are arriving; `received` have been stored.
65    Running {
66        /// Sectors stored so far.
67        received: u32,
68    },
69    /// Every sector landed. End the read with the polled reader's `stop`.
70    Done,
71    /// The drain gave up; end the read with the polled reader's `stop`.
72    Failed(DrainFailure),
73}
74
75/// Why a drain gave up.
76#[derive(Clone, Copy, Debug, PartialEq, Eq)]
77#[non_exhaustive]
78pub enum DrainFailure {
79    /// The drive answered with an error (INT5).
80    Drive {
81        /// Status byte of the error response.
82        status: u8,
83        /// Error code byte.
84        code: u8,
85    },
86    /// The data FIFO never filled after a sector interrupt.
87    DataNotReady,
88    /// No sector arrived for the timeout given to [`start`].
89    Watchdog,
90}
91
92const IDLE: u32 = 0;
93const RUNNING: u32 = 1;
94const DONE: u32 = 2;
95const FAILED: u32 = 3;
96/// `Drive` failure codes are `0x0500_0000 | status << 8 | code`.
97const FAIL_DRIVE: u32 = 0x0500_0000;
98const FAIL_DATA_NOT_READY: u32 = 0xfa00_0000;
99const FAIL_WATCHDOG: u32 = 0xff00_0000;
100
101struct Drain {
102    destination: *mut u32,
103    request: Request,
104    received: u32,
105    state: u32,
106    error: u32,
107    /// VBlank count at the last progress (start or a stored sector).
108    stamp: u32,
109    timeout: u32,
110}
111
112struct Global(UnsafeCell<Drain>);
113
114// SAFETY: reached from one CPU only, from the foreground with the CD source
115// closed or from the interrupt handler, never both at once.
116unsafe impl Sync for Global {}
117
118// SAFETY: a placeholder that is never read while `state` is `IDLE`; `start` replaces it.
119const NO_REQUEST: Request = unsafe { Request::new_raw(0, 0, core::ptr::null_mut()) };
120
121static DRAIN: Global = Global(UnsafeCell::new(Drain {
122    destination: core::ptr::null_mut(),
123    request: NO_REQUEST,
124    received: 0,
125    state: IDLE,
126    error: 0,
127    stamp: 0,
128    timeout: 0,
129}));
130
131#[repr(C, align(16))]
132struct Stack([u8; DRAIN_STACK_BYTES]);
133
134/// The handler's private stack, painted when [`start`] first puts the wrapper in
135/// the vector so a tool can see how much of it a run used ([`stack_unused_bytes`]).
136#[no_mangle]
137static mut PSX_CDDRAIN_STACK: Stack = Stack([0; DRAIN_STACK_BYTES]);
138/// Where the wrapper saves the interrupted context.
139#[no_mangle]
140static mut PSX_CDDRAIN_CONTEXT: [u32; 34] = [0; 34];
141/// The handler the wrapper hands every exception on to: whatever the vector led
142/// to when [`start`] first put the wrapper in (psx-rt's, or another wrapper
143/// that leads there). Zero until then.
144#[no_mangle]
145static mut PSX_CDDRAIN_NEXT_HANDLER: u32 = 0;
146/// `psx_rt::interrupts::vector_epoch` when the wrapper was put in the vector.
147static mut PSX_CDDRAIN_EPOCH: u32 = 0;
148
149// -------------------------------------------------------------- the wrapper
150
151core::arch::global_asm!(
152    r#"
153    .set noreorder
154    .set noat
155    .section .text.psx_cddrain_irq
156    .globl psx_cddrain_exception_wrapper
157psx_cddrain_exception_wrapper:
158    # Not an interrupt: straight through.
159    mfc0  $26, $13
160    nop
161    andi  $26, $26, 0x007c
162    bnez  $26, 9f
163    nop
164    # An interrupt, but is the CD source one of the pending, enabled ones?
165    lui   $26, {io_hi}
166    lw    $27, {i_stat}($26)
167    lw    $26, {i_mask}($26)
168    nop
169    and   $27, $27, $26
170    andi  $27, $27, {cd_bit}
171    beqz  $27, 9f
172    nop
173    # Save the interrupted context (everything but $k0/$k1) in our own block.
174    lui   $26, %hi({context})
175    addiu $26, $26, %lo({context})
176    sw    $1, 0($26)
177    sw    $2, 4($26)
178    sw    $3, 8($26)
179    sw    $4, 12($26)
180    sw    $5, 16($26)
181    sw    $6, 20($26)
182    sw    $7, 24($26)
183    sw    $8, 28($26)
184    sw    $9, 32($26)
185    sw    $10, 36($26)
186    sw    $11, 40($26)
187    sw    $12, 44($26)
188    sw    $13, 48($26)
189    sw    $14, 52($26)
190    sw    $15, 56($26)
191    sw    $16, 60($26)
192    sw    $17, 64($26)
193    sw    $18, 68($26)
194    sw    $19, 72($26)
195    sw    $20, 76($26)
196    sw    $21, 80($26)
197    sw    $22, 84($26)
198    sw    $23, 88($26)
199    sw    $24, 92($26)
200    sw    $25, 96($26)
201    sw    $28, 100($26)
202    sw    $29, 104($26)
203    sw    $30, 108($26)
204    sw    $31, 112($26)
205    mfhi  $27
206    sw    $27, 116($26)
207    mflo  $27
208    sw    $27, 120($26)
209    # Our own stack; the interrupted one is never written.
210    lui   $29, %hi({stack}+{stack_bytes})
211    addiu $29, $29, %lo({stack}+{stack_bytes})
212    addiu $29, $29, -16
213    jal   {handler}
214    nop
215    lui   $26, %hi({context})
216    addiu $26, $26, %lo({context})
217    lw    $27, 116($26)
218    nop
219    mthi  $27
220    lw    $27, 120($26)
221    nop
222    mtlo  $27
223    lw    $1, 0($26)
224    lw    $2, 4($26)
225    lw    $3, 8($26)
226    lw    $4, 12($26)
227    lw    $5, 16($26)
228    lw    $6, 20($26)
229    lw    $7, 24($26)
230    lw    $8, 28($26)
231    lw    $9, 32($26)
232    lw    $10, 36($26)
233    lw    $11, 40($26)
234    lw    $12, 44($26)
235    lw    $13, 48($26)
236    lw    $14, 52($26)
237    lw    $15, 56($26)
238    lw    $16, 60($26)
239    lw    $17, 64($26)
240    lw    $18, 68($26)
241    lw    $19, 72($26)
242    lw    $20, 76($26)
243    lw    $21, 80($26)
244    lw    $22, 84($26)
245    lw    $23, 88($26)
246    lw    $24, 92($26)
247    lw    $25, 96($26)
248    lw    $28, 100($26)
249    lw    $29, 104($26)
250    lw    $30, 108($26)
251    lw    $31, 112($26)
252    nop
2539:
254    # The handler that was in the vector before this one: psx-rt's (VBlank,
255    # display flip, faults, strays, and the return), or another wrapper that
256    # leads there.
257    lui   $26, %hi({next})
258    lw    $26, %lo({next})($26)
259    nop
260    jr    $26
261    nop
262    .set at
263    .set reorder
264    "#,
265    io_hi = const psx_hw::memory::io::BASE >> 16,
266    i_stat = const psx_hw::irq::I_STAT & 0xFFFF,
267    i_mask = const psx_hw::irq::I_MASK & 0xFFFF,
268    cd_bit = const CD_BIT,
269    stack = sym PSX_CDDRAIN_STACK,
270    stack_bytes = const DRAIN_STACK_BYTES,
271    context = sym PSX_CDDRAIN_CONTEXT,
272    next = sym PSX_CDDRAIN_NEXT_HANDLER,
273    handler = sym psx_cddrain_interrupt,
274);
275
276// The wrapper reaches both registers with one `lui` of the I/O window and a
277// signed 16-bit offset.
278const _: () = {
279    let window = psx_hw::memory::io::BASE >> 16;
280    assert!(psx_hw::irq::I_STAT >> 16 == window && psx_hw::irq::I_MASK >> 16 == window);
281    assert!(psx_hw::irq::I_STAT & 0xffff < 0x8000 && psx_hw::irq::I_MASK & 0xffff < 0x8000);
282};
283
284extern "C" {
285    fn psx_cddrain_exception_wrapper();
286    #[link_name = "__psx_rt_exception_handler"]
287    fn psx_rt_exception_handler();
288}
289
290// ------------------------------------------------------------------ handler
291
292/// Called by the wrapper, on the private stack, with CPU interrupts off.
293#[no_mangle]
294extern "C" fn psx_cddrain_interrupt() {
295    // SAFETY: exception entry masks CPU interrupts, and every foreground access
296    // closes the CD source before it takes its reference, so this is the only
297    // live reference to the drain.
298    let drain = unsafe { &mut *DRAIN.0.get() };
299    let mut cd = token();
300    let code = cd.irq_flag_value();
301    if code == flag::DATA_READY {
302        take_sector(drain, &mut cd);
303    } else if code == flag::ERROR {
304        let status = cd.read_response_byte();
305        let detail = cd.read_response_byte();
306        cd.discard_response();
307        cd.acknowledge_irq(flag::ACK_ALL);
308        fail(
309            drain,
310            FAIL_DRIVE | u32::from(status) << 8 | u32::from(detail),
311        );
312    } else if code != 0 {
313        // The acknowledge or completion of an earlier command arriving late:
314        // nothing to do with the sectors, so answer it and move on.
315        cd.discard_response();
316        cd.acknowledge_irq(code);
317    }
318}
319
320/// Pop the sector the interrupt announced and store it. Past the last one the
321/// drive is still reading until the caller's Pause lands, so the extra sectors
322/// are popped and dropped to keep the controller moving.
323fn take_sector(drain: &mut Drain, cd: &mut Cd) {
324    let wanted = drain.state == RUNNING && drain.received < drain.request.sectors();
325    let (destination, words) = if wanted {
326        let at = drain
327            .destination
328            .wrapping_add(drain.received as usize * SECTOR_WORDS as usize);
329        (at, drain.request.store_words(drain.received))
330    } else {
331        (core::ptr::null_mut(), 0)
332    };
333    // SAFETY: `destination` is the sector's slot in the buffer `start` was given
334    // (valid for `words` words by its contract), and unused when `words` is 0.
335    if !unsafe { pop_sector(cd, destination, words) } {
336        cd.discard_response();
337        cd.acknowledge_irq(flag::ACK_ALL);
338        fail(drain, FAIL_DATA_NOT_READY);
339        return;
340    }
341    cd.discard_response();
342    cd.acknowledge_irq(flag::DATA_READY);
343    if wanted {
344        drain.received += 1;
345        drain.stamp = psx_rt::interrupts::vblank_count();
346        if drain.received == drain.request.sectors() {
347            drain.state = DONE;
348            close_source();
349        }
350    }
351}
352
353fn fail(drain: &mut Drain, error: u32) {
354    if drain.state == RUNNING {
355        drain.state = FAILED;
356        drain.error = error;
357    }
358    close_source();
359}
360
361/// Pop one sector's 2048 bytes from the data FIFO as 512 little-endian words,
362/// storing the first `store_words` of them at `destination` and dropping the
363/// rest. `false` when the FIFO never fills.
364///
365/// # Safety
366///
367/// `destination` must be valid for `store_words` word writes.
368unsafe fn pop_sector(cd: &mut Cd, destination: *mut u32, store_words: usize) -> bool {
369    cd.request_data();
370    let mut ready = false;
371    for _ in 0..FIFO_POLLS {
372        if cd.status_register() & index_status::DATA_FIFO_NOT_EMPTY != 0 {
373            ready = true;
374            break;
375        }
376    }
377    if !ready {
378        return false;
379    }
380    for word in 0..SECTOR_WORDS as usize {
381        let b0 = u32::from(cd.read_data_byte());
382        let b1 = u32::from(cd.read_data_byte());
383        let b2 = u32::from(cd.read_data_byte());
384        let b3 = u32::from(cd.read_data_byte());
385        if word < store_words {
386            // SAFETY: `word < store_words`, inside the caller's contract.
387            unsafe {
388                destination
389                    .add(word)
390                    .write_volatile(b0 | b1 << 8 | b2 << 16 | b3 << 24);
391            }
392        }
393    }
394    true
395}
396
397/// The controller token. The drain only runs while the caller has handed the
398/// controller over, which is what [`start`] documents.
399fn token() -> Cd {
400    // SAFETY: a token is a logic guard (see `psx_io::periph`); the caller of
401    // `start` keeps every other user away while a drain runs.
402    unsafe { Cd::steal() }
403}
404
405// ------------------------------------------------------------- the source
406
407/// Let the CD interrupt source reach the CPU. psx-rt's handler would
408/// acknowledge a CD interrupt that reached it pending, so the source is claimed
409/// while it is open and this wrapper services it.
410fn open_source() {
411    psx_rt::interrupts::claim_interrupt_sources(CD_BIT);
412    irq::set_mask(irq::mask() | CD_BIT);
413}
414
415/// Stop the CD source reaching the CPU and drop the claim, so code that opens it
416/// itself (the polled reader) has its strays acknowledged by psx-rt as before.
417fn close_source() {
418    irq::set_mask(irq::mask() & !CD_BIT);
419    psx_rt::interrupts::release_interrupt_sources(CD_BIT);
420}
421
422/// Run `f` on the drain with the CD source closed, then reopen the source if the
423/// drain is still running.
424fn with_drain<R>(f: impl FnOnce(&mut Drain) -> R) -> R {
425    close_source();
426    // SAFETY: the source is closed, so the handler (the only other user) cannot
427    // run until it is reopened below, and the CPU has one thread of control.
428    let drain = unsafe { &mut *DRAIN.0.get() };
429    let result = f(drain);
430    if drain.state == RUNNING {
431        open_source();
432    }
433    result
434}
435
436// ------------------------------------------------------------- the foreground
437
438/// Hand the sectors of a read the caller has just started to the CD interrupt
439/// handler.
440///
441/// Call it right after `SectorReader::start_read` (or any polled start of a
442/// ReadN stream) returned `true`. `sectors` sectors are stored back to back at
443/// `destination`; with `byte_len` between `(sectors - 1) * 2048 + 1` and
444/// `sectors * 2048` only that many bytes are written (rounded up to a word), so
445/// a transfer never writes past a chunk that does not end on a sector boundary.
446/// With `timeout_vblanks` VBlanks passing without a sector the drain fails
447/// ([`DrainFailure::Watchdog`]).
448///
449/// Returns `false`, starting nothing, if the arguments are empty or
450/// misaligned.
451///
452/// # Safety
453///
454/// `destination` must be word-aligned and valid for writes of the bytes above,
455/// and nothing else may read or write them until the drain has finished or been
456/// cancelled. The caller must hold to the rules in the module documentation:
457/// the controller is the drain's until then.
458pub unsafe fn start(
459    destination: *mut u32,
460    sectors: u32,
461    byte_len: u32,
462    timeout_vblanks: u32,
463) -> bool {
464    if destination.is_null() || destination.align_offset(4) != 0 || sectors == 0 {
465        return false;
466    }
467    install_vector();
468    // SAFETY: the caller vouches for `destination` and `sectors`.
469    let request = unsafe { Request::new_raw(0, sectors, destination) }.with_byte_len(byte_len);
470    close_source();
471    // The read was started by polled code: anything it left pending on the
472    // CPU side must not look like a sector of ours.
473    irq::acknowledge(CD_BIT);
474    with_drain(|drain| {
475        *drain = Drain {
476            destination,
477            request,
478            received: 0,
479            state: RUNNING,
480            error: 0,
481            stamp: psx_rt::interrupts::vblank_count(),
482            timeout: timeout_vblanks,
483        };
484    });
485    true
486}
487
488/// Where the drain is. Also runs the no-progress check: a drain that has
489/// stored nothing for the `timeout_vblanks` given to [`start`] fails.
490#[must_use]
491pub fn poll() -> DrainState {
492    with_drain(|drain| {
493        if drain.state == RUNNING
494            && psx_rt::interrupts::vblank_count().wrapping_sub(drain.stamp) > drain.timeout
495        {
496            drain.state = FAILED;
497            drain.error = FAIL_WATCHDOG;
498        }
499        match drain.state {
500            RUNNING => DrainState::Running {
501                received: drain.received,
502            },
503            DONE => DrainState::Done,
504            FAILED => DrainState::Failed(decode(drain.error)),
505            _ => DrainState::Idle,
506        }
507    })
508}
509
510/// End the drain: the CD source is closed and the state goes back to
511/// [`DrainState::Idle`]. Call it after `Done` or `Failed`, or to give up on a
512/// running one. It does not touch the drive: the caller ends the read with the
513/// polled reader's `stop`.
514pub fn cancel() {
515    close_source();
516    // SAFETY: the source is closed, as in `with_drain`.
517    let drain = unsafe { &mut *DRAIN.0.get() };
518    drain.state = IDLE;
519}
520
521fn decode(error: u32) -> DrainFailure {
522    match error >> 24 {
523        0x05 => DrainFailure::Drive {
524            status: (error >> 8) as u8,
525            code: error as u8,
526        },
527        0xfa => DrainFailure::DataNotReady,
528        _ => DrainFailure::Watchdog,
529    }
530}
531
532fn paint_stack() {
533    // SAFETY: the handler cannot run (the source is closed, or the drain is not
534    // running) and nothing else uses this stack; plain volatile stores over a
535    // static this module owns.
536    unsafe {
537        let stack = (&raw mut PSX_CDDRAIN_STACK).cast::<u8>();
538        for i in 0..DRAIN_STACK_BYTES {
539            stack.add(i).write_volatile(STACK_FILL);
540        }
541    }
542}
543
544/// Bytes of the handler's stack never touched since [`start`] painted it (when it
545/// put the wrapper in the vector).
546#[must_use]
547pub fn stack_unused_bytes() -> usize {
548    let mut unused = 0;
549    // SAFETY: plain volatile reads of a static this module owns.
550    unsafe {
551        let stack = (&raw const PSX_CDDRAIN_STACK).cast::<u8>();
552        while unused < DRAIN_STACK_BYTES && stack.add(unused).read_volatile() == STACK_FILL {
553            unused += 1;
554        }
555    }
556    unused
557}
558
559fn install_vector() {
560    const EXCEPTION_VECTOR: *mut u32 = 0x8000_0080 as *mut u32;
561    const J_OPCODE: u32 = 0x0800_0000;
562    const J_MASK: u32 = 0xfc00_0000;
563    let wrapper = psx_cddrain_exception_wrapper as *const () as usize as u32;
564    // SAFETY: the general exception vector is two words of kernel RAM. The
565    // handler it leads to now is kept in a static the wrapper reads, before the
566    // vector is rewritten; it is psx-rt's unless something chained in front of
567    // psx-rt (the pad engine's wrapper) is there, and anything that is not a `j`
568    // is replaced by psx-rt's. A wrapper installed since psx-rt last reset the
569    // vector is not put in front again: it is already in the chain, and writing
570    // the vector would drop whatever was installed since. The wrapper switches
571    // stacks before it stores anything and hands over with `$sp` as it found it.
572    // The instruction cache is flushed so the CPU fetches the new words, and the
573    // wrapper is declared stack-safe so scratchpad stacks stay allowed.
574    unsafe {
575        let epoch = psx_rt::interrupts::vector_epoch();
576        if core::ptr::read_volatile(&raw const PSX_CDDRAIN_NEXT_HANDLER) != 0
577            && core::ptr::read_volatile(&raw const PSX_CDDRAIN_EPOCH) == epoch
578        {
579            return;
580        }
581        if !psx_rt::interrupts::is_stack_safe_handler_installed() {
582            psx_rt::interrupts::install_vblank_counter();
583        }
584        paint_stack();
585        let epoch = psx_rt::interrupts::vector_epoch();
586        core::ptr::write_volatile(&raw mut PSX_CDDRAIN_EPOCH, epoch);
587        let current = core::ptr::read_volatile(EXCEPTION_VECTOR);
588        let next = if current & J_MASK == J_OPCODE {
589            ((current & !J_MASK) << 2) | 0x8000_0000
590        } else {
591            psx_rt_exception_handler as *const () as usize as u32
592        };
593        core::ptr::write_volatile(&raw mut PSX_CDDRAIN_NEXT_HANDLER, next);
594        core::ptr::write_volatile(EXCEPTION_VECTOR, J_OPCODE | ((wrapper >> 2) & 0x03ff_ffff));
595        core::ptr::write_volatile(EXCEPTION_VECTOR.add(1), 0);
596        psx_rt::cache::flush_instruction_cache();
597        psx_rt::interrupts::declare_stack_safe_handler(psx_cddrain_exception_wrapper);
598    }
599}