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

psx_io/
controller_port.rs

1//! The controller and memory-card port: one serial transport shared by every
2//! driver on it.
3//!
4//! A pad and a memory card sit on the same wires, so a program has one owner
5//! for them, the [`ControllerPort`] token, and the drivers (`psx-pad`,
6//! `psx-mc`) borrow it for the length of a transaction. What they borrow is
7//! the [`Transport`]: select a socket, clock bytes with the device's `/ACK`
8//! pulse pacing each one, release the socket. The pad's timing is the
9//! reference, since it was tuned on an original SCPH-1200, a clone and an
10//! SCPH-110; a memory card uses the same exchange with a longer budget for the
11//! `/ACK` after a flash write.
12//!
13//! Register addresses and bit layouts live in [`psx_hw::sio::sio0`].
14//!
15//! ```text
16//! let mut port = peripherals.controller_port;
17//! let mut pads = psx_pad::PadReader::port1();
18//! let state = pads.poll(&mut port);
19//! let mut card = psx_mc::Card::new(psx_mc::HardwareCard::on_port(&mut port, Slot::One));
20//! ```
21
22use crate::periph::ControllerPort;
23use crate::{read_u32, read_u8, write_u16, write_u8};
24use psx_hw::sio::sio0;
25
26/// Which socket a transaction addresses.
27#[derive(Copy, Clone, Debug, PartialEq, Eq)]
28pub enum Port {
29    /// Controller port 1 and memory-card slot 1.
30    One,
31    /// Controller port 2 and memory-card slot 2.
32    Two,
33}
34
35impl Port {
36    /// Whether this is the second socket.
37    #[inline(always)]
38    pub const fn is_two(self) -> bool {
39        matches!(self, Port::Two)
40    }
41}
42
43/// Spin budgets for one transaction. Each spin is one bounded `STAT` read, so
44/// the budgets bound the time a missing or wedged device can cost.
45#[derive(Copy, Clone, Debug, PartialEq, Eq)]
46pub struct Timing {
47    /// Delay after selecting the socket, before the first byte. The original
48    /// SCPH-1200 gives no answer without it; fast clones do not care.
49    pub setup_spins: u32,
50    /// Bound on the byte shift itself (TX ready, then RX filled).
51    pub byte_spins: u32,
52    /// Bound on each wait for the device's `/ACK` to assert, and again to
53    /// release.
54    pub ack_spins: u32,
55}
56
57impl Timing {
58    /// The pad's timing, measured on silicon: 1,024 setup spins (the
59    /// SCPH-1200 floor sits between 384 and 768), and a 2,048-spin `/ACK`
60    /// wait, which exceeds the BIOS's own 100 microsecond DSR timeout.
61    pub const PAD: Timing = Timing {
62        setup_spins: 1_024,
63        byte_spins: 32_768,
64        ack_spins: 2_048,
65    };
66
67    /// The memory card's timing: the pad's setup and byte budgets, and a long
68    /// `/ACK` budget because a card can hold `/ACK` back while a frame's flash
69    /// write commits.
70    pub const CARD: Timing = Timing {
71        setup_spins: 1_024,
72        byte_spins: 32_768,
73        ack_spins: 200_000,
74    };
75}
76
77/// Why one byte exchange failed.
78#[derive(Copy, Clone, Debug, PartialEq, Eq)]
79pub enum ExchangeError {
80    /// The port never became ready to take the byte.
81    TxTimeout,
82    /// The byte shifted out but no reply came back.
83    RxTimeout,
84    /// The reply came back and the device never pulsed `/ACK`; the reply is
85    /// kept because an absent device answers `0xFF` here.
86    AckTimeout {
87        /// The byte received before the wait.
88        reply: u8,
89    },
90    /// The device pulsed `/ACK` but held it asserted.
91    AckStuck {
92        /// The byte received before the wait.
93        reply: u8,
94    },
95}
96
97/// The six accesses the transport makes to the port, and the transaction
98/// steps built on them.
99///
100/// [`ControllerPort`] implements it on the registers. Host tests implement it
101/// on a model of a pad or a card, so the production timing code runs under
102/// test unchanged.
103pub trait Transport {
104    /// Read the status register.
105    fn status(&mut self) -> u32;
106    /// Pop one received byte.
107    fn receive(&mut self) -> u8;
108    /// Start shifting one byte out.
109    fn transmit(&mut self, byte: u8);
110    /// Write the mode register.
111    fn set_mode(&mut self, value: u16);
112    /// Write the baud-rate reload.
113    fn set_baud(&mut self, value: u16);
114    /// Write the control register.
115    fn set_control(&mut self, value: u16);
116
117    /// Configure the port for 250 kHz, 8N1 and assert `/CS` on `port`.
118    ///
119    /// The `/ACK` interrupt is left disarmed: arming it disturbed real
120    /// transfers (the SCPH-1200 stopped answering, a clone's bytes corrupted),
121    /// so the transport watches the live `/ACK` level in `STAT` instead.
122    fn select(&mut self, port: Port) {
123        self.select_with(port, false);
124    }
125
126    /// [`select`](Self::select) with the `/ACK` interrupt armed when
127    /// `arm_ack_irq` is set, so `STAT` latches each pulse. Memory cards use
128    /// this because a CPU interrupt can hide a complete short ACK pulse.
129    fn select_with(&mut self, port: Port, arm_ack_irq: bool) {
130        self.set_mode(sio0::MODE_8N1);
131        self.set_baud(sio0::BAUD_250KHZ);
132        // Clear any stale IRQ latch from the previous transaction, then
133        // assert the select line.
134        self.set_control(sio0::ctrl::ACK);
135        self.set_control(sio0::selected_ctrl(port.is_two(), arm_ack_irq));
136    }
137
138    /// Release `/CS`, which resets the attached device's state machine.
139    fn deselect(&mut self) {
140        self.set_control(0);
141    }
142
143    /// Reset the port's UART. A deselect alone need not cancel a late reply
144    /// still in the shifter, so a failed transaction ends with this.
145    fn reset(&mut self) {
146        self.set_control(sio0::ctrl::RESET);
147    }
148
149    /// Pop up to a few stale bytes so the next reply lines up with the
150    /// first byte of the transaction. Bounded, so a stuck "RX not empty" flag
151    /// cannot spin forever.
152    fn drain_receive(&mut self) {
153        let mut popped = 0;
154        while self.status() & sio0::stat::RX_NOT_EMPTY != 0 && popped < 16 {
155            let _ = self.receive();
156            popped += 1;
157        }
158    }
159
160    /// Burn time with `spins` status reads, which the compiler cannot remove.
161    fn delay(&mut self, spins: u32) {
162        let mut remaining = spins;
163        while remaining > 0 {
164            let _ = self.status();
165            remaining -= 1;
166            core::hint::spin_loop();
167        }
168    }
169
170    /// Spin until any bit of `mask` is set in the status register, at most
171    /// `spins` reads after the first. `false` on timeout.
172    fn wait_status_set(&mut self, mask: u32, spins: u32) -> bool {
173        let mut remaining = spins;
174        while self.status() & mask == 0 {
175            if remaining == 0 {
176                return false;
177            }
178            remaining -= 1;
179            core::hint::spin_loop();
180        }
181        true
182    }
183
184    /// Spin until every bit of `mask` is clear in the status register, at most
185    /// `spins` reads after the first. `false` on timeout.
186    fn wait_status_clear(&mut self, mask: u32, spins: u32) -> bool {
187        let mut remaining = spins;
188        while self.status() & mask != 0 {
189            if remaining == 0 {
190                return false;
191            }
192            remaining -= 1;
193            core::hint::spin_loop();
194        }
195        true
196    }
197
198    /// Start a transaction: select `port`, wait out the setup time, drop
199    /// stale bytes, and wait for an `/ACK` left asserted by an aborted
200    /// transaction to release, so it is not counted as the first byte's.
201    ///
202    /// `false` means the line never released. Call [`finish`](Self::finish)
203    /// either way.
204    fn begin(&mut self, port: Port, timing: Timing) -> bool {
205        self.select(port);
206        self.finish_begin(timing)
207    }
208
209    /// Begin a memory-card transaction with the SIO ACK interrupt latch
210    /// armed. The card's short pulse can fall entirely inside an unrelated
211    /// CPU interrupt, after which the live DSR level no longer records it.
212    fn begin_card(&mut self, port: Port, timing: Timing) -> bool {
213        self.select_with(port, true);
214        let ready = self.finish_begin(timing);
215        if ready {
216            // A late ACK from the preceding transaction can arrive during
217            // setup. Its live level is gone now, but its IRQ latch must not
218            // count as the first byte's acknowledgement.
219            self.set_control(sio0::selected_ctrl(port.is_two(), true) | sio0::ctrl::ACK);
220        }
221        ready
222    }
223
224    /// Shared setup, stale RX drain and live ACK release check after select.
225    fn finish_begin(&mut self, timing: Timing) -> bool {
226        self.delay(timing.setup_spins);
227        self.drain_receive();
228        self.wait_status_clear(sio0::stat::DSR_LEVEL, timing.ack_spins)
229    }
230
231    /// End a transaction: release `/CS`, and after a failed one reset the
232    /// UART as well. The next [`select`](Self::select) restores mode and baud.
233    fn finish(&mut self, succeeded: bool) {
234        self.deselect();
235        if !succeeded {
236            self.reset();
237        }
238    }
239
240    /// Clock one byte and wait for the device's `/ACK`.
241    ///
242    /// Waits for TX ready, writes `byte`, and watches the live `/ACK` level
243    /// while the reply shifts in, so a pulse that ends before the reply
244    /// arrives is not missed. Unless `is_last` (the final byte of a packet is
245    /// never acknowledged), it then waits for `/ACK` to assert if it has not
246    /// yet, and to release, before the next byte may go. RX-ready alone only
247    /// says the byte arrived, not that the device is ready for another.
248    ///
249    /// No control-register write happens mid-transaction.
250    fn exchange(&mut self, byte: u8, is_last: bool, timing: Timing) -> Result<u8, ExchangeError> {
251        if !self.wait_status_set(sio0::stat::TX_READY, timing.byte_spins) {
252            return Err(ExchangeError::TxTimeout);
253        }
254        self.transmit(byte);
255        let mut ack_seen = false;
256        let mut remaining = timing.byte_spins;
257        loop {
258            let status = self.status();
259            ack_seen |= status & sio0::stat::DSR_LEVEL != 0;
260            if status & sio0::stat::RX_NOT_EMPTY != 0 {
261                break;
262            }
263            if remaining == 0 {
264                return Err(ExchangeError::RxTimeout);
265            }
266            remaining -= 1;
267            core::hint::spin_loop();
268        }
269        let reply = self.receive();
270        if !is_last {
271            if !ack_seen && !self.wait_status_set(sio0::stat::DSR_LEVEL, timing.ack_spins) {
272                return Err(ExchangeError::AckTimeout { reply });
273            }
274            if !self.wait_status_clear(sio0::stat::DSR_LEVEL, timing.ack_spins) {
275                return Err(ExchangeError::AckStuck { reply });
276            }
277        }
278        Ok(reply)
279    }
280
281    /// Card byte exchange. STAT.IRQ latches an ACK edge across a CPU
282    /// interrupt; the live DSR level still has to release before the next
283    /// byte, and CTRL.ACK clears only this byte's latch while /CS stays low.
284    fn exchange_card(
285        &mut self,
286        port: Port,
287        byte: u8,
288        is_last: bool,
289        timing: Timing,
290    ) -> Result<u8, ExchangeError> {
291        if !self.wait_status_set(sio0::stat::TX_READY, timing.byte_spins) {
292            return Err(ExchangeError::TxTimeout);
293        }
294        self.transmit(byte);
295        if !self.wait_status_set(sio0::stat::RX_NOT_EMPTY, timing.byte_spins) {
296            return Err(ExchangeError::RxTimeout);
297        }
298        let reply = self.receive();
299        if !is_last {
300            if !self.wait_status_set(sio0::stat::IRQ, timing.ack_spins) {
301                return Err(ExchangeError::AckTimeout { reply });
302            }
303            if !self.wait_status_clear(sio0::stat::DSR_LEVEL, timing.ack_spins) {
304                return Err(ExchangeError::AckStuck { reply });
305            }
306            self.set_control(sio0::selected_ctrl(port.is_two(), true) | sio0::ctrl::ACK);
307        }
308        Ok(reply)
309    }
310}
311
312impl Transport for ControllerPort {
313    #[inline(always)]
314    fn status(&mut self) -> u32 {
315        // SAFETY: STAT is the port's aligned 32-bit status register; reading it
316        // has no side effects. The `&mut` borrow of the token is the proof no
317        // other driver is mid-transaction.
318        unsafe { read_u32(sio0::STAT) }
319    }
320
321    #[inline(always)]
322    fn receive(&mut self) -> u8 {
323        // SAFETY: a byte read of DATA pops one RX FIFO byte.
324        unsafe { read_u8(sio0::DATA) }
325    }
326
327    #[inline(always)]
328    fn transmit(&mut self, byte: u8) {
329        // SAFETY: a byte write to DATA clocks it out of the port.
330        unsafe { write_u8(sio0::DATA, byte) }
331    }
332
333    #[inline(always)]
334    fn set_mode(&mut self, value: u16) {
335        // SAFETY: MODE is the port's 16-bit mode register.
336        unsafe { write_u16(sio0::MODE, value) }
337    }
338
339    #[inline(always)]
340    fn set_baud(&mut self, value: u16) {
341        // SAFETY: BAUD is the port's 16-bit baud-rate reload.
342        unsafe { write_u16(sio0::BAUD, value) }
343    }
344
345    #[inline(always)]
346    fn set_control(&mut self, value: u16) {
347        // SAFETY: CTRL is the port's 16-bit control register; it selects the
348        // socket and resets the port, nothing else.
349        unsafe { write_u16(sio0::CTRL, value) }
350    }
351}
352
353#[cfg(test)]
354mod tests {
355    extern crate std;
356
357    use super::*;
358    use std::vec::Vec;
359
360    /// A scripted port: each status read pops the next scripted word, and
361    /// every write is logged.
362    #[derive(Default)]
363    struct Script {
364        status: Vec<u32>,
365        reads: usize,
366        received: Vec<u8>,
367        sent: Vec<u8>,
368        control: Vec<u16>,
369    }
370
371    impl Script {
372        fn with_status(words: &[u32]) -> Self {
373            Script {
374                status: words.to_vec(),
375                ..Script::default()
376            }
377        }
378    }
379
380    impl Transport for Script {
381        fn status(&mut self) -> u32 {
382            // Past the script, hold the last word.
383            let word = self
384                .status
385                .get(self.reads)
386                .or(self.status.last())
387                .copied()
388                .unwrap_or(0);
389            self.reads += 1;
390            word
391        }
392        fn receive(&mut self) -> u8 {
393            self.received.pop().unwrap_or(0xff)
394        }
395        fn transmit(&mut self, byte: u8) {
396            self.sent.push(byte);
397        }
398        fn set_mode(&mut self, _value: u16) {}
399        fn set_baud(&mut self, _value: u16) {}
400        fn set_control(&mut self, value: u16) {
401            self.control.push(value);
402        }
403    }
404
405    const TX: u32 = sio0::stat::TX_READY;
406    const RX: u32 = sio0::stat::RX_NOT_EMPTY;
407    const DSR: u32 = sio0::stat::DSR_LEVEL;
408    const TIMING: Timing = Timing {
409        setup_spins: 2,
410        byte_spins: 4,
411        ack_spins: 4,
412    };
413
414    #[test]
415    fn the_token_is_the_only_way_to_a_port_that_implements_the_transport() {
416        fn takes_transport<T: Transport>(_: &mut T) {}
417        // SAFETY: a test-local token on the host, where no register is touched.
418        let mut port = unsafe { ControllerPort::steal() };
419        takes_transport(&mut port);
420        assert_eq!(core::mem::size_of::<ControllerPort>(), 0);
421    }
422
423    #[test]
424    fn select_clears_the_latch_then_asserts_the_port_without_arming_the_ack_interrupt() {
425        for (port, selected) in [(Port::One, 0x0003), (Port::Two, 0x2003)] {
426            let mut bus = Script::default();
427            bus.select(port);
428            assert_eq!(bus.control, [sio0::ctrl::ACK, selected]);
429            assert_eq!(selected & sio0::ctrl::ACK_IRQ_EN, 0);
430        }
431    }
432
433    #[test]
434    fn a_failed_transaction_resets_the_uart_and_a_clean_one_only_releases_the_port() {
435        let mut bus = Script::default();
436        bus.finish(true);
437        assert_eq!(bus.control, [0]);
438        let mut bus = Script::default();
439        bus.finish(false);
440        assert_eq!(bus.control, [0, sio0::ctrl::RESET]);
441    }
442
443    #[test]
444    fn begin_drops_stale_bytes_and_waits_for_a_held_ack_to_release() {
445        // One stale byte (RX set), then drained, then DSR still high twice
446        // before it releases.
447        let mut bus = Script::with_status(&[0, 0, RX, 0, DSR, DSR, 0]);
448        bus.received.push(0x55);
449        assert!(bus.begin(Port::One, TIMING));
450        assert!(bus.received.is_empty());
451
452        let mut stuck = Script::with_status(&[DSR]);
453        assert!(!stuck.begin(Port::One, TIMING));
454    }
455
456    #[test]
457    fn card_begin_clears_an_ack_that_arrived_during_setup() {
458        // The earlier transaction's ACK arrives during the setup delay.
459        // Its live level has released by the time begin checks the line.
460        let mut bus = Script::with_status(&[sio0::stat::IRQ | DSR, 0, 0, 0]);
461        assert!(bus.begin_card(Port::One, TIMING));
462        assert_eq!(
463            bus.control,
464            [
465                sio0::ctrl::ACK,
466                sio0::selected_ctrl(false, true),
467                sio0::selected_ctrl(false, true) | sio0::ctrl::ACK,
468            ]
469        );
470    }
471
472    #[test]
473    fn an_acknowledged_byte_waits_for_ack_to_assert_and_release() {
474        // TX ready; RX arrives at once without an ack; ack asserts, releases.
475        let mut bus = Script::with_status(&[TX, RX, DSR, 0]);
476        bus.received.push(0x41);
477        assert_eq!(bus.exchange(0x42, false, TIMING), Ok(0x41));
478        assert_eq!(bus.sent, [0x42]);
479        // No control write happened inside the exchange.
480        assert!(bus.control.is_empty());
481    }
482
483    #[test]
484    fn an_ack_seen_while_the_reply_shifts_in_is_not_waited_for_again() {
485        // The pulse lands during the RX wait (DSR set, RX not yet), ends, and
486        // RX arrives after: only the release wait remains.
487        let mut bus = Script::with_status(&[TX, DSR, RX, 0]);
488        bus.received.push(0x5a);
489        assert_eq!(bus.exchange(0x00, false, TIMING), Ok(0x5a));
490    }
491
492    #[test]
493    fn the_last_byte_of_a_packet_is_never_waited_on() {
494        let mut bus = Script::with_status(&[TX, RX]);
495        bus.received.push(0x80);
496        assert_eq!(bus.exchange(0x00, true, TIMING), Ok(0x80));
497        // Two status reads: TX ready and RX ready, nothing after.
498        assert_eq!(bus.reads, 2);
499    }
500
501    #[test]
502    fn card_ack_latch_survives_a_pulse_hidden_by_an_interrupt() {
503        // The reply arrived before the card's ACK. The next observation is
504        // after the pulse: DSR is low, but STAT.IRQ still records the edge.
505        let mut bus = Script::with_status(&[TX, RX, sio0::stat::IRQ, 0]);
506        bus.received.push(0x5a);
507        assert_eq!(bus.exchange_card(Port::One, 0x00, false, TIMING), Ok(0x5a));
508        assert_eq!(
509            bus.control,
510            [sio0::selected_ctrl(false, true) | sio0::ctrl::ACK]
511        );
512
513        let mut live = Script::with_status(&[TX, RX, 0]);
514        live.received.push(0x5a);
515        assert_eq!(
516            live.exchange(0x00, false, TIMING),
517            Err(ExchangeError::AckTimeout { reply: 0x5a })
518        );
519    }
520
521    #[test]
522    fn card_terminator_needs_no_ack_and_missing_card_times_out() {
523        let mut last = Script::with_status(&[TX, RX]);
524        last.received.push(0x47);
525        assert_eq!(last.exchange_card(Port::One, 0, true, TIMING), Ok(0x47));
526        assert_eq!(last.reads, 2);
527        assert!(last.control.is_empty());
528
529        let mut absent = Script::with_status(&[TX, RX, 0]);
530        absent.received.push(0xff);
531        assert_eq!(
532            absent.exchange_card(Port::One, 0x81, false, TIMING),
533            Err(ExchangeError::AckTimeout { reply: 0xff })
534        );
535    }
536
537    #[test]
538    fn each_failure_is_reported_with_its_stage() {
539        let mut bus = Script::with_status(&[0]);
540        assert_eq!(
541            bus.exchange(0x01, false, TIMING),
542            Err(ExchangeError::TxTimeout)
543        );
544        assert!(bus.sent.is_empty());
545
546        let mut bus = Script::with_status(&[TX, 0]);
547        assert_eq!(
548            bus.exchange(0x01, false, TIMING),
549            Err(ExchangeError::RxTimeout)
550        );
551
552        let mut bus = Script::with_status(&[TX, RX, 0]);
553        bus.received.push(0xff);
554        assert_eq!(
555            bus.exchange(0x01, false, TIMING),
556            Err(ExchangeError::AckTimeout { reply: 0xff })
557        );
558
559        let mut bus = Script::with_status(&[TX, RX | DSR, DSR]);
560        bus.received.push(0x41);
561        assert_eq!(
562            bus.exchange(0x01, false, TIMING),
563            Err(ExchangeError::AckStuck { reply: 0x41 })
564        );
565    }
566
567    #[test]
568    fn the_pad_and_card_budgets_differ_only_in_the_ack_wait() {
569        assert_eq!(
570            Timing {
571                ack_spins: Timing::PAD.ack_spins,
572                ..Timing::CARD
573            },
574            Timing::PAD
575        );
576        const { assert!(Timing::CARD.ack_spins > Timing::PAD.ack_spins) };
577    }
578}