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

psx_io/
irq.rs

1//! Interrupt controller: pending and enabled sources.
2//!
3//! The register addresses and source bit positions live in
4//! [`psx_hw::irq`].
5
6use psx_hw::irq as reg;
7
8/// Pending interrupt sources, one bit per [`psx_hw::irq::source`] position.
9#[doc(alias = "I_STAT")]
10#[inline(always)]
11pub fn pending() -> u32 {
12    // SAFETY: I_STAT (`psx_hw::irq::I_STAT`) is the interrupt controller's aligned 32-bit pending register on
13    // every PS1; reading it has no side effects.
14    unsafe { crate::read_u32(reg::I_STAT) }
15}
16
17/// Enabled interrupt sources (the mask register).
18#[doc(alias = "I_MASK")]
19#[inline(always)]
20pub fn mask() -> u32 {
21    // SAFETY: I_MASK (`psx_hw::irq::I_MASK`) is the interrupt controller's aligned 32-bit mask register on
22    // every PS1; reading it has no side effects.
23    unsafe { crate::read_u32(reg::I_MASK) }
24}
25
26/// Acknowledge pending bits by writing `!(bits)` -- the hardware
27/// AND-accumulates, so any bit left 1 in the written value is
28/// preserved, any bit that was 0 is cleared.
29#[inline(always)]
30pub fn acknowledge(bits: u32) {
31    // SAFETY: an aligned 32-bit write to I_STAT (`psx_hw::irq::I_STAT`). The hardware ANDs the value in, so
32    // it can only clear pending bits.
33    unsafe { crate::write_u32(reg::I_STAT, !bits) }
34}
35
36/// Set the mask register (who can interrupt the CPU).
37#[inline(always)]
38pub fn set_mask(bits: u32) {
39    // SAFETY: an aligned 32-bit write to I_MASK (`psx_hw::irq::I_MASK`). It only selects which sources raise
40    // the CPU interrupt line and touches no memory.
41    unsafe { crate::write_u32(reg::I_MASK, bits) }
42}
43
44/// Sources a polled driver must leave enabled in `I_MASK` (see
45/// [`keep_enabled_while_polling`]).
46///
47/// Forced into `.data` rather than left in `.bss`: a chain-loader blob is a
48/// bare image that nothing zeroes a `.bss` for, yet it reads the disc through
49/// the polled reader, which consults this word. Guest-only: the host builds
50/// this crate too, and mach-o spells section names differently.
51#[cfg_attr(target_arch = "mips", link_section = ".data")]
52static mut POLLING_KEEP: u32 = 0;
53
54/// Ask the polled drivers that cut `I_MASK` down to VBlank for the length of a
55/// stream (the CD [`SectorReader`](crate::cd::reader::SectorReader)) to leave
56/// `bits` enabled. For a source whose handler is installed and works alone
57/// through interrupts, such as the pad engine's IRQ7 and root counter 0: cut
58/// from the mask, its transaction never advances for as long as the stream
59/// runs, and the engine abandons and faults one transaction per VBlank. Call
60/// it from foreground code.
61pub fn keep_enabled_while_polling(bits: u32) {
62    // SAFETY: a foreground-only read-modify-write of a word no handler touches.
63    unsafe {
64        let kept = core::ptr::read_volatile(&raw const POLLING_KEEP);
65        core::ptr::write_volatile(&raw mut POLLING_KEEP, kept | bits);
66    }
67}
68
69/// Undo [`keep_enabled_while_polling`] for `bits`.
70pub fn release_polling_keep(bits: u32) {
71    // SAFETY: as in `keep_enabled_while_polling`.
72    unsafe {
73        let kept = core::ptr::read_volatile(&raw const POLLING_KEEP);
74        core::ptr::write_volatile(&raw mut POLLING_KEEP, kept & !bits);
75    }
76}
77
78/// The sources [`keep_enabled_while_polling`] holds enabled.
79pub fn polling_keep() -> u32 {
80    // SAFETY: a volatile aligned read of a word only the foreground writes.
81    unsafe { core::ptr::read_volatile(&raw const POLLING_KEEP) }
82}
83
84/// Clear the CPU's interrupt-enable bit (COP0 `SR.IEc`) and report whether it
85/// was set, so [`restore_cpu_interrupts`] can put it back. Sections nest.
86///
87/// This gates every interrupt at the CPU, whatever [`mask`] says. Use
88/// [`without_interrupts`] unless a guard cannot be a closure.
89///
90/// # Safety
91///
92/// Pair every call with one [`restore_cpu_interrupts`] of its result, in
93/// reverse order. Interrupts enabled early would let a handler run inside a
94/// section whose code assumes it cannot.
95#[inline(always)]
96pub unsafe fn disable_cpu_interrupts() -> bool {
97    #[cfg(target_arch = "mips")]
98    {
99        let sr: u32;
100        // Read SR, clear IEc, write it back. The nop after MFC0 covers its
101        // load delay. The two nops after MTC0 let the write settle before the
102        // section's first instruction. An interrupt taken between the read and
103        // the write returns through RFE with IEc as it was, and psx-rt's
104        // handler leaves the rest of SR alone, so the write-back loses nothing.
105        // SAFETY: COP0 SR read-modify-write of the interrupt-enable bit only.
106        unsafe {
107            core::arch::asm!(
108                "mfc0 $8, $12",
109                "nop",
110                // Clear bit 0 (IEc) with a shift pair: no mask register.
111                "srl $9, $8, 1",
112                "sll $9, $9, 1",
113                "mtc0 $9, $12",
114                "nop",
115                "nop",
116                out("$8") sr,
117                out("$9") _,
118                options(nostack),
119            );
120        }
121        sr & 1 != 0
122    }
123    // The host has no interrupts to mask.
124    #[cfg(not(target_arch = "mips"))]
125    false
126}
127
128/// Put back the interrupt-enable bit [`disable_cpu_interrupts`] found.
129///
130/// # Safety
131///
132/// `was_enabled` must be the result of the matching
133/// [`disable_cpu_interrupts`], and every section entered after it must
134/// already have ended.
135#[inline(always)]
136pub unsafe fn restore_cpu_interrupts(was_enabled: bool) {
137    #[cfg(target_arch = "mips")]
138    if was_enabled {
139        // SAFETY: re-enables interrupts only when the matching disable found
140        // them enabled.
141        unsafe {
142            core::arch::asm!(
143                "mfc0 $8, $12",
144                "nop",
145                "ori $8, $8, 1",
146                "mtc0 $8, $12",
147                out("$8") _,
148                options(nostack),
149            );
150        }
151    }
152    #[cfg(not(target_arch = "mips"))]
153    let _ = was_enabled;
154}
155
156/// Run `f` with CPU interrupts masked, then restore the previous state.
157///
158/// For a read-modify-write of a register an interrupt handler also writes
159/// (the DMA enable register, `DPCR`). Keep `f` short: VBlank waits until it
160/// returns.
161#[inline(always)]
162pub fn without_interrupts<R>(f: impl FnOnce() -> R) -> R {
163    // SAFETY: restored below, after `f` returns. A panic in `f` halts the
164    // console, so the section is never left half-open with code running.
165    let was_enabled = unsafe { disable_cpu_interrupts() };
166    let result = f();
167    // SAFETY: pairs the disable above; nested sections inside `f` have ended.
168    unsafe { restore_cpu_interrupts(was_enabled) };
169    result
170}
171
172/// Renamed to [`acknowledge`].
173#[deprecated(note = "renamed to `acknowledge`")]
174#[inline(always)]
175pub fn ack(bits: u32) {
176    acknowledge(bits)
177}
178
179/// Moved to [`psx_hw::irq::source`].
180pub mod source {
181    use psx_hw::irq::source as bit;
182
183    /// Moved to [`psx_hw::irq::source::CDROM`].
184    #[deprecated(note = "moved to `psx_hw::irq::source::CDROM`")]
185    pub const CDROM: u32 = bit::CDROM;
186    /// Moved to [`psx_hw::irq::source::DMA`].
187    #[deprecated(note = "moved to `psx_hw::irq::source::DMA`")]
188    pub const DMA: u32 = bit::DMA;
189    /// Moved to [`psx_hw::irq::source::SPU`].
190    #[deprecated(note = "moved to `psx_hw::irq::source::SPU`")]
191    pub const SPU: u32 = bit::SPU;
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197
198    #[test]
199    fn a_section_runs_its_closure_once_and_returns_its_value() {
200        let mut runs = 0;
201        let value = without_interrupts(|| {
202            runs += 1;
203            without_interrupts(|| 7)
204        });
205        assert_eq!((runs, value), (1, 7));
206    }
207}
208
209#[cfg(test)]
210mod polling_keep_tests {
211    use super::*;
212
213    #[test]
214    fn sources_kept_for_polled_drivers_are_added_and_released_independently() {
215        assert_eq!(polling_keep(), 0);
216        keep_enabled_while_polling(0x90);
217        keep_enabled_while_polling(0x10);
218        assert_eq!(polling_keep(), 0x90);
219        release_polling_keep(0x80);
220        assert_eq!(polling_keep(), 0x10);
221        release_polling_keep(0x10);
222        assert_eq!(polling_keep(), 0);
223    }
224}