psx_pad/engine.rs
1// SPDX-License-Identifier: GPL-2.0-or-later
2//! The interrupt-driven pad engine: its state machine, with no hardware in it.
3//!
4//! The synchronous driver in the crate root spends the CPU's time waiting. A
5//! poll holds a setup delay of 1,024 status reads after raising `/CS`, then
6//! spins on `/ACK` after every byte, and a socket with nothing in it spends
7//! the whole delay and the whole `/ACK` budget to learn that. This engine
8//! never waits. A frame's VBlank starts one transaction per port; every step
9//! after that is an interrupt, and between interrupts the CPU runs the game.
10//!
11//! ```text
12//! VBlank ──► select port ──► arm timer(setup)
13//! timer ──► transmit byte 0 ──► arm timer(ack budget)
14//! IRQ7 ──► read reply, clear latch, transmit next byte ──► arm timer
15//! ... (the last byte has no ACK: the timer ends it)
16//! done ──► deselect, publish a snapshot, start the next port
17//! ```
18//!
19//! What stops a byte that never comes is the timer, not a loop: an absent
20//! pad answers `0xFF` and never pulses `/ACK`, so the first byte's budget
21//! runs out and the port reads as absent. That costs wall time on the wire
22//! (a fraction of a millisecond) and almost nothing on the CPU, and a pad
23//! plugged in later is found by the next VBlank's transaction.
24//!
25//! The game reads a [`Snapshot`] (a sequence number and, per port, the last
26//! clean [`PadState`] and whether the port is present) without disturbing the
27//! engine: [`Published::read`] is a copy.
28//!
29//! This module is the policy, generic over [`Hw`] so the host tests drive it
30//! against a controller model with real timing; the console side (the
31//! exception wrapper, the timer, the registers) is in `console.rs`.
32//! `sdk/docs/PAD-IRQ-ENGINE.md` is the design.
33
34use crate::{
35 mode_from_id_low, AnalogRequirement, AnalogSticks, PadMode, PadState, Rumble, MOTOR_MAP_PACKET,
36};
37use core::cell::UnsafeCell;
38use core::ptr::{read_volatile, write_volatile};
39use psx_hw::sio::sio0::stat;
40use psx_io::controller_port::Port;
41
42/// How the engine decides a byte is done and the next may go.
43#[derive(Copy, Clone, Debug, PartialEq, Eq)]
44pub enum BytePacing {
45 /// The device's `/ACK` pulse, delivered as IRQ7, advances the packet; the
46 /// timer is only the limit for a byte that is never acknowledged. This
47 /// is how the BIOS paces a pad and adapts to a slow unit. Each byte
48 /// costs one write of the control register to clear the latched IRQ.
49 Ack,
50 /// A fixed gap after each byte. The `/ACK` interrupt is never armed and
51 /// no control register is written between bytes, the wire pattern the
52 /// pre-ACK driver was proven with on three pad models. A pad slower to
53 /// acknowledge than [`Config::timed_gap_cycles`] slips the packet.
54 Timed,
55}
56
57/// The engine's settings.
58#[derive(Copy, Clone, Debug, PartialEq, Eq)]
59pub struct Config {
60 /// How bytes are paced.
61 pub pacing: BytePacing,
62 /// VBlanks between transactions: 1 polls every frame, 2 every other.
63 pub kick_every: u8,
64 /// Which ports are polled, `[port 1, port 2]`.
65 pub ports: [bool; 2],
66 /// CPU cycles from raising `/CS` to the first byte. The original SCPH-1200
67 /// answers nothing without it (silicon, 2026-06-22); the synchronous
68 /// driver's 1,024 status reads are about 6,900 cycles.
69 pub setup_cycles: u32,
70 /// CPU cycles after a byte starts within which its `/ACK` must arrive,
71 /// the byte's own shift included. The synchronous driver allows 2,048
72 /// status reads after the reply, about 13,700 cycles.
73 pub ack_cycles: u32,
74 /// CPU cycles after the final byte starts at which its reply is read; the
75 /// device does not acknowledge it. The byte itself shifts in 1,088.
76 pub last_byte_cycles: u32,
77 /// [`BytePacing::Timed`] only: CPU cycles after a byte starts before
78 /// the next one goes.
79 pub timed_gap_cycles: u32,
80}
81
82impl Config {
83 /// Both ports every frame, paced on `/ACK`.
84 pub const DEFAULT: Config = Config {
85 pacing: BytePacing::Ack,
86 kick_every: 1,
87 ports: [true, true],
88 setup_cycles: 7_000,
89 ack_cycles: 14_800,
90 last_byte_cycles: 3_000,
91 timed_gap_cycles: 4_500,
92 };
93
94 /// [`DEFAULT`](Self::DEFAULT) for a game with one controller.
95 pub const PORT1_ONLY: Config = Config {
96 ports: [true, false],
97 ..Config::DEFAULT
98 };
99}
100
101impl Default for Config {
102 fn default() -> Self {
103 Config::DEFAULT
104 }
105}
106
107/// What the engine needs from the console: the serial port, and one timer
108/// that raises an interrupt after a number of CPU cycles.
109pub trait Hw {
110 /// The status register.
111 fn status(&mut self) -> u32;
112 /// Configure 250 kHz 8N1, clear a stale latched IRQ, and assert `/CS` on
113 /// `port` with the `/ACK` interrupt armed when `ack_irq`.
114 fn select(&mut self, port: Port, ack_irq: bool);
115 /// Release `/CS`.
116 fn deselect(&mut self);
117 /// Reset the UART, so a reply still in flight from an abandoned packet
118 /// cannot be taken for the next one's.
119 fn reset_uart(&mut self);
120 /// Pop stale bytes from the receive FIFO.
121 fn drain_receive(&mut self);
122 /// Start shifting one byte out.
123 fn transmit(&mut self, byte: u8);
124 /// Pop one received byte.
125 fn receive(&mut self) -> u8;
126 /// Wait, a few microseconds at most, for a pulse of `/ACK` already seen to
127 /// end. `false` when the line stays asserted.
128 fn wait_ack_release(&mut self) -> bool;
129 /// Clear the latched `/ACK` IRQ so the next pulse raises IRQ7 again,
130 /// leaving `/CS` asserted on `port`, or released when `None`.
131 fn clear_ack_latch(&mut self, port: Option<Port>, ack_irq: bool);
132 /// Raise the timer interrupt in `cycles` CPU cycles, once, replacing any
133 /// deadline already armed.
134 fn arm_deadline(&mut self, cycles: u32);
135 /// Disarm the deadline.
136 fn cancel_deadline(&mut self);
137 /// Whether the armed deadline has been reached. An interrupt left over from
138 /// a deadline that was cancelled or replaced answers `false`.
139 fn deadline_expired(&mut self) -> bool;
140}
141
142/// What the engine last learned about a port.
143#[derive(Copy, Clone, Debug, PartialEq, Eq)]
144pub enum Health {
145 /// No transaction has finished on this port yet.
146 Unseen,
147 /// A device answered; [`PortReading::pad`] is its latest clean state.
148 Present,
149 /// Nothing answered: an empty socket.
150 Absent,
151 /// The latest transaction failed part way. [`PortReading::pad`] still holds
152 /// the last clean state, so a held button is not released and pressed
153 /// again.
154 Faulted,
155}
156
157/// One port, as the game sees it.
158#[derive(Copy, Clone, Debug, PartialEq, Eq)]
159pub struct PortReading {
160 /// The latest clean state: the pad's, or [`PadState::NONE`] for an empty
161 /// socket.
162 pub pad: PadState,
163 /// What the latest transaction found.
164 pub health: Health,
165 /// Transactions that read a pad (or an empty socket) cleanly.
166 pub updates: u32,
167 /// Transactions that failed part way.
168 pub faults: u32,
169 /// Why the latest failed transaction failed; kept after a clean one.
170 pub last_fault: Option<Fault>,
171}
172
173impl PortReading {
174 /// A port nothing has been read from.
175 pub const UNSEEN: PortReading = PortReading {
176 pad: PadState::NONE,
177 health: Health::Unseen,
178 updates: 0,
179 faults: 0,
180 last_fault: None,
181 };
182}
183
184/// Both ports at one instant, with the sequence number of the publication.
185#[derive(Copy, Clone, Debug, PartialEq, Eq)]
186pub struct Snapshot {
187 /// Publications so far; changes whenever a port was updated.
188 pub seq: u32,
189 /// `[port 1, port 2]`.
190 pub ports: [PortReading; 2],
191}
192
193impl Snapshot {
194 /// The reading for `port`.
195 pub const fn port(&self, port: Port) -> &PortReading {
196 match port {
197 Port::One => &self.ports[0],
198 Port::Two => &self.ports[1],
199 }
200 }
201
202 /// The latest clean pad state for `port`.
203 pub const fn pad(&self, port: Port) -> PadState {
204 self.port(port).pad
205 }
206}
207
208/// Where the engine publishes: two buffers and a sequence number, so a reader
209/// in the foreground gets a consistent copy while the interrupt handler
210/// publishes, with no lock and no interrupt masking.
211///
212/// One writer (the engine) and any number of foreground readers, on one CPU.
213pub struct Published {
214 seq: UnsafeCell<u32>,
215 slots: UnsafeCell<[[PortReading; 2]; 2]>,
216}
217
218// SAFETY: the single writer is the engine, in interrupt context or with
219// interrupts off; readers copy under the sequence check in `read`, which
220// retries if the writer reused the slot they were copying.
221unsafe impl Sync for Published {}
222
223impl Published {
224 /// Nothing published.
225 pub const fn new() -> Self {
226 Published {
227 seq: UnsafeCell::new(0),
228 slots: UnsafeCell::new([[PortReading::UNSEEN; 2]; 2]),
229 }
230 }
231
232 /// Publish `ports`. Only the engine calls this.
233 fn publish(&self, ports: &[PortReading; 2]) {
234 // SAFETY: the writer is the engine alone (see the `Sync` impl); the
235 // slot written is the one readers do not take until `seq` moves.
236 unsafe {
237 let seq = read_volatile(self.seq.get());
238 let next = seq.wrapping_add(1);
239 write_volatile(&mut (*self.slots.get())[(next & 1) as usize], *ports);
240 psx_io::dma::compiler_barrier();
241 write_volatile(self.seq.get(), next);
242 }
243 }
244
245 /// A consistent copy of the latest publication.
246 pub fn read(&self) -> Snapshot {
247 loop {
248 // SAFETY: volatile reads of the sequence number and of the slot it
249 // names; the slot is re-validated against the sequence number
250 // after the copy, so a torn read is discarded.
251 let (seq, ports, after) = unsafe {
252 let seq = read_volatile(self.seq.get());
253 psx_io::dma::compiler_barrier();
254 let ports = read_volatile(&(*self.slots.get())[(seq & 1) as usize]);
255 psx_io::dma::compiler_barrier();
256 (seq, ports, read_volatile(self.seq.get()))
257 };
258 // The writer fills the other slot first; it only touches this one
259 // again on the second publication after `seq`.
260 if after.wrapping_sub(seq) < 2 {
261 return Snapshot { seq, ports };
262 }
263 }
264 }
265}
266
267impl Default for Published {
268 fn default() -> Self {
269 Self::new()
270 }
271}
272
273/// Counters, for tools and for tests.
274#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
275pub struct Stats {
276 /// Interrupts the engine handled (ACK and deadline).
277 pub events: u32,
278 /// VBlanks that started a round of transactions.
279 pub kicks: u32,
280 /// VBlanks skipped because the port was leased out.
281 pub leased_skips: u32,
282 /// Rounds abandoned because the previous one was still running at the
283 /// next VBlank: a round is under a millisecond and a half on the wire, so
284 /// an interrupt was lost.
285 pub stalls: u32,
286 /// `/ACK` interrupts that arrived with no byte waiting for one.
287 pub spurious: u32,
288}
289
290/// Who may use the serial port.
291#[derive(Copy, Clone, Debug, PartialEq, Eq)]
292pub enum Owner {
293 /// The engine, which polls on every VBlank.
294 Engine,
295 /// A foreground driver (a memory card) holds the port; the engine does
296 /// not touch it, and VBlanks that come meanwhile are not polled.
297 Lease,
298}
299
300/// Why a transaction failed.
301#[derive(Copy, Clone, Debug, PartialEq, Eq)]
302pub enum Fault {
303 /// The port would not take the byte.
304 TxBusy,
305 /// `/ACK` was still asserted when it should have ended.
306 AckStuck,
307 /// A byte was never acknowledged.
308 AckTimeout,
309 /// The reply did not arrive.
310 RxMissing,
311 /// An ID this driver does not know.
312 BadId,
313 /// The ID's second byte was not `0x5A`.
314 BadMagic,
315}
316
317#[derive(Copy, Clone, Debug)]
318enum Kind {
319 Poll,
320 Config([u8; 8]),
321}
322
323/// The packet on the wire.
324#[derive(Copy, Clone, Debug)]
325struct Txn {
326 port: Port,
327 kind: Kind,
328 /// The pacing in force when the transaction started: a change of
329 /// [`Config`] takes effect from the next one, never half way through a
330 /// packet whose select was made for the old one.
331 pacing: BytePacing,
332 /// The byte most recently transmitted.
333 idx: u8,
334 /// Exchanges in the packet, the address byte included. Nine until the ID
335 /// says otherwise.
336 len: u8,
337 rx: [u8; 9],
338 /// The motor bytes of a poll, for a pad that answers as an analog
339 /// DualShock: zeros unless the port's motors are mapped.
340 motors: (u8, u8),
341}
342
343#[derive(Copy, Clone, Debug, PartialEq, Eq)]
344enum Phase {
345 Idle,
346 /// `/CS` is up and the setup timer is running.
347 Setup,
348 /// Byte `txn.idx` is on the wire.
349 Byte,
350}
351
352/// What a transaction found.
353#[derive(Copy, Clone, Debug)]
354enum Outcome {
355 Pad(PadState),
356 Absent,
357 /// A configuration packet went through; `mapped` when it was the motor
358 /// mapping and the pad answered it from configuration mode.
359 Configured {
360 mapped: bool,
361 },
362 Failed(Fault),
363}
364
365const ENTER_CONFIG: [u8; 8] = [0x43, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00];
366const EXIT_CONFIG: [u8; 8] = [0x43, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
367const ANALOG_LOCK: [u8; 8] = [0x44, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x00];
368
369/// The configuration packets of a request, one per VBlank, the spacing Sony's
370/// libpad uses.
371#[derive(Copy, Clone, Debug, PartialEq, Eq)]
372enum JobKind {
373 /// Analog mode, locked.
374 Analog,
375 /// Analog mode, locked, and the motors mapped, in one visit to
376 /// configuration mode.
377 AnalogRumble,
378 /// The motors mapped; the pad's mode is left as it is.
379 Rumble,
380}
381
382impl JobKind {
383 const fn packets(self) -> &'static [[u8; 8]] {
384 match self {
385 JobKind::Analog => &[ENTER_CONFIG, ANALOG_LOCK, EXIT_CONFIG],
386 JobKind::AnalogRumble => &[ENTER_CONFIG, ANALOG_LOCK, MOTOR_MAP_PACKET, EXIT_CONFIG],
387 JobKind::Rumble => &[ENTER_CONFIG, MOTOR_MAP_PACKET, EXIT_CONFIG],
388 }
389 }
390
391 /// Packets in the sequence; the exit is the last, and the step after it
392 /// waits for a poll to check what the pad settled on.
393 const fn len(self) -> u8 {
394 self.packets().len() as u8
395 }
396
397 const fn maps_motors(self) -> bool {
398 !matches!(self, JobKind::Analog)
399 }
400}
401
402/// Exit-config repeats for a pad still answering ID 0xF3 afterwards.
403const EXIT_RETRIES: u8 = 3;
404/// Failed configuration attempts before the request gives up.
405const ANALOG_FAULT_LIMIT: u8 = 8;
406
407/// A configuration request on a port, in progress.
408#[derive(Copy, Clone, Debug)]
409struct AnalogJob {
410 /// 0 none; 1..=`kind.len()` the packet to send; the step after waits for
411 /// a poll to verify.
412 step: u8,
413 kind: JobKind,
414 retries: u8,
415 faults: u8,
416 outcome: Option<AnalogRequirement>,
417}
418
419impl AnalogJob {
420 const NONE: AnalogJob = AnalogJob {
421 step: 0,
422 kind: JobKind::Analog,
423 retries: 0,
424 faults: 0,
425 outcome: None,
426 };
427
428 const fn start(kind: JobKind) -> AnalogJob {
429 AnalogJob {
430 step: 1,
431 kind,
432 ..AnalogJob::NONE
433 }
434 }
435
436 /// The step that waits for a verifying poll.
437 const fn verify_step(&self) -> u8 {
438 self.kind.len() + 1
439 }
440}
441
442#[derive(Copy, Clone, Debug)]
443struct PortCtl {
444 reading: PortReading,
445 job: AnalogJob,
446 /// What the motors are asked for on every poll.
447 rumble: Rumble,
448 /// The game wants the motors on this port; the engine maps them whenever
449 /// a pad appears and has not been mapped.
450 rumble_wanted: bool,
451 /// The pad took the motor mapping since it last appeared.
452 mapped: bool,
453 /// The pad did not take it (a digital pad, a pad that refuses
454 /// configuration mode); not asked again until the pad is replugged.
455 refused: bool,
456}
457
458/// Index of `port` in the engine's per-port arrays.
459const fn index(port: Port) -> usize {
460 match port {
461 Port::One => 0,
462 Port::Two => 1,
463 }
464}
465
466/// The byte the host sends as exchange `idx` of a packet.
467const fn tx_byte(kind: &Kind, idx: u8, id: u8, motors: (u8, u8)) -> u8 {
468 match (kind, idx) {
469 (_, 0) => 0x01,
470 (Kind::Poll, 1) => 0x42,
471 // The two motor bytes, to a pad that answered as an analog DualShock.
472 (Kind::Poll, 3) if id == 0x73 => motors.0,
473 (Kind::Poll, 4) if id == 0x73 => motors.1,
474 (Kind::Poll, _) => 0x00,
475 (Kind::Config(packet), _) => packet[idx as usize - 1],
476 }
477}
478
479/// The state machine. One per console, driven by three events: a VBlank
480/// ([`on_vblank`](Self::on_vblank)), a device's `/ACK`
481/// ([`on_ack`](Self::on_ack)) and the deadline timer
482/// ([`on_deadline`](Self::on_deadline)). The three run with CPU interrupts off.
483/// Everything else is for the foreground, which must not overlap them.
484pub struct Engine<'p, H: Hw> {
485 hw: H,
486 published: &'p Published,
487 config: Config,
488 phase: Phase,
489 txn: Txn,
490 owner: Owner,
491 vblanks: u8,
492 ports: [PortCtl; 2],
493 stats: Stats,
494}
495
496impl<'p, H: Hw> Engine<'p, H> {
497 /// An idle engine that publishes to `published`.
498 pub const fn new(hw: H, published: &'p Published, config: Config) -> Self {
499 Engine {
500 hw,
501 published,
502 config,
503 phase: Phase::Idle,
504 txn: Txn {
505 port: Port::One,
506 kind: Kind::Poll,
507 pacing: BytePacing::Ack,
508 idx: 0,
509 len: 9,
510 rx: [0; 9],
511 motors: (0, 0),
512 },
513 owner: Owner::Engine,
514 vblanks: 0,
515 ports: [PortCtl {
516 reading: PortReading::UNSEEN,
517 job: AnalogJob::NONE,
518 rumble: Rumble::OFF,
519 rumble_wanted: false,
520 mapped: false,
521 refused: false,
522 }; 2],
523 stats: Stats {
524 events: 0,
525 kicks: 0,
526 leased_skips: 0,
527 stalls: 0,
528 spurious: 0,
529 },
530 }
531 }
532
533 /// The hardware.
534 pub fn hw(&self) -> &H {
535 &self.hw
536 }
537
538 /// The hardware, mutably.
539 pub fn hw_mut(&mut self) -> &mut H {
540 &mut self.hw
541 }
542
543 /// The settings in force.
544 pub const fn config(&self) -> Config {
545 self.config
546 }
547
548 /// Change the settings; they apply from the next transaction.
549 pub fn configure(&mut self, config: Config) {
550 self.config = config;
551 }
552
553 /// The counters.
554 pub const fn stats(&self) -> Stats {
555 self.stats
556 }
557
558 /// Who may use the serial port now.
559 pub const fn owner(&self) -> Owner {
560 self.owner
561 }
562
563 /// Whether no transaction is on the wire.
564 pub fn is_idle(&self) -> bool {
565 self.phase == Phase::Idle
566 }
567
568 /// Publish the current readings. A freshly built engine calls this so the
569 /// snapshot a previous engine left behind does not outlive it: its
570 /// counters start again from zero.
571 pub fn publish_readings(&self) {
572 self.published
573 .publish(&[self.ports[0].reading, self.ports[1].reading]);
574 }
575
576 /// The latest publication.
577 pub fn snapshot(&self) -> Snapshot {
578 self.published.read()
579 }
580
581 // ------------------------------------------------------------ events
582
583 /// A VBlank: start a round of transactions, one per enabled port, unless
584 /// the port is leased. A round still running is abandoned.
585 pub fn on_vblank(&mut self) {
586 if self.owner == Owner::Lease {
587 self.stats.leased_skips = self.stats.leased_skips.wrapping_add(1);
588 return;
589 }
590 if self.phase != Phase::Idle {
591 // A round takes well under a frame, so the last one lost an
592 // interrupt. Reset the port; the next VBlank starts afresh.
593 self.stats.stalls = self.stats.stalls.wrapping_add(1);
594 self.abandon();
595 return;
596 }
597 self.vblanks = self.vblanks.saturating_add(1);
598 if self.vblanks < self.config.kick_every {
599 return;
600 }
601 self.vblanks = 0;
602 self.stats.kicks = self.stats.kicks.wrapping_add(1);
603 self.start_port(0);
604 }
605
606 /// The device's `/ACK` pulse raised IRQ7.
607 pub fn on_ack(&mut self) {
608 // A card driver holding the lease arms the same interrupt (its ACK
609 // latch is how it sees a pulse a CPU interrupt would hide) and waits
610 // on STAT.IRQ. Clearing the latch, or the select, here would erase the
611 // acknowledgement it is waiting for and fail the transaction.
612 if self.owner == Owner::Lease {
613 return;
614 }
615 self.note_event();
616 let acking = self.txn.pacing == BytePacing::Ack;
617 if !acking || self.phase != Phase::Byte {
618 // Nothing is waiting for an acknowledgement: clear the latch so
619 // the next one raises the interrupt, and move nothing.
620 self.stats.spurious = self.stats.spurious.wrapping_add(1);
621 let port = (self.phase != Phase::Idle).then_some(self.txn.port);
622 self.hw.clear_ack_latch(port, acking);
623 return;
624 }
625 if self.hw.status() & stat::RX_NOT_EMPTY == 0 {
626 return self.fail(Fault::RxMissing);
627 }
628 let reply = self.hw.receive();
629 if !self.hw.wait_ack_release() {
630 return self.fail(Fault::AckStuck);
631 }
632 self.hw.clear_ack_latch(Some(self.txn.port), true);
633 self.accept(reply);
634 }
635
636 /// The deadline timer's interrupt.
637 pub fn on_deadline(&mut self) {
638 if !self.hw.deadline_expired() {
639 return;
640 }
641 self.note_event();
642 match self.phase {
643 Phase::Idle => {}
644 Phase::Setup => self.begin(),
645 Phase::Byte => self.byte_deadline(),
646 }
647 }
648
649 fn note_event(&mut self) {
650 self.stats.events = self.stats.events.wrapping_add(1);
651 }
652
653 // --------------------------------------------------------- the packet
654
655 /// Start the transaction on the first enabled port from index `from`, or
656 /// go idle when there is none.
657 fn start_port(&mut self, from: usize) {
658 let mut i = from;
659 while i < 2 && !self.config.ports[i] {
660 i += 1;
661 }
662 if i >= 2 {
663 self.phase = Phase::Idle;
664 return;
665 }
666 let port = if i == 0 { Port::One } else { Port::Two };
667 let ctl = &self.ports[i];
668 let job = &ctl.job;
669 let kind = if job.step >= 1 && job.step <= job.kind.len() {
670 Kind::Config(job.kind.packets()[job.step as usize - 1])
671 } else {
672 Kind::Poll
673 };
674 let motors = if ctl.mapped {
675 ctl.rumble.bytes()
676 } else {
677 (0, 0)
678 };
679 self.txn = Txn {
680 port,
681 kind,
682 pacing: self.config.pacing,
683 idx: 0,
684 len: 9,
685 rx: [0; 9],
686 motors,
687 };
688 self.hw.select(port, self.txn.pacing == BytePacing::Ack);
689 self.hw.arm_deadline(self.config.setup_cycles);
690 self.phase = Phase::Setup;
691 }
692
693 /// The setup time has passed: send the address byte.
694 fn begin(&mut self) {
695 self.hw.drain_receive();
696 // An `/ACK` left asserted by an abandoned packet would be taken for
697 // this packet's first.
698 if self.hw.status() & stat::DSR_LEVEL != 0 {
699 return self.fail(Fault::AckStuck);
700 }
701 self.transmit(0);
702 }
703
704 fn transmit(&mut self, idx: u8) {
705 if self.hw.status() & stat::TX_READY == 0 {
706 return self.fail(Fault::TxBusy);
707 }
708 let last = idx + 1 == self.txn.len;
709 self.txn.idx = idx;
710 self.hw.transmit(tx_byte(
711 &self.txn.kind,
712 idx,
713 self.txn.rx[1],
714 self.txn.motors,
715 ));
716 let budget = if last {
717 self.config.last_byte_cycles
718 } else {
719 match self.txn.pacing {
720 BytePacing::Ack => self.config.ack_cycles,
721 BytePacing::Timed => self.config.timed_gap_cycles,
722 }
723 };
724 self.hw.arm_deadline(budget);
725 self.phase = Phase::Byte;
726 }
727
728 /// The timer ended a byte: the reply is read either way, but only the
729 /// last byte, or any byte under fixed pacing, may go unacknowledged. An
730 /// address byte answered `0xFF` with no `/ACK` is an empty socket.
731 fn byte_deadline(&mut self) {
732 let last = self.txn.idx + 1 == self.txn.len;
733 if self.hw.status() & stat::RX_NOT_EMPTY == 0 {
734 return self.fail(Fault::RxMissing);
735 }
736 let reply = self.hw.receive();
737 if last || self.txn.pacing == BytePacing::Timed {
738 self.accept(reply);
739 } else if self.txn.idx == 0 && reply == 0xff {
740 self.finish(Outcome::Absent);
741 } else {
742 self.fail(Fault::AckTimeout);
743 }
744 }
745
746 /// Take the reply to byte `txn.idx` and send the next, or finish.
747 fn accept(&mut self, reply: u8) {
748 let idx = self.txn.idx;
749 self.txn.rx[idx as usize] = reply;
750 // The ID in the reply to the command byte sets the length of every
751 // packet, a configuration command included: a digital pad answers a
752 // nine-byte command with five bytes and stops acknowledging.
753 match (idx, reply) {
754 (1, id) => match mode_from_id_low(id) {
755 PadMode::Digital => self.txn.len = 5,
756 PadMode::Analog | PadMode::Config | PadMode::Negcon => self.txn.len = 9,
757 PadMode::Disconnected => return self.finish(Outcome::Absent),
758 PadMode::Unknown => return self.fail(Fault::BadId),
759 },
760 (2, magic) if magic != 0x5a => return self.fail(Fault::BadMagic),
761 _ => {}
762 }
763 if idx + 1 >= self.txn.len {
764 let outcome = match self.txn.kind {
765 Kind::Poll => Outcome::Pad(self.decode()),
766 Kind::Config(packet) => Outcome::Configured {
767 mapped: packet[0] == MOTOR_MAP_PACKET[0]
768 && self.txn.rx[1] == 0xf3
769 && self.txn.rx[2] == 0x5a,
770 },
771 };
772 self.finish(outcome);
773 } else {
774 self.transmit(idx + 1);
775 }
776 }
777
778 /// The pad state in a complete poll reply.
779 fn decode(&self) -> PadState {
780 let rx = &self.txn.rx;
781 let mode = mode_from_id_low(rx[1]);
782 let sticks = if self.txn.len == 9 {
783 AnalogSticks {
784 right_x: rx[5],
785 right_y: rx[6],
786 left_x: rx[7],
787 left_y: rx[8],
788 }
789 } else {
790 AnalogSticks::CENTERED
791 };
792 crate::RawPoll {
793 id_low: rx[1],
794 id_high: rx[2],
795 buttons_low: rx[3],
796 buttons_high: rx[4],
797 mode,
798 sticks,
799 exchanges: self.txn.len,
800 ack_seen: 0,
801 }
802 .to_state()
803 }
804
805 fn fail(&mut self, why: Fault) {
806 self.finish(Outcome::Failed(why));
807 }
808
809 /// End the transaction in flight and start the next port's.
810 fn finish(&mut self, outcome: Outcome) {
811 let i = self.end(outcome);
812 self.start_port(i + 1);
813 }
814
815 /// End the transaction in flight, publish what it found, and go idle.
816 /// Returns the port's index.
817 fn end(&mut self, outcome: Outcome) -> usize {
818 let i = index(self.txn.port);
819 self.hw.cancel_deadline();
820 self.hw.deselect();
821 if matches!(outcome, Outcome::Failed(_)) {
822 self.hw.reset_uart();
823 }
824 self.phase = Phase::Idle;
825 self.record(i, outcome);
826 if !matches!(outcome, Outcome::Configured { .. }) {
827 self.published
828 .publish(&[self.ports[0].reading, self.ports[1].reading]);
829 }
830 i
831 }
832
833 /// Give up on a round that no interrupt is advancing.
834 fn abandon(&mut self) {
835 self.end(Outcome::Failed(Fault::RxMissing));
836 }
837
838 /// Fold an outcome into the port's reading and its configuration request.
839 fn record(&mut self, i: usize, outcome: Outcome) {
840 let ctl = &mut self.ports[i];
841 let reading = &mut ctl.reading;
842 let job = &mut ctl.job;
843 match outcome {
844 Outcome::Pad(pad) => {
845 reading.pad = pad;
846 reading.health = Health::Present;
847 reading.updates = reading.updates.wrapping_add(1);
848 if job.step == job.verify_step() {
849 if pad.mode == PadMode::Config && job.retries < EXIT_RETRIES {
850 // The exit did not take: send it again.
851 job.retries += 1;
852 job.step = job.kind.len();
853 } else {
854 job.outcome = Some(AnalogRequirement::from_mode(pad.mode));
855 job.step = 0;
856 // A mapping that was asked for and not taken stays
857 // refused until the pad is plugged in again.
858 if job.kind.maps_motors() && !ctl.mapped {
859 ctl.refused = true;
860 }
861 }
862 }
863 // A pad that appeared (or came back) with the motors wanted
864 // and not mapped: map them. Only an analog DualShock has them.
865 if job.step == 0
866 && ctl.rumble_wanted
867 && !ctl.mapped
868 && !ctl.refused
869 && pad.mode == PadMode::Analog
870 {
871 // The analog request just answered keeps its answer.
872 let answer = job.outcome;
873 *job = AnalogJob::start(JobKind::Rumble);
874 job.outcome = answer;
875 }
876 }
877 Outcome::Absent => {
878 reading.pad = PadState::NONE;
879 reading.health = Health::Absent;
880 reading.updates = reading.updates.wrapping_add(1);
881 // A pad that is plugged in again has lost its mapping.
882 ctl.mapped = false;
883 ctl.refused = false;
884 if job.step != 0 {
885 job.outcome = Some(AnalogRequirement::Absent);
886 job.step = 0;
887 }
888 }
889 Outcome::Configured { mapped } => {
890 if mapped {
891 ctl.mapped = true;
892 }
893 if job.step >= 1 && job.step <= job.kind.len() {
894 job.step += 1;
895 }
896 }
897 Outcome::Failed(why) => {
898 reading.health = Health::Faulted;
899 reading.last_fault = Some(why);
900 reading.faults = reading.faults.wrapping_add(1);
901 if job.step != 0 {
902 job.faults += 1;
903 if job.faults >= ANALOG_FAULT_LIMIT {
904 job.outcome = Some(AnalogRequirement::Absent);
905 job.step = 0;
906 }
907 }
908 }
909 }
910 }
911
912 // --------------------------------------------------------- foreground
913
914 /// The latest reading of `port`, ahead of the next publication.
915 pub fn reading(&self, port: Port) -> PortReading {
916 self.ports[index(port)].reading
917 }
918
919 /// Put the pad on `port` in analog mode and lock it there, one command
920 /// per VBlank, then check what it settled on. A request made while one is
921 /// running changes nothing. [`analog_outcome`]
922 /// (Self::analog_outcome) answers once that is done.
923 pub fn request_analog(&mut self, port: Port) {
924 let ctl = &mut self.ports[index(port)];
925 if ctl.job.step == 0 {
926 // With the motors wanted and not mapped, the same visit to
927 // configuration mode maps them.
928 let kind = if ctl.rumble_wanted && !ctl.mapped {
929 JobKind::AnalogRumble
930 } else {
931 JobKind::Analog
932 };
933 ctl.job = AnalogJob::start(kind);
934 }
935 }
936
937 /// Put the motors of the pad on `port` under the poll: map them, whenever
938 /// a DualShock in analog mode is there and again each time one is plugged
939 /// in, and send them [`set_rumble`](Self::set_rumble)'s request on every
940 /// poll from then on. [`rumble_mapped`](Self::rumble_mapped) says whether
941 /// the pad took it; a digital pad and a pad that refuses configuration
942 /// mode never do, and are asked once per plug-in.
943 pub fn enable_rumble(&mut self, port: Port) {
944 let ctl = &mut self.ports[index(port)];
945 ctl.rumble_wanted = true;
946 ctl.refused = false;
947 if ctl.job.step == 0 && !ctl.mapped {
948 ctl.job = AnalogJob::start(JobKind::Rumble);
949 }
950 }
951
952 /// Stop wanting the motors on `port`: they are asked to stop on the next
953 /// poll, and the pad is not mapped again after a replug.
954 pub fn disable_rumble(&mut self, port: Port) {
955 let ctl = &mut self.ports[index(port)];
956 ctl.rumble_wanted = false;
957 ctl.rumble = Rumble::OFF;
958 }
959
960 /// What the motors on `port` are asked to do on every poll. Nothing
961 /// reaches a pad until it is mapped.
962 pub fn set_rumble(&mut self, port: Port, rumble: Rumble) {
963 self.ports[index(port)].rumble = rumble;
964 }
965
966 /// What the motors on `port` are asked for.
967 pub fn rumble(&self, port: Port) -> Rumble {
968 self.ports[index(port)].rumble
969 }
970
971 /// Whether the pad on `port` took the motor mapping.
972 pub fn rumble_mapped(&self, port: Port) -> bool {
973 self.ports[index(port)].mapped
974 }
975
976 /// Whether the pad on `port` was asked for its motors and did not take
977 /// the mapping.
978 pub fn rumble_refused(&self, port: Port) -> bool {
979 self.ports[index(port)].refused
980 }
981
982 /// Ask every motor on both ports to stop: for a pause, a menu or an exit.
983 /// The pads hear it on their next poll.
984 pub fn stop_motors(&mut self) {
985 for ctl in &mut self.ports {
986 ctl.rumble = Rumble::OFF;
987 }
988 }
989
990 /// Whether any motor is being asked to run.
991 pub fn motors_requested(&self) -> bool {
992 self.ports.iter().any(|ctl| !ctl.rumble.is_off())
993 }
994
995 /// What the pad on `port` settled on after [`request_analog`]
996 /// (Self::request_analog); `None` while the request is still running or
997 /// none was made.
998 pub fn analog_outcome(&self, port: Port) -> Option<AnalogRequirement> {
999 self.ports[index(port)].job.outcome
1000 }
1001
1002 /// Whether an analog request on `port` is still running.
1003 pub fn analog_pending(&self, port: Port) -> bool {
1004 self.ports[index(port)].job.step != 0
1005 }
1006
1007 /// Take the serial port for a foreground driver, if no transaction is on
1008 /// the wire. While held, VBlanks poll nothing and the snapshot stands.
1009 pub fn try_lease(&mut self) -> bool {
1010 if self.owner == Owner::Engine && self.phase == Phase::Idle {
1011 self.owner = Owner::Lease;
1012 true
1013 } else {
1014 false
1015 }
1016 }
1017
1018 /// Take the serial port now, abandoning a transaction in flight: for a
1019 /// caller that has waited as long as it can. The abandoned port reads
1020 /// [`Health::Faulted`] until its next transaction.
1021 pub fn force_lease(&mut self) {
1022 if self.phase != Phase::Idle {
1023 self.abandon();
1024 }
1025 self.owner = Owner::Lease;
1026 }
1027
1028 /// Give the serial port back to the engine.
1029 pub fn release_lease(&mut self) {
1030 self.owner = Owner::Engine;
1031 }
1032}