1use 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
43const 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;
48pub const HANDLER_STACK_BYTES: usize = 768;
50const STACK_FILL: u8 = 0xa5;
52const ACK_RELEASE_SPINS: u32 = 256;
54const LEASE_PATIENCE_VBLANKS: u32 = 3;
56const LEASE_PATIENCE_ATTEMPTS: u32 = 4_000;
60
61pub struct Mmio {
65 armed: bool,
67 target: u16,
69}
70
71impl Mmio {
72 const fn new() -> Self {
73 Mmio {
74 armed: false,
75 target: 0,
76 }
77 }
78}
79
80fn token() -> ControllerPort {
83 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 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 self.armed && timers::counter(Timer::Timer0) >= self.target
151 }
152}
153
154struct Global(UnsafeCell<Engine<'static, Mmio>>);
157
158unsafe impl Sync for Global {}
161
162static PUBLISHED: Published = Published::new();
164
165static ENGINE: Global = Global(UnsafeCell::new(Engine::new(
166 Mmio::new(),
167 &PUBLISHED,
168 Config::DEFAULT,
169)));
170
171struct TokenSlot(UnsafeCell<Option<ControllerPort>>);
173
174unsafe 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#[no_mangle]
187static mut PSX_PAD_IRQ_STACK: Stack = Stack([0; HANDLER_STACK_BYTES]);
188#[no_mangle]
190static mut PSX_PAD_IRQ_CONTEXT: [u32; 34] = [0; 34];
191#[no_mangle]
194static mut PSX_PAD_NEXT_HANDLER: u32 = 0;
195#[cfg(target_arch = "mips")]
197static mut PSX_PAD_EPOCH: u32 = 0;
198static mut INSTALLED: bool = false;
200
201#[inline(always)]
203fn with_engine<R>(f: impl FnOnce(&mut Engine<'static, Mmio>) -> R) -> R {
204 irq::without_interrupts(|| {
205 f(unsafe { &mut *ENGINE.0.get() })
209 })
210}
211
212#[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#[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#[no_mangle]
341extern "C" fn psx_pad_interrupt() {
342 let pending = irq::pending() & irq::mask() & SOURCES;
343 irq::acknowledge(pending & (SIO_BIT | TIMER_BIT));
347 let engine = unsafe { &mut *ENGINE.0.get() };
351 if pending & VBLANK_BIT != 0 {
352 engine.on_vblank();
353 }
354 if pending & SIO_BIT != 0 {
357 engine.on_ack();
358 }
359 if pending & TIMER_BIT != 0 {
360 engine.on_deadline();
361 }
362}
363
364#[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 unsafe {
384 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 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
425pub fn install(port: ControllerPort, config: Config) -> Result<(), ControllerPort> {
440 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 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 irq::keep_enabled_while_polling(SIO_BIT | TIMER_BIT);
470 psx_rt::interrupts::claim_interrupt_sources(SIO_BIT | TIMER_BIT);
473 unsafe { core::ptr::write_volatile(&raw mut INSTALLED, true) };
475 Ok(())
476}
477
478pub fn uninstall() -> Option<ControllerPort> {
487 if !installed_flag() {
488 return None;
489 }
490 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 unsafe { core::ptr::write_volatile(&raw mut INSTALLED, false) };
522 unsafe { (*TOKEN.0.get()).take() }
525}
526
527pub fn is_installed() -> bool {
533 #[cfg(target_arch = "mips")]
534 {
535 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
545fn installed_flag() -> bool {
549 unsafe { core::ptr::read_volatile(&raw const INSTALLED) }
551}
552
553pub fn snapshot() -> Snapshot {
558 PUBLISHED.read()
559}
560
561pub fn pad(port: Port) -> PadState {
563 PUBLISHED.read().pad(port)
564}
565
566pub fn reading(port: Port) -> PortReading {
569 *PUBLISHED.read().port(port)
570}
571
572pub fn configure(config: Config) {
574 with_engine(|engine| engine.configure(config));
575}
576
577pub fn stats() -> Stats {
579 with_engine(|engine| engine.stats())
580}
581
582pub fn request_analog(port: Port) {
585 with_engine(|engine| engine.request_analog(port));
586}
587
588pub fn analog_outcome(port: Port) -> Option<AnalogRequirement> {
590 with_engine(|engine| engine.analog_outcome(port))
591}
592
593pub fn enable_rumble(port: Port) {
599 with_engine(|engine| engine.enable_rumble(port));
600}
601
602pub fn disable_rumble(port: Port) {
604 with_engine(|engine| engine.disable_rumble(port));
605}
606
607pub fn set_rumble(port: Port, rumble: Rumble) {
610 with_engine(|engine| engine.set_rumble(port, rumble));
611}
612
613pub fn rumble_mapped(port: Port) -> bool {
615 with_engine(|engine| engine.rumble_mapped(port))
616}
617
618pub fn stop_motors() {
624 let (start, idle) = with_engine(|engine| {
625 engine.stop_motors();
626 (engine.stats().kicks, engine.is_idle())
627 });
628 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
646pub fn owner() -> Owner {
648 with_engine(|engine| engine.owner())
649}
650
651pub 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 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 let port = unsafe { (*TOKEN.0.get()).take() };
699 Some(Lease { port })
700 })
701}
702
703pub fn try_lease() -> Option<Lease> {
705 take_lease(Engine::try_lease)
706}
707
708pub 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
732pub fn handler_stack_unused_bytes() -> usize {
737 let mut unused = 0;
738 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}