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

psx_mc/
hardware.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2//! On-device SIO0 transport for a physical memory card (feature `hw`).
3//!
4//! Talks the raw card protocol byte by byte: assert the port, clock `0x81` to
5//! address the card, then a Read (`0x52`) or Write (`0x57`) command frame. The
6//! serial link is `psx-io`'s shared [`Transport`], the one `psx-pad` polls
7//! controllers with: the same select, the same ACK-paced byte exchange that
8//! watches the live `/ACK` level, the same release. A card's own timing is a
9//! longer `/ACK` budget, because its write commit stalls between bytes while
10//! flash settles.
11//!
12//! A [`HardwareCard`] holds the controller port while it exists: either the
13//! [`ControllerPort`] token itself ([`HardwareCard::on_port`] with the token,
14//! and [`release`](HardwareCard::release) gives it back) or a `&mut` borrow of
15//! one the program keeps for polling pads between saves.
16//!
17//! Timing is exposed as a runtime knob ([`HardwareCard::on_port_with_timing`])
18//! because real silicon varies: the emulator ACKs instantly, an official card
19//! needs the setup delay, and a write commit may need a longer ACK wait than a
20//! pad byte.
21//!
22//! [`HardwareCard::last_trace`] exposes bounded transport diagnostics. In
23//! particular, an `/ACK` timeout is never silently treated as a successful
24//! exchange: the rest of that transaction is aborted and the first failing byte
25//! remains visible to an on-console diagnostic.
26
27use crate::{Block, Error, Result, FRAME_COUNT, FRAME_SIZE};
28use core::borrow::BorrowMut;
29use psx_io::controller_port::{ExchangeError, Port, Transport};
30use psx_io::periph::ControllerPort;
31
32// Protocol bytes.
33const CARD_SELECT: u8 = 0x81;
34const CMD_READ: u8 = 0x52;
35const CMD_WRITE: u8 = 0x57;
36const ID1: u8 = 0x5a;
37const ACK1: u8 = 0x5c;
38const END_GOOD: u8 = 0x47;
39/// A card needs a slightly longer recovery interval after acknowledging the
40/// initial `0x81` device-select byte than it does between ordinary frame bytes.
41const FIRST_COMMAND_SETTLE_SPINS: u32 = 1_024;
42/// Conservative volatile-MMIO delay after a 128-byte sector write. Reference
43/// drivers leave at least two video periods before accessing the card again.
44/// This intentionally covers the slower 50 Hz case as well as 60 Hz consoles.
45///
46/// This is the wait the blocking [`Block::write_frame`] spins away. In the
47/// emulator one spin costs about 8 cycles, which makes it between five and six
48/// video periods (a VoXide save step, drawing included, takes seven); it is
49/// not measured on a console. A
50/// [`CardJob`](crate::CardJob) keeps the same wait as
51/// [`SETTLE_VBLANKS`](crate::SETTLE_VBLANKS) vblanks instead of spinning.
52const POST_WRITE_SETTLE_SPINS: u32 = 400_000;
53
54/// Which controller/card port to use.
55pub type Slot = Port;
56
57/// The first low-level failure observed in the latest frame transaction.
58#[derive(Copy, Clone, Debug, PartialEq, Eq)]
59pub enum TransportFault {
60    /// No low-level timeout was observed.
61    None,
62    /// SIO0 never became ready to accept the next byte.
63    TxTimeout,
64    /// SIO0 never returned a byte after transmission.
65    RxTimeout,
66    /// The card did not pulse `/ACK` after a non-final byte.
67    AckTimeout,
68    /// `/ACK` was observed, but the live line did not return high.
69    AckReleaseTimeout,
70}
71
72/// Compact evidence from the latest raw read/write transaction.
73#[derive(Copy, Clone, Debug, PartialEq, Eq)]
74pub struct TransportTrace {
75    /// Total byte exchanges attempted before the transaction was aborted.
76    pub exchanges: u16,
77    /// Number of `/ACK` pulses observed.
78    pub acknowledgements: u16,
79    /// First low-level fault.
80    pub fault: TransportFault,
81    /// Zero-based exchange at which `fault` occurred, or `0xffff` for none.
82    pub fault_exchange: u16,
83    /// First ten response bytes (flags, IDs, echoes and acknowledgements).
84    pub response_prefix: [u8; 10],
85}
86
87impl TransportTrace {
88    const fn new() -> Self {
89        Self {
90            exchanges: 0,
91            acknowledgements: 0,
92            fault: TransportFault::None,
93            fault_exchange: u16::MAX,
94            response_prefix: [0xff; 10],
95        }
96    }
97}
98
99/// Tunable transfer timing (bounded MMIO spin counts). Defaults mirror the pad.
100#[derive(Copy, Clone, Debug)]
101pub struct Timing {
102    /// Delay after asserting select, before the first byte (strict-pad setup).
103    pub setup_spins: u32,
104    /// Bound on waiting for TX-ready / RX-filled per byte.
105    pub byte_spins: u32,
106    /// Bound on waiting for the `/ACK` pulse (raise for slow write commits).
107    pub ack_spins: u32,
108}
109
110impl Default for Timing {
111    fn default() -> Self {
112        let card = psx_io::controller_port::Timing::CARD;
113        Timing {
114            setup_spins: card.setup_spins,
115            byte_spins: card.byte_spins,
116            ack_spins: card.ack_spins,
117        }
118    }
119}
120
121impl Timing {
122    fn link(self) -> psx_io::controller_port::Timing {
123        psx_io::controller_port::Timing {
124            setup_spins: self.setup_spins,
125            byte_spins: self.byte_spins,
126            ack_spins: self.ack_spins,
127        }
128    }
129}
130
131/// A physical memory card reached over SIO0.
132///
133/// `P` is how the card holds the port: the [`ControllerPort`] token (the
134/// default) or a `&mut ControllerPort` borrowed from the program for the
135/// length of the card's use. While a card holds the port, a pad poll cannot
136/// borrow it:
137///
138/// ```compile_fail,E0499
139/// use psx_mc::{HardwareCard, Slot};
140/// use psx_io::periph::ControllerPort;
141///
142/// // SAFETY: the doctest never touches the port; it only has to compile.
143/// let mut port = unsafe { ControllerPort::steal() };
144/// let mut card = HardwareCard::on_port(&mut port, Slot::One);
145/// let other_driver = &mut port; // the card still holds the borrow
146/// let _ = card.last_trace();
147/// let _ = other_driver;
148/// ```
149pub struct HardwareCard<P = ControllerPort> {
150    port: P,
151    slot: Slot,
152    timing: Timing,
153    trace: TransportTrace,
154}
155
156impl HardwareCard<ControllerPort> {
157    /// A card on the given `slot` with default timing.
158    #[deprecated(note = "use `HardwareCard::on_port` with the `ControllerPort` token")]
159    pub fn new(slot: Slot) -> Self {
160        Self::on_port(steal_port(), slot)
161    }
162}
163
164/// The token for a deprecated constructor that never took one.
165fn steal_port() -> ControllerPort {
166    // SAFETY: a token is a logic guard, not a memory-safety one (see
167    // `psx_io::periph`), and the old constructors never took one.
168    unsafe { ControllerPort::steal() }
169}
170
171impl<P: BorrowMut<ControllerPort>> HardwareCard<P> {
172    /// A card on `slot`, reached through `port` (the token, or a borrow of
173    /// it), with the memory card's default [`Timing`].
174    pub fn on_port(port: P, slot: Slot) -> Self {
175        Self::on_port_with_timing(port, slot, Timing::default())
176    }
177
178    /// [`on_port`](Self::on_port) with custom [`Timing`], for tuning against
179    /// real silicon.
180    pub fn on_port_with_timing(port: P, slot: Slot, timing: Timing) -> Self {
181        HardwareCard {
182            port,
183            slot,
184            timing,
185            trace: TransportTrace::new(),
186        }
187    }
188
189    /// Give the port back: the token when the card owned it, the borrow
190    /// otherwise.
191    pub fn release(self) -> P {
192        self.port
193    }
194
195    /// Diagnostic evidence from the most recent frame read or write.
196    pub fn last_trace(&self) -> TransportTrace {
197        self.trace
198    }
199
200    /// The port, between transactions, for another driver that shares it (a
201    /// pad poll). Every frame read or write finishes inside its own call, so
202    /// the card is never mid-transaction when this is reachable.
203    pub fn controller_port(&mut self) -> &mut ControllerPort {
204        self.port.borrow_mut()
205    }
206}
207
208/// One frame transaction's view of the port: the shared transport plus the
209/// card's trace of what happened on it.
210struct Link<'a, T> {
211    bus: &'a mut T,
212    slot: Slot,
213    timing: Timing,
214    trace: TransportTrace,
215}
216
217impl<T: Transport> Link<'_, T> {
218    fn select(&mut self) {
219        if !self.bus.begin_card(self.slot, self.timing.link()) {
220            // The previous transaction left `/ACK` asserted and it never
221            // released. Every exchange fails from here.
222            self.record_fault(TransportFault::AckReleaseTimeout, 0);
223        }
224    }
225
226    fn record_fault(&mut self, fault: TransportFault, exchange: u16) {
227        if self.trace.fault == TransportFault::None {
228            self.trace.fault = fault;
229            self.trace.fault_exchange = exchange;
230        }
231    }
232
233    fn note_reply(&mut self, exchange: u16, reply: u8) {
234        if (exchange as usize) < self.trace.response_prefix.len() {
235            self.trace.response_prefix[exchange as usize] = reply;
236        }
237        self.trace.exchanges = exchange + 1;
238    }
239
240    /// Clock one byte and, when `wait_ack`, wait for the card's `/ACK` pulse so
241    /// the next byte is not clocked early. Returns the received byte, or
242    /// `0xff` once the transaction has failed.
243    fn xfer(&mut self, tx: u8, wait_ack: bool) -> u8 {
244        if self.trace.fault != TransportFault::None {
245            return 0xff;
246        }
247        let exchange = self.trace.exchanges;
248        match self
249            .bus
250            .exchange_card(self.slot, tx, !wait_ack, self.timing.link())
251        {
252            Ok(reply) => {
253                self.note_reply(exchange, reply);
254                if wait_ack {
255                    self.trace.acknowledgements += 1;
256                }
257                reply
258            }
259            Err(ExchangeError::TxTimeout) => {
260                self.record_fault(TransportFault::TxTimeout, exchange);
261                0xff
262            }
263            Err(ExchangeError::RxTimeout) => {
264                self.record_fault(TransportFault::RxTimeout, exchange);
265                0xff
266            }
267            Err(ExchangeError::AckTimeout { reply }) => {
268                self.note_reply(exchange, reply);
269                self.record_fault(TransportFault::AckTimeout, exchange);
270                reply
271            }
272            Err(ExchangeError::AckStuck { reply }) => {
273                self.note_reply(exchange, reply);
274                self.trace.acknowledgements += 1;
275                self.record_fault(TransportFault::AckReleaseTimeout, exchange);
276                reply
277            }
278        }
279    }
280
281    fn end(&mut self) {
282        let clean = self.trace.fault == TransportFault::None;
283        self.bus.finish(clean);
284    }
285
286    fn read_frame(&mut self, frame: u16, out: &mut [u8; FRAME_SIZE]) -> Result<()> {
287        let msb = (frame >> 8) as u8;
288        let lsb = frame as u8;
289
290        self.select();
291        self.xfer(CARD_SELECT, true); // open bus
292        self.bus.delay(FIRST_COMMAND_SETTLE_SPINS);
293        let flags = self.xfer(CMD_READ, true);
294        let id1 = self.xfer(0x00, true); // 0x5A
295        let _id2 = self.xfer(0x00, true); // 0x5D
296        let _ = self.xfer(msb, true); // 0x00
297        let _ = self.xfer(lsb, true); // MSB echo
298        let ack1 = self.xfer(0x00, true); // 0x5C
299        let _ack2 = self.xfer(0x00, true); // 0x5D
300        let emsb = self.xfer(0x00, true); // MSB
301        let elsb = self.xfer(0x00, true); // LSB
302        for b in out.iter_mut() {
303            *b = self.xfer(0x00, true);
304        }
305        let chk = self.xfer(0x00, true);
306        let end = self.xfer(0x00, false); // terminator, no ACK
307        self.end();
308
309        if id1 == 0xff {
310            return Err(Error::NoCard);
311        }
312        // FLAG bit 2 reports an error from the previous write transaction.
313        if flags & 0x04 != 0
314            || id1 != ID1
315            || ack1 != ACK1
316            || emsb != msb
317            || elsb != lsb
318            || end != END_GOOD
319        {
320            return Err(Error::Protocol);
321        }
322        let mut want = msb ^ lsb;
323        for &b in out.iter() {
324            want ^= b;
325        }
326        if want != chk {
327            return Err(Error::BadChecksum);
328        }
329        Ok(())
330    }
331
332    fn write_frame(&mut self, frame: u16, data: &[u8; FRAME_SIZE]) -> Result<()> {
333        let msb = (frame >> 8) as u8;
334        let lsb = frame as u8;
335        let mut chk = msb ^ lsb;
336        for &b in data.iter() {
337            chk ^= b;
338        }
339
340        self.select();
341        self.xfer(CARD_SELECT, true); // flag
342        self.bus.delay(FIRST_COMMAND_SETTLE_SPINS);
343        self.xfer(CMD_WRITE, true);
344        let id1 = self.xfer(0x00, true); // 0x5A
345        let _id2 = self.xfer(0x00, true); // 0x5D
346        let _ = self.xfer(msb, true); // 0x00
347        let _ = self.xfer(lsb, true); // MSB echo
348        for &b in data.iter() {
349            self.xfer(b, true);
350        }
351        self.xfer(chk, true); // commit happens here (flash write)
352        let ack1 = self.xfer(0x00, true); // 0x5C
353        let _ack2 = self.xfer(0x00, true); // 0x5D
354        let end = self.xfer(0x00, false); // terminator
355        self.end();
356
357        if id1 == 0xff {
358            return Err(Error::NoCard);
359        }
360        if id1 != ID1 || ack1 != ACK1 {
361            return Err(Error::Protocol);
362        }
363        if end != END_GOOD {
364            // 0x4E = bad checksum / not written.
365            return Err(Error::Protocol);
366        }
367        Ok(())
368    }
369}
370
371/// Run one frame transaction on `bus`, leaving its trace in `trace`.
372fn transact<T: Transport, R>(
373    bus: &mut T,
374    slot: Slot,
375    timing: Timing,
376    trace: &mut TransportTrace,
377    run: impl FnOnce(&mut Link<'_, T>) -> R,
378) -> R {
379    let mut link = Link {
380        bus,
381        slot,
382        timing,
383        trace: TransportTrace::new(),
384    };
385    let result = run(&mut link);
386    *trace = link.trace;
387    result
388}
389
390fn check_range(frame: u16) -> Result<()> {
391    if (frame as usize) < FRAME_COUNT {
392        Ok(())
393    } else {
394        Err(Error::OutOfRange)
395    }
396}
397
398/// One frame write on `bus`. With `settle`, the card is then left idle while
399/// its non-volatile write finishes; starting another transaction too early can
400/// produce a protocol-successful readback while still losing directory updates
401/// across a power cycle. Without it, the wait is the caller's to keep (see
402/// [`Block::write_frame_unsettled`]). A frame refused before the port was
403/// touched owes no wait.
404fn write_transaction<T: Transport>(
405    bus: &mut T,
406    slot: Slot,
407    timing: Timing,
408    trace: &mut TransportTrace,
409    frame: u16,
410    data: &[u8; FRAME_SIZE],
411    settle: bool,
412) -> Result<()> {
413    check_range(frame)?;
414    let result = transact(bus, slot, timing, trace, |link| {
415        link.write_frame(frame, data)
416    });
417    if settle {
418        bus.delay(POST_WRITE_SETTLE_SPINS);
419    }
420    result
421}
422
423impl<P: BorrowMut<ControllerPort>> Block for HardwareCard<P> {
424    fn read_frame(&mut self, frame: u16, out: &mut [u8; FRAME_SIZE]) -> Result<()> {
425        check_range(frame)?;
426        let (slot, timing) = (self.slot, self.timing);
427        transact(
428            self.port.borrow_mut(),
429            slot,
430            timing,
431            &mut self.trace,
432            |link| link.read_frame(frame, out),
433        )
434    }
435
436    fn write_frame(&mut self, frame: u16, data: &[u8; FRAME_SIZE]) -> Result<()> {
437        let (slot, timing) = (self.slot, self.timing);
438        write_transaction(
439            self.port.borrow_mut(),
440            slot,
441            timing,
442            &mut self.trace,
443            frame,
444            data,
445            true,
446        )
447    }
448
449    fn write_frame_unsettled(&mut self, frame: u16, data: &[u8; FRAME_SIZE]) -> Result<()> {
450        let (slot, timing) = (self.slot, self.timing);
451        write_transaction(
452            self.port.borrow_mut(),
453            slot,
454            timing,
455            &mut self.trace,
456            frame,
457            data,
458            false,
459        )
460    }
461}
462
463#[cfg(test)]
464mod tests;