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

psx_rt/
cache.rs

1//! Instruction-cache invalidation, and the only code in the SDK that touches the cache
2//! control register or COP0 Status.IsC.
3//!
4//! # The hazard this module exists for
5//!
6//! Invalidating the instruction cache means changing the cache control register
7//! (`0xFFFE0130`) and isolating the cache (SR.IsC). On a console, doing either while a DMA
8//! channel is moving data makes the CPU's next instruction fetch receive a word of the DMA's
9//! traffic instead of the word from ROM or RAM: a GPU linked-list walk delivered a list word to
10//! the instruction fetch and the program jumped into the weeds (Quake's flush with DMA2 live,
11//! 2026-10-22: six of seven variants dead, the two that flushed with DMA idle or not at all
12//! survived). The BIOS `A(44h) FlushCache` does the same writes and fails the same way. The
13//! emulator cannot reproduce it, so the SDK makes it impossible to write down.
14//!
15//! # How the SDK enforces it
16//!
17//! 1. **Ownership.** The cache control register and SR.IsC are named in this file and nowhere
18//!    else in the SDK (a host test scans every crate for them). There is no public constant, no
19//!    raw accessor and no BIOS flush wrapper. `psx-hw` keeps the register's address as a hardware
20//!    map entry for the emulator; guest code never uses it.
21//! 2. **Proof token.** A flush is only reachable through a [`Quiesced`] token, which
22//!    [`with_dma_quiesced`] hands to its closure after it has masked interrupts and waited
23//!    (bounded, counted) for every DMA channel to go idle, re-checked inside the masked window.
24//!    The token holds `&mut` of every DMA owner token ([`DmaOwners`]), so starting a DMA from
25//!    the closure through any SDK driver does not compile. [`flush_instruction_cache`] and
26//!    [`flush_instruction_cache_range`] are that API with nothing else in the closure.
27//! 3. **Link time.** `cache-gate` (`tools/psoxide-hazard`) disassembles the final image and fails
28//!    the build when code outside this module's routines writes `0xFFFE0130` or sets IsC.
29//! 4. **Emulator.** A tripwire hard-fails a cache-control write that changes bits 13..16, 3 or 7
30//!    while a DMA channel is busy.
31//!
32//! The wait cannot hang: every poll loop is bounded, and a bound that runs out is counted
33//! (`psx_io::diag`, shown on the stop-panel) and the flush still happens, because stale
34//! instructions are the worse failure and a channel wedged for that long is already a fault.
35//!
36//! # The flush itself
37//!
38//! The R3000A's instruction cache is 4 KiB, direct mapped, 256 lines of 16 bytes. psx-spx
39//! ("Memory Control", FFFE0130h, and the COP0 status register's IsC bit 16) describes how
40//! software reaches its tags: with the cache control register in tag test mode and SR.IsC set, a
41//! word store to an address in `0x000..0x1000` writes the tag of the line that address maps to,
42//! instead of memory. Storing zero marks the line invalid.
43//!
44//! The routines:
45//!
46//! - run from the KSEG1 (uncached) alias of their own code, so no instruction is fetched
47//!   through the cache while it changes;
48//! - clear SR before touching the cache control register, so no interrupt can run while the
49//!   scratchpad is unmapped or the cache is isolated;
50//! - select the flush setting, set SR.IsC alone, and zero the tag of every line;
51//! - clear SR.IsC before writing the running setting back, since whether a store to the cache
52//!   control register reaches the port while the cache is isolated isn't documented;
53//! - put the caller's SR back and return.
54
55use core::marker::PhantomData;
56use psx_io::periph::{Cd, GpuDma, MdecDma, OrderingTableClearDma, SpuDma};
57
58/// Polls of the DMA channels' control registers a wait makes before it gives up. A linked-list
59/// walk of a heavy frame lasts a fraction of a display period; this is several periods.
60const DMA_IDLE_SPINS: u32 = 1_000_000;
61
62/// Times a flush lets interrupts back in and waits again because a VBlank kick started a walk
63/// between the idle check and the mask. After that it waits inside the masked window.
64const KICK_RETRIES: u32 = 4;
65
66/// What the DMA gate saw on the way to a quiet bus.
67#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
68pub struct QuiesceReport {
69    /// A DMA channel was busy when the gate was entered.
70    pub busy_at_entry: bool,
71    /// Times a walk started between the idle check and the interrupt mask, so the gate backed
72    /// out and waited again.
73    pub retries: u32,
74    /// Control-register polls that found a channel busy.
75    pub spins: u32,
76    /// A bound ran out: a channel was still busy when the gate gave up and went on.
77    pub timed_out: bool,
78}
79
80/// The hardware the gate looks at; the host tests drive it with a script.
81trait Bus {
82    /// True while any DMA channel has its busy bit set.
83    fn dma_busy(&mut self) -> bool;
84    /// Mask interrupts; returns whether they were enabled.
85    fn irq_off(&mut self) -> bool;
86    /// Put the interrupt state back.
87    fn irq_restore(&mut self, was_enabled: bool);
88}
89
90/// Poll until no channel is busy, at most `limit` busy polls. `true` when idle was seen.
91fn spin_until_idle(bus: &mut impl Bus, limit: u32, spins: &mut u32) -> bool {
92    let mut n = 0u32;
93    while bus.dma_busy() {
94        n += 1;
95        *spins = spins.saturating_add(1);
96        if n >= limit {
97            return false;
98        }
99    }
100    true
101}
102
103/// Run `run` with interrupts masked and every DMA channel idle.
104///
105/// Waits first with interrupts on (a walk takes up to a frame, and VBlank should keep being
106/// served), then masks and checks again: the VBlank handler may have kicked a queued frame in
107/// between. If it did, back out and wait again, a few times, then wait inside the window.
108fn run_when_dma_idle<B: Bus, R>(
109    bus: &mut B,
110    limit: u32,
111    run: impl FnOnce(QuiesceReport) -> R,
112) -> (R, QuiesceReport) {
113    let mut report = QuiesceReport {
114        busy_at_entry: bus.dma_busy(),
115        ..QuiesceReport::default()
116    };
117    let mut tries = 0u32;
118    loop {
119        let idle = spin_until_idle(bus, limit, &mut report.spins);
120        let was = bus.irq_off();
121        if !idle {
122            // The bound ran out with interrupts on; do not wait twice as long again.
123            report.timed_out = true;
124            let r = run(report);
125            bus.irq_restore(was);
126            return (r, report);
127        }
128        if !bus.dma_busy() {
129            let r = run(report);
130            bus.irq_restore(was);
131            return (r, report);
132        }
133        if tries >= KICK_RETRIES {
134            report.timed_out = !spin_until_idle(bus, limit, &mut report.spins);
135            let r = run(report);
136            bus.irq_restore(was);
137            return (r, report);
138        }
139        bus.irq_restore(was);
140        tries += 1;
141        report.retries += 1;
142    }
143}
144
145/// The DMA owner tokens, borrowed for as long as the bus is held quiet.
146///
147/// Every SDK driver that starts a transfer takes one of these tokens by `&mut` (`psx_gpu::Gpu`
148/// owns [`GpuDma`], `psx_spu::Spu` owns [`SpuDma`], and so on; see `psx_io::periph`). A
149/// [`Quiesced`] holds all of them, so inside the closure of [`with_dma_quiesced`] none of those
150/// drivers can be used.
151pub struct DmaOwners<'a> {
152    _gpu: &'a mut GpuDma,
153    _otc: &'a mut OrderingTableClearDma,
154    _mdec: &'a mut MdecDma,
155    _spu: &'a mut SpuDma,
156    _cd: &'a mut Cd,
157}
158
159impl<'a> DmaOwners<'a> {
160    /// Borrow every DMA owner token. A driver that owns its token lends it through its own
161    /// accessor (`Gpu::dma_mut`, `SectorReader::cd_mut`, ...); a program that kept its
162    /// [`Peripherals`](crate::Peripherals) intact uses
163    /// [`Peripherals::dma_owners`](crate::Peripherals::dma_owners).
164    pub fn new(
165        gpu: &'a mut GpuDma,
166        otc: &'a mut OrderingTableClearDma,
167        mdec: &'a mut MdecDma,
168        spu: &'a mut SpuDma,
169        cd: &'a mut Cd,
170    ) -> Self {
171        Self {
172            _gpu: gpu,
173            _otc: otc,
174            _mdec: mdec,
175            _spu: spu,
176            _cd: cd,
177        }
178    }
179}
180
181/// Proof that interrupts are masked and no DMA channel is running, for as long as the borrow of
182/// [`with_dma_quiesced`]'s closure lasts. It cannot be built any other way, and it owns the
183/// right to change the cache.
184pub struct Quiesced<'a> {
185    _owners: DmaOwners<'a>,
186    report: QuiesceReport,
187    _not_send: PhantomData<*mut ()>,
188}
189
190impl Quiesced<'_> {
191    /// What the gate saw on the way in.
192    pub fn report(&self) -> QuiesceReport {
193        self.report
194    }
195
196    /// Invalidate every line of the instruction cache.
197    ///
198    /// Call it after writing instructions to RAM (an exception vector, patched or loaded code)
199    /// so the CPU fetches the new words.
200    #[doc(alias = "FlushCache")]
201    pub fn flush_icache(&mut self) {
202        raw::flush_all();
203    }
204
205    /// Invalidate the instruction-cache lines that hold the bytes `[start, end)`.
206    ///
207    /// For a caller that rewrote a few words of code (a patched call site): the other lines, and
208    /// the working set they hold, stay valid. A range of 4 KiB or more is the whole cache.
209    pub fn flush_icache_range(&mut self, start: u32, end: u32) {
210        if end.wrapping_sub(start) >= 0x1000 {
211            raw::flush_all();
212        } else {
213            raw::flush_range(start, end);
214        }
215    }
216}
217
218/// Run `f` with interrupts masked and every DMA channel idle, and hand it the [`Quiesced`] token
219/// that lets it change the instruction cache.
220///
221/// The gate waits for the channels with interrupts on, masks, checks again, and backs out and
222/// waits if a queued frame was kicked meanwhile (see [`QuiesceReport`]). `owners` stays
223/// borrowed until `f` returns, so the closure cannot start a transfer. Keep `f` short:
224/// VBlank and every other interrupt wait until it returns.
225///
226/// ```
227/// use psx_io::periph::{Cd, GpuDma, MdecDma, OrderingTableClearDma, SpuDma};
228/// use psx_rt::cache::{with_dma_quiesced, DmaOwners};
229///
230/// // SAFETY: a doctest on the host; nothing else holds these tokens.
231/// let (mut gpu, mut otc, mut mdec, mut spu, mut cd) = unsafe {
232///     (GpuDma::steal(), OrderingTableClearDma::steal(), MdecDma::steal(), SpuDma::steal(), Cd::steal())
233/// };
234/// with_dma_quiesced(DmaOwners::new(&mut gpu, &mut otc, &mut mdec, &mut spu, &mut cd), |q| {
235///     q.flush_icache();
236/// });
237/// ```
238///
239/// Starting a DMA inside the closure does not compile, because the token set is borrowed:
240///
241/// ```compile_fail,E0499
242/// use psx_io::periph::{Cd, GpuDma, MdecDma, OrderingTableClearDma, SpuDma};
243/// use psx_rt::cache::{with_dma_quiesced, DmaOwners};
244///
245/// // SAFETY: a doctest on the host; nothing else holds these tokens.
246/// let (mut gpu, mut otc, mut mdec, mut spu, mut cd) = unsafe {
247///     (GpuDma::steal(), OrderingTableClearDma::steal(), MdecDma::steal(), SpuDma::steal(), Cd::steal())
248/// };
249/// let mut table = [0u32; 16];
250/// with_dma_quiesced(DmaOwners::new(&mut gpu, &mut otc, &mut mdec, &mut spu, &mut cd), |q| {
251///     otc.clear_table(&mut table); // starts DMA 6 while the bus is held quiet
252///     q.flush_icache();
253/// });
254/// ```
255pub fn with_dma_quiesced<R>(owners: DmaOwners<'_>, f: impl FnOnce(&mut Quiesced<'_>) -> R) -> R {
256    let mut bus = HwBus;
257    let (r, report) = run_when_dma_idle(&mut bus, DMA_IDLE_SPINS, |report| {
258        let mut quiesced = Quiesced {
259            _owners: owners,
260            report,
261            _not_send: PhantomData,
262        };
263        diag_enter();
264        f(&mut quiesced)
265    });
266    diag_exit(report);
267    r
268}
269
270/// Invalidate every line of the instruction cache, once the DMA channels are idle.
271///
272/// [`with_dma_quiesced`] with a closure that only flushes, so no tokens are needed: the closure
273/// starts no transfer, which is the whole of what the token set proves. Interrupts are off for
274/// the whole time the cache is being changed.
275#[inline(never)]
276#[doc(alias = "FlushCache")]
277pub fn flush_instruction_cache() {
278    with_internal_owners(|q| q.flush_icache());
279}
280
281/// Invalidate the instruction-cache lines that hold the bytes `[start, end)`, once the DMA
282/// channels are idle. A range of 4 KiB or more is the whole cache.
283#[inline(never)]
284pub fn flush_instruction_cache_range(start: u32, end: u32) {
285    with_internal_owners(|q| q.flush_icache_range(start, end));
286}
287
288/// [`with_dma_quiesced`] for the SDK's own closures, which only flush.
289fn with_internal_owners(f: impl FnOnce(&mut Quiesced<'_>)) {
290    // SAFETY: the tokens are zero-sized and only borrowed by the `Quiesced` for the duration of
291    // `f`, which is one of this module's flush calls and starts no transfer; nothing else runs
292    // meanwhile (interrupts are masked and the program is single threaded).
293    let (mut gpu, mut otc, mut mdec, mut spu, mut cd) = unsafe {
294        (
295            GpuDma::steal(),
296            OrderingTableClearDma::steal(),
297            MdecDma::steal(),
298            SpuDma::steal(),
299            Cd::steal(),
300        )
301    };
302    with_dma_quiesced(
303        DmaOwners::new(&mut gpu, &mut otc, &mut mdec, &mut spu, &mut cd),
304        f,
305    );
306}
307
308/// Renamed to [`flush_instruction_cache`].
309#[deprecated(note = "renamed to `flush_instruction_cache`")]
310#[inline(always)]
311pub fn flush_i_cache() {
312    flush_instruction_cache()
313}
314
315// ---------------------------------------------------------------- hardware
316
317/// The value `psx_rt::diag` writes back to the cache control register when a fault is taken
318/// inside a flush.
319#[cfg(target_arch = "mips")]
320#[allow(
321    dead_code,
322    reason = "only the stop-panel reads these two; the handler always uses the bit"
323)]
324pub(crate) const RUNNING_SETTING: u32 = psx_hw::memory::cache_control::RUNNING;
325
326/// COP0 Status.IsC, which the exception handler clears first when a flush faults.
327#[cfg(target_arch = "mips")]
328#[allow(
329    dead_code,
330    reason = "only the stop-panel reads these two; the handler always uses the bit"
331)]
332pub(crate) const ISOLATE_CACHE_BIT: u32 = 1 << 16;
333
334/// The cache control register's address, for the panel's read of it.
335#[cfg(target_arch = "mips")]
336#[allow(
337    dead_code,
338    reason = "only the stop-panel reads these two; the handler always uses the bit"
339)]
340pub(crate) const CONTROL_ADDRESS: u32 = psx_hw::memory::cache_control::ADDR;
341
342#[cfg(target_arch = "mips")]
343struct HwBus;
344
345#[cfg(target_arch = "mips")]
346impl Bus for HwBus {
347    fn dma_busy(&mut self) -> bool {
348        use psx_io::dma::{is_busy, Channel};
349        is_busy(Channel::Gpu)
350            || is_busy(Channel::Cd)
351            || is_busy(Channel::Spu)
352            || is_busy(Channel::MdecIn)
353            || is_busy(Channel::MdecOut)
354            || is_busy(Channel::OrderingTableClear)
355            || is_busy(Channel::Expansion)
356    }
357
358    fn irq_off(&mut self) -> bool {
359        // SAFETY: paired with `irq_restore` in `run_when_dma_idle`, in reverse order.
360        unsafe { crate::critical_section::acquire() }.was_enabled()
361    }
362
363    fn irq_restore(&mut self, was_enabled: bool) {
364        // SAFETY: `was_enabled` came from the matching `irq_off`.
365        unsafe {
366            crate::critical_section::release(crate::critical_section::RestoreState::from_enabled(
367                was_enabled,
368            ));
369        }
370    }
371}
372
373/// The host has no DMA and no cache: the gate is a lock and a no-op.
374#[cfg(not(target_arch = "mips"))]
375struct HwBus;
376
377#[cfg(not(target_arch = "mips"))]
378impl Bus for HwBus {
379    fn dma_busy(&mut self) -> bool {
380        false
381    }
382
383    fn irq_off(&mut self) -> bool {
384        // SAFETY: paired with `irq_restore`.
385        unsafe { crate::critical_section::acquire() }.was_enabled()
386    }
387
388    fn irq_restore(&mut self, was_enabled: bool) {
389        // SAFETY: `was_enabled` came from the matching `irq_off`.
390        unsafe {
391            crate::critical_section::release(crate::critical_section::RestoreState::from_enabled(
392                was_enabled,
393            ));
394        }
395    }
396}
397
398/// Console-diag: record what the flush found, inside the window.
399#[inline(always)]
400fn diag_enter() {
401    #[cfg(all(feature = "console-diag", target_arch = "mips"))]
402    {
403        use psx_io::dma::{control, Channel};
404        let chcr = [
405            control(Channel::MdecIn),
406            control(Channel::MdecOut),
407            control(Channel::Gpu),
408            control(Channel::Cd),
409            control(Channel::Spu),
410            control(Channel::Expansion),
411            control(Channel::OrderingTableClear),
412        ];
413        let sr: u32;
414        // SAFETY: reads COP0 Status; the `nop` covers the MFC0 load delay.
415        unsafe {
416            core::arch::asm!("mfc0 {t}, $12", "nop", t = out(reg) sr, options(nostack, nomem));
417        }
418        // SAFETY: an aligned read of the cache control register, which has no side effect.
419        let cc = unsafe { psx_io::read_u32(CONTROL_ADDRESS) };
420        psx_io::diag::flush_enter(chcr, psx_io::gpu::status().bits(), sr, cc);
421    }
422}
423
424/// Console-diag: count the wait.
425#[inline(always)]
426fn diag_exit(report: QuiesceReport) {
427    psx_io::diag::flush_exit(
428        report.busy_at_entry,
429        report.retries,
430        report.spins,
431        report.timed_out,
432    );
433}
434
435/// The routines that change the cache control register and SR.IsC. Private, and unsafe to call
436/// outside the proof of a [`Quiesced`].
437mod raw {
438    #[cfg(target_arch = "mips")]
439    use psx_hw::memory::cache_control;
440
441    // O32: uses only $t0-$t6 (caller saved), never the stack, returns
442    // through $ra. SR is COP0 register 12.
443    #[cfg(target_arch = "mips")]
444    core::arch::global_asm!(
445        r#"
446    .set noreorder
447    .section .text.__psx_rt_flush_i_cache,"ax",@progbits
448    .globl __psx_rt_flush_i_cache
449    .type __psx_rt_flush_i_cache,@function
450    .p2align 2
451__psx_rt_flush_i_cache:
452    lui   $t0, %hi(.Lpsx_rt_flush_uncached)
453    addiu $t0, $t0, %lo(.Lpsx_rt_flush_uncached)
454    lui   $t1, 0xA000
455    or    $t0, $t0, $t1
456    jr    $t0
457    nop
458.Lpsx_rt_flush_uncached:
459    mfc0  $t2, $12
460    lui   $t3, {port_hi}
461    mtc0  $zero, $12
462    lui   $t4, {flush_hi}
463    ori   $t4, $t4, {flush_lo}
464    sw    $t4, {port_lo}($t3)
465    lui   $t4, 0x0001
466    mtc0  $t4, $12
467    nop
468    nop
469    addu  $t5, $zero, $zero
470    li    $t6, 0x1000
471.Lpsx_rt_flush_line:
472    addiu $t5, $t5, 16
473    bne   $t5, $t6, .Lpsx_rt_flush_line
474    sw    $zero, -16($t5)
475    mtc0  $zero, $12
476    nop
477    nop
478    lui   $t4, {running_hi}
479    ori   $t4, $t4, {running_lo}
480    sw    $t4, {port_lo}($t3)
481    mtc0  $t2, $12
482    nop
483    jr    $ra
484    nop
485    .size __psx_rt_flush_i_cache, . - __psx_rt_flush_i_cache
486    .set reorder
487    "#,
488        port_hi = const cache_control::ADDR >> 16,
489        port_lo = const cache_control::ADDR & 0xFFFF,
490        flush_hi = const cache_control::FLUSH >> 16,
491        flush_lo = const cache_control::FLUSH & 0xFFFF,
492        running_hi = const cache_control::RUNNING >> 16,
493        running_lo = const cache_control::RUNNING & 0xFFFF,
494    );
495
496    // Same routine over a byte range: invalidates only the lines that map the addresses
497    // `[start, end)` (`$a0`, `$a1`; at most 4 KiB are visited, the cache's size). A caller that
498    // changed a few words (one patched call site) pays for their lines instead of the whole cache,
499    // and keeps the rest of the working set warm. Uses `$t0-$t7`, no stack.
500    #[cfg(target_arch = "mips")]
501    core::arch::global_asm!(
502        r#"
503    .set noreorder
504    .section .text.__psx_rt_flush_i_cache_range,"ax",@progbits
505    .globl __psx_rt_flush_i_cache_range
506    .type __psx_rt_flush_i_cache_range,@function
507    .p2align 2
508__psx_rt_flush_i_cache_range:
509    lui   $t0, %hi(.Lpsx_rt_flush_range_uncached)
510    addiu $t0, $t0, %lo(.Lpsx_rt_flush_range_uncached)
511    lui   $t1, 0xA000
512    or    $t0, $t0, $t1
513    jr    $t0
514    nop
515.Lpsx_rt_flush_range_uncached:
516    mfc0  $t2, $12
517    lui   $t3, {port_hi}
518    mtc0  $zero, $12
519    lui   $t4, {flush_hi}
520    ori   $t4, $t4, {flush_lo}
521    sw    $t4, {port_lo}($t3)
522    lui   $t4, 0x0001
523    mtc0  $t4, $12
524    andi  $t5, $a0, 0x0FF0
525    addiu $t6, $a1, -1
526    srl   $t6, $t6, 4
527    srl   $t7, $a0, 4
528    subu  $t6, $t6, $t7
529    addiu $t6, $t6, 1
530.Lpsx_rt_flush_range_line:
531    sw    $zero, 0($t5)
532    addiu $t5, $t5, 16
533    addiu $t6, $t6, -1
534    bnez  $t6, .Lpsx_rt_flush_range_line
535    andi  $t5, $t5, 0x0FFF
536    mtc0  $zero, $12
537    nop
538    nop
539    lui   $t4, {running_hi}
540    ori   $t4, $t4, {running_lo}
541    sw    $t4, {port_lo}($t3)
542    mtc0  $t2, $12
543    nop
544    jr    $ra
545    nop
546    .size __psx_rt_flush_i_cache_range, . - __psx_rt_flush_i_cache_range
547    .set reorder
548    "#,
549        port_hi = const cache_control::ADDR >> 16,
550        port_lo = const cache_control::ADDR & 0xFFFF,
551        flush_hi = const cache_control::FLUSH >> 16,
552        flush_lo = const cache_control::FLUSH & 0xFFFF,
553        running_hi = const cache_control::RUNNING >> 16,
554        running_lo = const cache_control::RUNNING & 0xFFFF,
555    );
556
557    #[cfg(target_arch = "mips")]
558    extern "C" {
559        fn __psx_rt_flush_i_cache_range(start: u32, end: u32);
560        fn __psx_rt_flush_i_cache();
561    }
562
563    /// Invalidate the whole instruction cache.
564    ///
565    /// Only [`super::Quiesced`] calls this: interrupts are masked and no DMA runs.
566    #[cfg(target_arch = "mips")]
567    #[inline(always)]
568    pub(super) fn flush_all() {
569        // SAFETY: the routine clobbers only O32 caller-saved registers ($t0-$t6), uses no
570        // stack, returns through $ra, and leaves SR as it found it and the cache control register
571        // in the running setting. Its only stores land on isolated cache tags or the cache control
572        // port, never on RAM. The caller holds a `Quiesced`, so no DMA is moving data.
573        unsafe { __psx_rt_flush_i_cache() }
574    }
575
576    /// Invalidate the lines of `[start, end)`, a range under 4 KiB.
577    ///
578    /// Only [`super::Quiesced`] calls this.
579    #[cfg(target_arch = "mips")]
580    #[inline(always)]
581    pub(super) fn flush_range(start: u32, end: u32) {
582        // SAFETY: as `flush_all`; it clobbers $t0-$t7.
583        unsafe { __psx_rt_flush_i_cache_range(start, end) }
584    }
585
586    /// Host no-op, so shared code can call it unconditionally.
587    #[cfg(not(target_arch = "mips"))]
588    pub(super) fn flush_all() {}
589
590    /// Host no-op.
591    #[cfg(not(target_arch = "mips"))]
592    pub(super) fn flush_range(_start: u32, _end: u32) {}
593}
594
595#[cfg(test)]
596mod tests {
597    extern crate std;
598
599    use super::*;
600    use std::vec::Vec;
601
602    /// A scripted bus. `busy_polls` busy reads remain; each mask can start a new walk
603    /// (`kicks_on_mask` times, `kick_len` busy reads each); `wedged` never goes idle.
604    struct Script {
605        busy_polls: u32,
606        kicks_on_mask: u32,
607        kick_len: u32,
608        wedged: bool,
609        enabled: bool,
610        masked_polls: u32,
611        unmasked_polls: u32,
612        polls: u32,
613    }
614
615    impl Script {
616        fn idle() -> Self {
617            Self {
618                busy_polls: 0,
619                kicks_on_mask: 0,
620                kick_len: 3,
621                wedged: false,
622                enabled: true,
623                masked_polls: 0,
624                unmasked_polls: 0,
625                polls: 0,
626            }
627        }
628    }
629
630    impl Bus for Script {
631        fn dma_busy(&mut self) -> bool {
632            self.polls += 1;
633            if self.enabled {
634                self.unmasked_polls += 1;
635            } else {
636                self.masked_polls += 1;
637            }
638            if self.wedged {
639                return true;
640            }
641            if self.busy_polls > 0 {
642                self.busy_polls -= 1;
643                return true;
644            }
645            false
646        }
647
648        fn irq_off(&mut self) -> bool {
649            let was = self.enabled;
650            self.enabled = false;
651            if self.kicks_on_mask > 0 {
652                self.kicks_on_mask -= 1;
653                self.busy_polls = self.kick_len;
654            }
655            was
656        }
657
658        fn irq_restore(&mut self, was_enabled: bool) {
659            self.enabled = was_enabled;
660        }
661    }
662
663    /// The script behind a `RefCell`, so the closure the gate runs can look at the bus at the
664    /// moment it is called.
665    struct Shared<'a>(&'a core::cell::RefCell<Script>);
666
667    impl Bus for Shared<'_> {
668        fn dma_busy(&mut self) -> bool {
669            self.0.borrow_mut().dma_busy()
670        }
671        fn irq_off(&mut self) -> bool {
672            self.0.borrow_mut().irq_off()
673        }
674        fn irq_restore(&mut self, was_enabled: bool) {
675            self.0.borrow_mut().irq_restore(was_enabled)
676        }
677    }
678
679    /// Run the gate. When the closure runs, interrupts must be masked and, unless the channel is
680    /// wedged, no walk may be running: the two conditions a flush needs.
681    fn gate(bus: Script, limit: u32) -> (u32, QuiesceReport, Script) {
682        let bus = core::cell::RefCell::new(bus);
683        let runs = core::cell::Cell::new(0u32);
684        let (_, report) = run_when_dma_idle(&mut Shared(&bus), limit, |r| {
685            let b = bus.borrow();
686            assert!(!b.enabled, "the flush must run with interrupts masked");
687            assert!(
688                r.timed_out || b.busy_polls == 0,
689                "the flush must not run while a channel is busy"
690            );
691            runs.set(runs.get() + 1);
692        });
693        (runs.get(), report, bus.into_inner())
694    }
695
696    #[test]
697    fn an_idle_bus_flushes_once_with_interrupts_masked() {
698        let (runs, report, bus) = gate(Script::idle(), 100);
699        assert_eq!(runs, 1);
700        assert_eq!(report, QuiesceReport::default());
701        assert!(bus.enabled, "interrupts are back on afterwards");
702    }
703
704    #[test]
705    fn a_walk_is_waited_out_with_interrupts_on() {
706        let mut bus = Script::idle();
707        bus.busy_polls = 7;
708        let (runs, report, bus) = gate(bus, 100);
709        assert_eq!(runs, 1);
710        assert!(report.busy_at_entry);
711        assert_eq!(
712            report.spins, 6,
713            "the entry probe saw 1 of 7 busy reads, the wait the other 6"
714        );
715        assert!(!report.timed_out);
716        assert_eq!(report.retries, 0);
717        assert_eq!(bus.masked_polls, 1, "inside the window it only re-checks");
718    }
719
720    #[test]
721    fn a_walk_kicked_between_the_check_and_the_mask_is_waited_out_again() {
722        let mut bus = Script::idle();
723        bus.kicks_on_mask = 1;
724        let (runs, report, bus) = gate(bus, 100);
725        assert_eq!(runs, 1);
726        assert_eq!(report.retries, 1);
727        assert!(!report.timed_out);
728        assert_eq!(bus.busy_polls, 0);
729        assert!(bus.enabled);
730    }
731
732    #[test]
733    fn kicks_that_keep_coming_end_in_a_wait_inside_the_window() {
734        let mut bus = Script::idle();
735        bus.kicks_on_mask = 1000;
736        let (runs, report, bus) = gate(bus, 100);
737        assert_eq!(runs, 1);
738        assert_eq!(report.retries, KICK_RETRIES);
739        assert!(!report.timed_out, "the walk ended inside the window");
740        assert_eq!(bus.busy_polls, 0);
741        assert!(bus.masked_polls > 1);
742    }
743
744    #[test]
745    fn a_wedged_channel_is_bounded_counted_and_the_flush_still_runs() {
746        let mut bus = Script::idle();
747        bus.wedged = true;
748        let (runs, report, bus) = gate(bus, 50);
749        assert_eq!(runs, 1);
750        assert!(report.timed_out);
751        assert!(report.spins <= 50);
752        assert!(bus.polls <= 50 + 3, "no unbounded polling: {}", bus.polls);
753        assert!(bus.enabled);
754    }
755
756    #[test]
757    fn a_wedged_channel_behind_endless_kicks_is_still_bounded() {
758        let mut bus = Script::idle();
759        bus.kicks_on_mask = u32::MAX;
760        bus.kick_len = u32::MAX; // each kick is a walk that never ends
761        let (runs, report, bus) = gate(bus, 20);
762        assert_eq!(runs, 1);
763        assert!(report.timed_out);
764        assert!(bus.polls < 20 * (KICK_RETRIES + 3), "polls: {}", bus.polls);
765    }
766
767    #[test]
768    fn interrupt_state_is_restored_exactly() {
769        let mut bus = Script::idle();
770        bus.enabled = false;
771        bus.busy_polls = 3;
772        let (runs, _, bus) = gate(bus, 100);
773        assert_eq!(runs, 1);
774        assert!(
775            !bus.enabled,
776            "a caller that had interrupts off keeps them off"
777        );
778    }
779
780    #[test]
781    fn the_public_api_runs_on_the_host() {
782        flush_instruction_cache();
783        flush_instruction_cache_range(0x8001_0000, 0x8001_0010);
784        flush_instruction_cache_range(0x8001_0000, 0x8001_2000);
785    }
786
787    /// The cache control register and SR.IsC are named in this file only (psx-hw keeps the
788    /// register's address for the emulator). A new use anywhere else in the SDK fails here, and
789    /// in the image at link time (`cache-gate`).
790    #[test]
791    fn nothing_else_in_the_sdk_names_the_cache_control_register_or_isc() {
792        fn visit(dir: &std::path::Path, hits: &mut Vec<std::string::String>) {
793            for entry in std::fs::read_dir(dir).unwrap() {
794                let path = entry.unwrap().path();
795                if path.is_dir() {
796                    if path.file_name().is_some_and(|n| n == "target") {
797                        continue;
798                    }
799                    visit(&path, hits);
800                } else if path.extension().is_some_and(|e| e == "rs") {
801                    let text = std::fs::read_to_string(&path).unwrap();
802                    let is_this_file = path.ends_with("psx-rt/src/cache.rs");
803                    for needle in ["cache_control", "FFFE0130", "FFFE_0130", "IsC"] {
804                        if text.contains(needle) && !is_this_file {
805                            hits.push(std::format!("{}: {needle}", path.display()));
806                        }
807                    }
808                }
809            }
810        }
811        let crates = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
812        let mut hits = Vec::new();
813        visit(&crates, &mut hits);
814        assert!(hits.is_empty(), "outside psx-rt/src/cache.rs: {hits:#?}");
815    }
816}