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

psx_pad/
console.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2//! The console side of the pad engine: the serial port and a timer behind
3//! [`Hw`], the one global [`Engine`], and the exception wrapper that feeds it.
4//!
5//! Everything here is for the target. (It compiles on the host so the
6//! documentation shows it; none of it may run there.)
7//!
8//! # Interrupt path
9//!
10//! The wrapper sits in the general exception vector in front of whatever
11//! handler was there when [`install`] ran (psx-rt's, or a wrapper such as
12//! psx-cdstream's that leads to it). For an interrupt with VBlank, the
13//! controller (IRQ7) or root counter 0 pending it saves the interrupted CPU
14//! context, switches to a private stack, runs the engine's events, restores
15//! the context and jumps on to the next handler either way, so the VBlank
16//! counter, the display flip and the fault handling run exactly as before.
17//! The wrapper never touches the interrupted stack, which is what makes it
18//! safe with a scratchpad stack; [`install`] declares it so.
19//!
20//! # Foreground path
21//!
22//! Every foreground call runs with CPU interrupts off for its few
23//! instructions, so it never overlaps a handler. Reading a snapshot takes no
24//! lock at all ([`snapshot`]).
25//!
26//! # Memory cards
27//!
28//! The engine owns the port token. A card driver borrows it as a [`Lease`],
29//! which keeps the engine off the port until it is dropped.
30
31use crate::engine::{Config, Engine, Hw, Owner, PortReading, Published, Snapshot, Stats};
32use crate::{AnalogRequirement, PadState, Rumble};
33use core::cell::UnsafeCell;
34use core::ops::{Deref, DerefMut};
35use psx_hw::irq::source;
36use psx_hw::sio::sio0::{self, ctrl, stat};
37use psx_hw::timers::mode;
38use psx_io::controller_port::{Port, Transport};
39use psx_io::irq;
40use psx_io::periph::ControllerPort;
41use psx_io::timers::{self, Timer};
42
43/// The VBlank, controller and root counter 0 sources in `I_STAT` and `I_MASK`.
44const VBLANK_BIT: u32 = 1 << source::VBLANK;
45const SIO_BIT: u32 = 1 << source::CONTROLLER;
46const TIMER_BIT: u32 = 1 << source::TIMER0;
47const SOURCES: u32 = VBLANK_BIT | SIO_BIT | TIMER_BIT;
48/// Bytes of private stack the handler runs on.
49pub const HANDLER_STACK_BYTES: usize = 768;
50/// Fill byte of the handler stack, to measure how much of it was used.
51const STACK_FILL: u8 = 0xa5;
52/// Status reads the handler waits for an `/ACK` pulse to end.
53const ACK_RELEASE_SPINS: u32 = 256;
54/// VBlanks [`lease`] waits for the engine to go idle before taking the port.
55const LEASE_PATIENCE_VBLANKS: u32 = 3;
56/// Attempts [`lease`] makes before it stops counting on VBlanks, which never
57/// arrive for a caller that has interrupts off. Each is a few dozen cycles, so
58/// this is several milliseconds, longer than a round on the wire.
59const LEASE_PATIENCE_ATTEMPTS: u32 = 4_000;
60
61// -------------------------------------------------------------------- port
62
63/// The serial port and root counter 0, through the SDK's register steps.
64pub struct Mmio {
65    /// A deadline is armed and has not been cancelled.
66    armed: bool,
67    /// Its length in CPU cycles.
68    target: u16,
69}
70
71impl Mmio {
72    const fn new() -> Self {
73        Mmio {
74            armed: false,
75            target: 0,
76        }
77    }
78}
79
80/// The port token. The engine owns the port whenever it runs, which is what
81/// [`install`] took the real token for.
82fn token() -> ControllerPort {
83    // SAFETY: a token is a logic guard (see `psx_io::periph`). `install` holds
84    // the real one for as long as the engine may touch the port, and hands it
85    // back only when the engine is idle or leased out.
86    unsafe { ControllerPort::steal() }
87}
88
89impl Hw for Mmio {
90    fn status(&mut self) -> u32 {
91        token().status()
92    }
93
94    fn select(&mut self, port: Port, ack_irq: bool) {
95        token().select_with(port, ack_irq);
96    }
97
98    fn deselect(&mut self) {
99        token().deselect();
100    }
101
102    fn reset_uart(&mut self) {
103        token().reset();
104    }
105
106    fn drain_receive(&mut self) {
107        token().drain_receive();
108    }
109
110    fn transmit(&mut self, byte: u8) {
111        token().transmit(byte);
112    }
113
114    fn receive(&mut self) -> u8 {
115        token().receive()
116    }
117
118    fn wait_ack_release(&mut self) -> bool {
119        token().wait_status_clear(stat::DSR_LEVEL, ACK_RELEASE_SPINS)
120    }
121
122    fn clear_ack_latch(&mut self, port: Option<Port>, ack_irq: bool) {
123        let selected = match port {
124            Some(port) => sio0::selected_ctrl(port.is_two(), ack_irq),
125            None => 0,
126        };
127        token().set_control(selected | ctrl::ACK);
128    }
129
130    fn arm_deadline(&mut self, cycles: u32) {
131        let target = cycles.clamp(1, u32::from(u16::MAX)) as u16;
132        self.armed = true;
133        if target != self.target {
134            self.target = target;
135            timers::set_target(Timer::Timer0, target);
136        }
137        // System clock, interrupt once at the target. Writing the mode
138        // restarts the count from zero.
139        timers::set_mode(Timer::Timer0, mode::IRQ_AT_TARGET);
140    }
141
142    fn cancel_deadline(&mut self) {
143        self.armed = false;
144        timers::set_mode(Timer::Timer0, 0);
145    }
146
147    fn deadline_expired(&mut self) -> bool {
148        // An interrupt raised by a deadline that was since replaced or
149        // cancelled finds the restarted count below the new target.
150        self.armed && timers::counter(Timer::Timer0) >= self.target
151    }
152}
153
154// ------------------------------------------------------------------- state
155
156struct Global(UnsafeCell<Engine<'static, Mmio>>);
157
158// SAFETY: the engine is reached from one CPU only, from the foreground with
159// CPU interrupts off or from the exception wrapper, never both at once.
160unsafe impl Sync for Global {}
161
162/// Where the engine publishes; the foreground reads it without a lock.
163static PUBLISHED: Published = Published::new();
164
165static ENGINE: Global = Global(UnsafeCell::new(Engine::new(
166    Mmio::new(),
167    &PUBLISHED,
168    Config::DEFAULT,
169)));
170
171/// The port token while the engine holds it.
172struct TokenSlot(UnsafeCell<Option<ControllerPort>>);
173
174// SAFETY: touched from the foreground only, and only inside `with_engine`
175// sections or before the wrapper can run, never from the handler.
176unsafe impl Sync for TokenSlot {}
177
178static TOKEN: TokenSlot = TokenSlot(UnsafeCell::new(None));
179
180#[repr(C, align(16))]
181struct Stack([u8; HANDLER_STACK_BYTES]);
182
183/// The handler's private stack, painted by [`install`] so a tool can see how
184/// much of it a run used ([`handler_stack_unused_bytes`] does the same from
185/// inside).
186#[no_mangle]
187static mut PSX_PAD_IRQ_STACK: Stack = Stack([0; HANDLER_STACK_BYTES]);
188/// Where the wrapper saves the interrupted context.
189#[no_mangle]
190static mut PSX_PAD_IRQ_CONTEXT: [u32; 34] = [0; 34];
191/// The handler the wrapper hands every exception on to: whatever the vector
192/// led to when [`install`] ran.
193#[no_mangle]
194static mut PSX_PAD_NEXT_HANDLER: u32 = 0;
195/// `psx_rt::interrupts::vector_epoch` when the wrapper was put in the vector.
196#[cfg(target_arch = "mips")]
197static mut PSX_PAD_EPOCH: u32 = 0;
198/// Set by [`install`], cleared by [`uninstall`].
199static mut INSTALLED: bool = false;
200
201/// Run `f` on the engine with CPU interrupts off.
202#[inline(always)]
203fn with_engine<R>(f: impl FnOnce(&mut Engine<'static, Mmio>) -> R) -> R {
204    irq::without_interrupts(|| {
205        // SAFETY: CPU interrupts are off, so the wrapper (the only other user
206        // of the engine) cannot run, and the CPU has one thread of control, so
207        // no other foreground reference exists.
208        f(unsafe { &mut *ENGINE.0.get() })
209    })
210}
211
212// -------------------------------------------------------------- the wrapper
213
214#[cfg(target_arch = "mips")]
215core::arch::global_asm!(
216    r#"
217    .set noreorder
218    .set noat
219    .section .text.psx_pad_irq
220    .globl psx_pad_exception_wrapper
221psx_pad_exception_wrapper:
222    # Not an interrupt: straight through.
223    mfc0  $26, $13
224    nop
225    andi  $26, $26, 0x007c
226    bnez  $26, 9f
227    nop
228    # An interrupt, but is VBlank, the controller or counter 0 one of the
229    # pending, enabled sources?
230    lui   $26, {io_hi}
231    lw    $27, {i_stat}($26)
232    lw    $26, {i_mask}($26)
233    nop
234    and   $27, $27, $26
235    andi  $27, $27, {sources}
236    beqz  $27, 9f
237    nop
238    # Save the interrupted context in our own block: every register the
239    # handler may change. $16-$23 and $30 are callee-saved, so the handler
240    # returns them as it found them; $k0/$k1 are the exception handler's own.
241    lui   $26, %hi({context})
242    addiu $26, $26, %lo({context})
243    sw    $1, 0($26)
244    sw    $2, 4($26)
245    sw    $3, 8($26)
246    sw    $4, 12($26)
247    sw    $5, 16($26)
248    sw    $6, 20($26)
249    sw    $7, 24($26)
250    sw    $8, 28($26)
251    sw    $9, 32($26)
252    sw    $10, 36($26)
253    sw    $11, 40($26)
254    sw    $12, 44($26)
255    sw    $13, 48($26)
256    sw    $14, 52($26)
257    sw    $15, 56($26)
258    sw    $24, 92($26)
259    sw    $25, 96($26)
260    sw    $28, 100($26)
261    sw    $29, 104($26)
262    sw    $31, 112($26)
263    mfhi  $27
264    sw    $27, 116($26)
265    mflo  $27
266    sw    $27, 120($26)
267    # Our own stack; the interrupted one is never written.
268    lui   $29, %hi({stack}+{stack_bytes})
269    addiu $29, $29, %lo({stack}+{stack_bytes})
270    addiu $29, $29, -16
271    jal   {handler}
272    nop
273    lui   $26, %hi({context})
274    addiu $26, $26, %lo({context})
275    lw    $27, 116($26)
276    nop
277    mthi  $27
278    lw    $27, 120($26)
279    nop
280    mtlo  $27
281    lw    $1, 0($26)
282    lw    $2, 4($26)
283    lw    $3, 8($26)
284    lw    $4, 12($26)
285    lw    $5, 16($26)
286    lw    $6, 20($26)
287    lw    $7, 24($26)
288    lw    $8, 28($26)
289    lw    $9, 32($26)
290    lw    $10, 36($26)
291    lw    $11, 40($26)
292    lw    $12, 44($26)
293    lw    $13, 48($26)
294    lw    $14, 52($26)
295    lw    $15, 56($26)
296    lw    $24, 92($26)
297    lw    $25, 96($26)
298    lw    $28, 100($26)
299    lw    $29, 104($26)
300    lw    $31, 112($26)
301    nop
3029:
303    # The handler that was in the vector before this one: psx-rt's, or a
304    # wrapper that leads to it.
305    lui   $26, %hi({next})
306    lw    $26, %lo({next})($26)
307    nop
308    jr    $26
309    nop
310    .set at
311    .set reorder
312    "#,
313    io_hi = const psx_hw::memory::io::BASE >> 16,
314    i_stat = const psx_hw::irq::I_STAT & 0xFFFF,
315    i_mask = const psx_hw::irq::I_MASK & 0xFFFF,
316    sources = const SOURCES,
317    stack = sym PSX_PAD_IRQ_STACK,
318    stack_bytes = const HANDLER_STACK_BYTES,
319    context = sym PSX_PAD_IRQ_CONTEXT,
320    next = sym PSX_PAD_NEXT_HANDLER,
321    handler = sym psx_pad_interrupt,
322);
323
324// The wrapper reaches both registers with one `lui` of the I/O window and a
325// signed 16-bit offset.
326#[cfg(target_arch = "mips")]
327const _: () = {
328    let window = psx_hw::memory::io::BASE >> 16;
329    assert!(psx_hw::irq::I_STAT >> 16 == window && psx_hw::irq::I_MASK >> 16 == window);
330    assert!(psx_hw::irq::I_STAT & 0xffff < 0x8000 && psx_hw::irq::I_MASK & 0xffff < 0x8000);
331    assert!(SOURCES <= 0xffff);
332};
333
334#[cfg(target_arch = "mips")]
335extern "C" {
336    fn psx_pad_exception_wrapper();
337}
338
339/// Called by the wrapper, on the private stack, with CPU interrupts off.
340#[no_mangle]
341extern "C" fn psx_pad_interrupt() {
342    let pending = irq::pending() & irq::mask() & SOURCES;
343    // The controller and the timer are acknowledged before the engine runs,
344    // so an interrupt they raise meanwhile is not lost. VBlank is left for
345    // psx-rt's handler, which acknowledges it after the engine has seen it.
346    irq::acknowledge(pending & (SIO_BIT | TIMER_BIT));
347    // SAFETY: exception entry masks CPU interrupts, and every foreground
348    // access runs with them off, so this is the only live reference to the
349    // engine.
350    let engine = unsafe { &mut *ENGINE.0.get() };
351    if pending & VBLANK_BIT != 0 {
352        engine.on_vblank();
353    }
354    // An acknowledgement that landed with a deadline is handled first: the
355    // byte it ends then re-arms the deadline, which retires the old one.
356    if pending & SIO_BIT != 0 {
357        engine.on_ack();
358    }
359    if pending & TIMER_BIT != 0 {
360        engine.on_deadline();
361    }
362}
363
364// ------------------------------------------------------------------- set-up
365
366#[cfg(target_arch = "mips")]
367const EXCEPTION_VECTOR: *mut u32 = 0x8000_0080 as *mut u32;
368#[cfg(target_arch = "mips")]
369const J_OPCODE: u32 = 0x0800_0000;
370#[cfg(target_arch = "mips")]
371const J_MASK: u32 = 0xfc00_0000;
372
373#[cfg(target_arch = "mips")]
374fn install_vector() -> bool {
375    // SAFETY: the general exception vector is two words of kernel RAM. The
376    // word read is the handler this one chains to; it is kept in a static the
377    // wrapper reads, before the vector is rewritten, and only a `j` is
378    // accepted since anything else cannot be chained to. The wrapper switches
379    // stacks before it stores anything, and hands over to the next handler
380    // with `$sp` as it found it. The instruction cache is flushed so the CPU
381    // fetches the new words, and the wrapper is declared stack-safe so
382    // scratchpad stacks stay allowed.
383    unsafe {
384        // Installed before (and uninstalled since): already in the chain,
385        // unless psx-rt's handler went back into the vector since, which
386        // drops every wrapper in front of it (the epoch counts those).
387        let epoch = psx_rt::interrupts::vector_epoch();
388        if core::ptr::read_volatile(&raw const PSX_PAD_NEXT_HANDLER) != 0
389            && core::ptr::read_volatile(&raw const PSX_PAD_EPOCH) == epoch
390        {
391            return true;
392        }
393        let current = core::ptr::read_volatile(EXCEPTION_VECTOR);
394        if current & J_MASK != J_OPCODE {
395            return false;
396        }
397        let next = ((current & !J_MASK) << 2) | 0x8000_0000;
398        let wrapper = psx_pad_exception_wrapper as *const () as usize as u32;
399        core::ptr::write_volatile(&raw mut PSX_PAD_EPOCH, epoch);
400        core::ptr::write_volatile(&raw mut PSX_PAD_NEXT_HANDLER, next);
401        core::ptr::write_volatile(EXCEPTION_VECTOR, J_OPCODE | ((wrapper >> 2) & !J_MASK));
402        core::ptr::write_volatile(EXCEPTION_VECTOR.add(1), 0);
403        psx_rt::cache::flush_instruction_cache();
404        psx_rt::interrupts::declare_stack_safe_handler(psx_pad_exception_wrapper);
405    }
406    true
407}
408
409#[cfg(not(target_arch = "mips"))]
410fn install_vector() -> bool {
411    true
412}
413
414fn paint_stack() {
415    // SAFETY: plain volatile writes to a static this module owns, before the
416    // wrapper can run.
417    unsafe {
418        let stack = (&raw mut PSX_PAD_IRQ_STACK).cast::<u8>();
419        for i in 0..HANDLER_STACK_BYTES {
420            stack.add(i).write_volatile(STACK_FILL);
421        }
422    }
423}
424
425/// Take over the controller port: put the exception wrapper in front of the
426/// handler the vector leads to and start polling on every VBlank.
427///
428/// From here the port belongs to the engine, so nothing may poll it
429/// synchronously; a memory card borrows it through [`lease`]. It chains to
430/// whatever the vector led to, and psx-cdstream's wrapper does the same, so
431/// the two can be installed in either order. Ask for analog mode with the synchronous
432/// `require_analog_on` before installing, or with [`request_analog`] after.
433///
434/// If psx-rt's handler is not in the vector yet this installs it first
435/// (`install_vblank_counter`). The root counter 0 is the engine's from here.
436///
437/// Returns the token if the engine is already installed, or if the vector
438/// holds something that cannot be chained to.
439pub fn install(port: ControllerPort, config: Config) -> Result<(), ControllerPort> {
440    // SAFETY: foreground, before the wrapper can run; the flag is read here
441    // and set below under the same condition.
442    if unsafe { (*TOKEN.0.get()).is_some() } {
443        return Err(port);
444    }
445    if !psx_rt::interrupts::is_stack_safe_handler_installed() {
446        psx_rt::interrupts::install_vblank_counter();
447    }
448    let masked = irq::mask() & !(SIO_BIT | TIMER_BIT);
449    irq::set_mask(masked);
450    paint_stack();
451    if !install_vector() {
452        return Err(port);
453    }
454    // SAFETY: foreground, with the SIO and counter sources masked and the
455    // engine idle; see above.
456    unsafe { *TOKEN.0.get() = Some(port) };
457    let mut port_io = token();
458    port_io.deselect();
459    port_io.drain_receive();
460    timers::set_mode(Timer::Timer0, 0);
461    irq::acknowledge(SIO_BIT | TIMER_BIT);
462    with_engine(|engine| {
463        *engine = Engine::new(Mmio::new(), &PUBLISHED, config);
464        engine.publish_readings();
465    });
466    irq::set_mask(irq::mask() | SIO_BIT | TIMER_BIT | VBLANK_BIT);
467    // A polled CD read cuts `I_MASK` down to VBlank for its whole stream; the
468    // engine runs on these two sources alone, so it asks to keep them.
469    irq::keep_enabled_while_polling(SIO_BIT | TIMER_BIT);
470    // psx-rt's handler would acknowledge these as strays if they reach it
471    // pending, behind another wrapper's handler or this one's.
472    psx_rt::interrupts::claim_interrupt_sources(SIO_BIT | TIMER_BIT);
473    // SAFETY: foreground; written here and in `uninstall` only.
474    unsafe { core::ptr::write_volatile(&raw mut INSTALLED, true) };
475    Ok(())
476}
477
478/// Give the port back to synchronous code. Waits for the transaction in
479/// flight, as [`lease`] does (and abandons it after the same patience), then
480/// closes the controller and counter 0 sources. The wrapper stays in the
481/// exception vector, chained, a few instructions per exception; [`install`]
482/// finds it there and takes the port again.
483///
484/// `None` when the engine is not installed or a [`Lease`] holds the port: a
485/// card transaction is not the engine's to cut short.
486pub fn uninstall() -> Option<ControllerPort> {
487    if !installed_flag() {
488        return None;
489    }
490    // Leave nothing spinning in a pad that is about to be polled by something
491    // that does not know about it.
492    if with_engine(|engine| engine.motors_requested()) {
493        stop_motors();
494    }
495    let start = psx_rt::interrupts::vblank_count();
496    let mut attempts = 0u32;
497    loop {
498        let claimed = with_engine(|engine| {
499            if engine.owner() == Owner::Lease {
500                None
501            } else {
502                Some(engine.try_lease())
503            }
504        })?;
505        if claimed {
506            break;
507        }
508        attempts += 1;
509        let waited = psx_rt::interrupts::vblank_count().wrapping_sub(start);
510        if waited >= LEASE_PATIENCE_VBLANKS || attempts >= LEASE_PATIENCE_ATTEMPTS {
511            with_engine(Engine::force_lease);
512            break;
513        }
514    }
515    irq::set_mask(irq::mask() & !(SIO_BIT | TIMER_BIT));
516    irq::release_polling_keep(SIO_BIT | TIMER_BIT);
517    psx_rt::interrupts::release_interrupt_sources(SIO_BIT | TIMER_BIT);
518    timers::set_mode(Timer::Timer0, 0);
519    irq::acknowledge(SIO_BIT | TIMER_BIT);
520    // SAFETY: foreground; written here and in `install` only.
521    unsafe { core::ptr::write_volatile(&raw mut INSTALLED, false) };
522    // SAFETY: foreground; the engine is leased to this call, so nothing else
523    // takes the token.
524    unsafe { (*TOKEN.0.get()).take() }
525}
526
527/// Whether [`install`] has run, [`uninstall`] has not, and psx-rt's handler has
528/// not been put back in the vector since (which drops the wrapper from the
529/// exception chain: `false` then, and the engine no longer runs). Otherwise
530/// the wrapper is in the chain, first in the vector or behind psx-cdstream's,
531/// which chains to it.
532pub fn is_installed() -> bool {
533    #[cfg(target_arch = "mips")]
534    {
535        // psx-rt's handler going back into the vector drops the wrapper from
536        // the chain without telling it; the epoch says whether that happened.
537        // SAFETY: a volatile read of a word the foreground writes.
538        let epoch = unsafe { core::ptr::read_volatile(&raw const PSX_PAD_EPOCH) };
539        installed_flag() && epoch == psx_rt::interrupts::vector_epoch()
540    }
541    #[cfg(not(target_arch = "mips"))]
542    installed_flag()
543}
544
545/// Whether [`install`] ran and [`uninstall`] has not, whether or not the
546/// wrapper is still in the vector. [`uninstall`] goes by this: it must still be
547/// able to give the port back when the wrapper was dropped from under it.
548fn installed_flag() -> bool {
549    // SAFETY: a volatile read of a flag the foreground writes.
550    unsafe { core::ptr::read_volatile(&raw const INSTALLED) }
551}
552
553// ------------------------------------------------------------ the foreground
554
555/// The latest publication of both ports. A copy: no lock, no interrupt
556/// masking.
557pub fn snapshot() -> Snapshot {
558    PUBLISHED.read()
559}
560
561/// The latest clean state of `port`.
562pub fn pad(port: Port) -> PadState {
563    PUBLISHED.read().pad(port)
564}
565
566/// The latest reading of `port`: the pad's state and whether the socket is
567/// present.
568pub fn reading(port: Port) -> PortReading {
569    *PUBLISHED.read().port(port)
570}
571
572/// Change the settings; they apply from the next transaction.
573pub fn configure(config: Config) {
574    with_engine(|engine| engine.configure(config));
575}
576
577/// A copy of the counters.
578pub fn stats() -> Stats {
579    with_engine(|engine| engine.stats())
580}
581
582/// Ask for analog mode on `port` and lock it there. See
583/// [`Engine::request_analog`]; [`analog_outcome`] answers a few frames later.
584pub fn request_analog(port: Port) {
585    with_engine(|engine| engine.request_analog(port));
586}
587
588/// What the pad settled on after [`request_analog`]; `None` while pending.
589pub fn analog_outcome(port: Port) -> Option<AnalogRequirement> {
590    with_engine(|engine| engine.analog_outcome(port))
591}
592
593/// Put the motors of the pad on `port` under the poll. The engine maps them
594/// (command 0x4D, in the same visit to configuration mode as an analog request
595/// if one is pending) whenever an analog DualShock is there and again each time
596/// one is plugged in, then sends [`set_rumble`]'s request with every poll.
597/// [`rumble_mapped`] says whether the pad took it.
598pub fn enable_rumble(port: Port) {
599    with_engine(|engine| engine.enable_rumble(port));
600}
601
602/// Stop wanting the motors on `port`. They are told to stop on the next poll.
603pub fn disable_rumble(port: Port) {
604    with_engine(|engine| engine.disable_rumble(port));
605}
606
607/// What the motors on `port` are asked to do on every poll. Takes effect on a
608/// pad that has been mapped; a digital pad ignores it.
609pub fn set_rumble(port: Port, rumble: Rumble) {
610    with_engine(|engine| engine.set_rumble(port, rumble));
611}
612
613/// Whether the pad on `port` took the motor mapping.
614pub fn rumble_mapped(port: Port) -> bool {
615    with_engine(|engine| engine.rumble_mapped(port))
616}
617
618/// Stop every motor now and return once a poll with the motors off has gone
619/// out on each port, so a program can pause, open a menu, or hand the port over
620/// knowing nothing is still spinning. Waits as [`lease`] does, three VBlanks at
621/// most; a port a [`Lease`] holds is not polled meanwhile. An unplugged pad has
622/// nothing to stop.
623pub fn stop_motors() {
624    let (start, idle) = with_engine(|engine| {
625        engine.stop_motors();
626        (engine.stats().kicks, engine.is_idle())
627    });
628    // A round already on the wire took its motor bytes when it started; the
629    // next round is the first to send zeros.
630    let target = start.wrapping_add(if idle { 1 } else { 2 });
631    let first = psx_rt::interrupts::vblank_count();
632    let mut attempts = 0u32;
633    loop {
634        let done = with_engine(|engine| {
635            let kicks = engine.stats().kicks;
636            kicks.wrapping_sub(target) < 0x8000_0000 && engine.is_idle()
637        });
638        attempts += 1;
639        let waited = psx_rt::interrupts::vblank_count().wrapping_sub(first);
640        if done || waited >= LEASE_PATIENCE_VBLANKS || attempts >= LEASE_PATIENCE_ATTEMPTS {
641            return;
642        }
643    }
644}
645
646/// Who may use the port now.
647pub fn owner() -> Owner {
648    with_engine(|engine| engine.owner())
649}
650
651// --------------------------------------------------------------------- lease
652
653/// The port, on loan from the engine: it derefs to the [`ControllerPort`] a
654/// memory card or a diagnostic needs, and the engine polls nothing until it
655/// is dropped. VBlanks that pass meanwhile are not polled, so the snapshot
656/// stands still; keep a lease to one transaction.
657pub struct Lease {
658    port: Option<ControllerPort>,
659}
660
661impl Deref for Lease {
662    type Target = ControllerPort;
663
664    fn deref(&self) -> &ControllerPort {
665        self.port
666            .as_ref()
667            .expect("a lease holds the port until it is dropped")
668    }
669}
670
671impl DerefMut for Lease {
672    fn deref_mut(&mut self) -> &mut ControllerPort {
673        self.port
674            .as_mut()
675            .expect("a lease holds the port until it is dropped")
676    }
677}
678
679impl Drop for Lease {
680    fn drop(&mut self) {
681        if let Some(port) = self.port.take() {
682            with_engine(|engine| {
683                // SAFETY: foreground, inside the engine section; the token
684                // went out with this lease and comes back with it.
685                unsafe { *TOKEN.0.get() = Some(port) };
686                engine.release_lease();
687            });
688        }
689    }
690}
691
692fn take_lease(take: impl FnOnce(&mut Engine<'static, Mmio>) -> bool) -> Option<Lease> {
693    with_engine(|engine| {
694        if !take(engine) {
695            return None;
696        }
697        // SAFETY: foreground, inside the engine section.
698        let port = unsafe { (*TOKEN.0.get()).take() };
699        Some(Lease { port })
700    })
701}
702
703/// Borrow the port if no transaction is on the wire right now.
704pub fn try_lease() -> Option<Lease> {
705    take_lease(Engine::try_lease)
706}
707
708/// Borrow the port. Waits for a transaction in flight (under two
709/// milliseconds on the wire); if the engine has not gone idle after a few
710/// VBlanks it abandons the transaction instead of waiting longer. A caller
711/// with CPU interrupts off cannot let the transaction finish, so it waits a
712/// fixed number of attempts instead and then takes the port.
713pub fn lease() -> Lease {
714    let start = psx_rt::interrupts::vblank_count();
715    let mut attempts = 0u32;
716    loop {
717        if let Some(lease) = try_lease() {
718            return lease;
719        }
720        attempts += 1;
721        let waited = psx_rt::interrupts::vblank_count().wrapping_sub(start);
722        if waited >= LEASE_PATIENCE_VBLANKS || attempts >= LEASE_PATIENCE_ATTEMPTS {
723            let lease = take_lease(|engine| {
724                engine.force_lease();
725                true
726            });
727            return lease.expect("the engine holds the port token once installed");
728        }
729    }
730}
731
732// --------------------------------------------------------------- diagnostics
733
734/// Bytes of the handler's private stack never touched since [`install`]
735/// painted it.
736pub fn handler_stack_unused_bytes() -> usize {
737    let mut unused = 0;
738    // SAFETY: plain volatile reads of a static this module owns.
739    unsafe {
740        let stack = (&raw const PSX_PAD_IRQ_STACK).cast::<u8>();
741        while unused < HANDLER_STACK_BYTES && stack.add(unused).read_volatile() == STACK_FILL {
742            unused += 1;
743        }
744    }
745    unused
746}