psx_mc/lib.rs
1// SPDX-License-Identifier: GPL-2.0-or-later
2//! PlayStation 1 memory-card driver.
3//!
4//! Three layers, each usable on its own:
5//!
6//! 1. **Transport** -- a [`Block`] device exposes the card as 1024 raw 128-byte
7//! frames. [`HardwareCard`] talks to a physical card over SIO0 (feature
8//! `hw`, on by default); [`RamCard`] is an in-memory image for host tests and
9//! virtual saves.
10//! 2. **Filesystem** -- [`Card`] wraps any [`Block`] and implements the standard
11//! PS1 directory: named files, block allocation with the real link-chain,
12//! BIOS-visible title + icon frames, and per-frame XOR checksums. Saves show
13//! up in the console's memory-card manager like any retail game.
14//! 3. **Container** -- [`Card::write`] wraps payloads in a small self-describing
15//! header so [`Card::read`] can transparently handle both plain and (feature
16//! `compress`) LZSS-compressed saves.
17//!
18//! ## Why talk to SIO0 directly
19//!
20//! Like [`psx_pad`](../psx_pad), this avoids BIOS syscalls so the same code runs
21//! under an HLE BIOS side-load or a real boot. The card protocol is a fixed
22//! request/response the [`hardware`] module drives byte by byte, over the same
23//! shared SIO0 transport the pad driver polls controllers with, so the port has
24//! one owner (the `ControllerPort` token) however many drivers use it.
25//!
26//! ## Example
27//!
28//! ```text
29//! use psx_mc::{Card, HardwareCard, Slot};
30//!
31//! // `port` is the `ControllerPort` token (or a `&mut` of it, to keep polling
32//! // pads between saves).
33//! let mut card = Card::new(HardwareCard::on_port(&mut port, Slot::One));
34//! if !card.is_formatted()? {
35//! card.format()?;
36//! }
37//! card.write("BESLES-00000MYGAME01", "MY GAME", &save_bytes)?;
38//!
39//! let mut buf = [0u8; 8192];
40//! let len = card.read("BESLES-00000MYGAME01", &mut buf)?;
41//! ```
42//!
43//! ## Saving without stopping the frame
44//!
45//! `Card::write` on a [`HardwareCard`] is a blocking call: every frame
46//! transaction takes milliseconds and each write is followed by the card's
47//! commit time, so a save holds the CPU for seconds. A game loop that must
48//! keep drawing hands the same operations to a [`CardJob`], which reads the
49//! directory, runs them against a staged copy, then sends the writes one per
50//! step with the commit waits spread over vblanks. See the [`job`] docs.
51//!
52//! All logic below the transport is pure and covered by host unit tests
53//! (`cargo test --no-default-features`, optionally `--features compress`).
54
55#![no_std]
56#![allow(clippy::result_unit_err)]
57
58mod fs;
59pub mod job;
60mod ram;
61
62#[cfg(test)]
63mod tests;
64
65#[cfg(feature = "compress")]
66pub mod compress;
67
68#[cfg(feature = "hw")]
69#[doc(alias = "SIO0")]
70pub mod hardware;
71
72pub use job::{queue_frames, CardJob, Staged, Step, DIR_FRAMES, FORMAT_FRAMES, SETTLE_VBLANKS};
73pub use ram::RamCard;
74
75#[cfg(feature = "hw")]
76pub use hardware::{HardwareCard, Slot, TransportFault, TransportTrace};
77/// The token a [`HardwareCard`] drives the port through.
78#[cfg(feature = "hw")]
79pub use psx_io::periph::ControllerPort;
80
81// --------------------------------------------------------------------------
82// Card geometry (fixed by the hardware).
83// --------------------------------------------------------------------------
84
85/// Bytes per frame (the transfer unit of the serial protocol).
86pub const FRAME_SIZE: usize = 128;
87/// Frames per 8 KiB block.
88pub const FRAMES_PER_BLOCK: usize = 64;
89/// Total blocks on a standard card (block 0 is the directory).
90pub const BLOCK_COUNT: usize = 16;
91/// Total frames on a standard card.
92pub const FRAME_COUNT: usize = BLOCK_COUNT * FRAMES_PER_BLOCK; // 1024
93/// Total card size in bytes (128 KiB).
94pub const CARD_SIZE: usize = FRAME_COUNT * FRAME_SIZE;
95/// Usable save blocks (blocks 1..=15; block 0 holds the directory).
96pub const DATA_BLOCKS: usize = BLOCK_COUNT - 1;
97/// Maximum file-name length (region+product code + name), excluding the NUL.
98pub const MAX_NAME_LEN: usize = 20;
99/// Renamed to [`MAX_NAME_LEN`].
100#[deprecated(note = "renamed to `MAX_NAME_LEN`")]
101pub const MAX_NAME: usize = MAX_NAME_LEN;
102
103/// A native PS1 memory-card save icon.
104///
105/// The BIOS displays a 16×16, 4bpp indexed image. `pixels` contains two
106/// left-to-right pixels per byte (low nibble first); `palette` contains the 16
107/// BGR555 colours. This type represents one static icon frame.
108#[derive(Copy, Clone, Debug, PartialEq, Eq)]
109pub struct SaveIcon {
110 /// Sixteen BGR555 palette entries. Palette index zero is conventionally
111 /// transparent.
112 pub palette: [u16; 16],
113 /// 16×16 pixels at 4bpp: exactly one 128-byte memory-card frame.
114 pub pixels: [u8; FRAME_SIZE],
115}
116
117impl SaveIcon {
118 /// Construct a static save icon from its native palette and packed pixels.
119 pub const fn new(palette: [u16; 16], pixels: [u8; FRAME_SIZE]) -> Self {
120 Self { palette, pixels }
121 }
122}
123
124// --------------------------------------------------------------------------
125// Errors.
126// --------------------------------------------------------------------------
127
128/// Everything that can go wrong talking to a card or its filesystem.
129#[derive(Copy, Clone, Debug, PartialEq, Eq)]
130pub enum Error {
131 /// No card responded on the port (no `/ACK`), or it was removed mid-transfer.
132 NoCard,
133 /// The card broke protocol (bad ID/ACK/terminator byte).
134 Protocol,
135 /// A frame's stored checksum did not match its data (read); likely a
136 /// corrupt or half-written card.
137 BadChecksum,
138 /// Frame index past the end of the card.
139 OutOfRange,
140 /// The card has no valid `MC` directory header (needs [`Card::format`]).
141 NotFormatted,
142 /// No file with the requested name exists.
143 NotFound,
144 /// Not enough free blocks for the save.
145 NoSpace,
146 /// A file with that name already exists and `overwrite` was not set.
147 Exists,
148 /// The directory link-chain is inconsistent (corrupt card).
149 Corrupt,
150 /// The caller's read buffer is smaller than the stored payload.
151 BufferTooSmall,
152 /// The save is not a `psx-mc` container, or its header is malformed.
153 BadContainer,
154 /// The payload is compressed but this build lacks the `compress` feature,
155 /// or decompression failed.
156 Compression,
157 /// A supplied name/title was empty or too long.
158 BadName,
159}
160
161/// Convenience alias.
162pub type Result<T> = core::result::Result<T, Error>;
163
164// --------------------------------------------------------------------------
165// Block transport abstraction.
166// --------------------------------------------------------------------------
167
168/// A card as a flat array of [`FRAME_COUNT`] 128-byte frames.
169///
170/// This is the seam between the hardware and the filesystem: implement it once
171/// per backing (real card, RAM image, a file on a host) and the whole [`Card`]
172/// filesystem works unchanged.
173pub trait Block {
174 /// Read frame `frame` (0..[`FRAME_COUNT`]) into `out`.
175 fn read_frame(&mut self, frame: u16, out: &mut [u8; FRAME_SIZE]) -> Result<()>;
176 /// Write `data` to frame `frame` (0..[`FRAME_COUNT`]).
177 fn write_frame(&mut self, frame: u16, data: &[u8; FRAME_SIZE]) -> Result<()>;
178 /// [`write_frame`](Self::write_frame) without waiting out the card's
179 /// commit time afterwards.
180 ///
181 /// A physical card needs time to commit a frame to flash after the
182 /// transfer, and no other transaction may reach it until that has passed.
183 /// `write_frame` spins that time away inside the call; this variant returns
184 /// as soon as the transfer ends, and the caller owes the card
185 /// [`SETTLE_VBLANKS`] before the next read or write. [`CardJob`] is that
186 /// caller, spreading the wait over frames. A device with no commit time
187 /// (the default) simply writes.
188 fn write_frame_unsettled(&mut self, frame: u16, data: &[u8; FRAME_SIZE]) -> Result<()> {
189 self.write_frame(frame, data)
190 }
191}
192
193// --------------------------------------------------------------------------
194// Directory listing entry.
195// --------------------------------------------------------------------------
196
197/// One file as reported by [`Card::list`].
198///
199/// The fields stay public because games build `[Entry; N]` listing buffers
200/// with a struct literal (voxide's save menu, the hello-memcard example).
201/// Nothing relies on them for memory safety: [`Entry::name`] checks both the
202/// length and the UTF-8.
203#[derive(Copy, Clone, Debug, PartialEq, Eq)]
204pub struct Entry {
205 /// File name bytes (ASCII), `name_len` valid.
206 pub name: [u8; MAX_NAME_LEN + 1],
207 /// Valid length of `name`.
208 pub name_len: u8,
209 /// Number of 8 KiB blocks the file occupies.
210 pub blocks: u8,
211}
212
213impl Entry {
214 /// The file name as a `&str`.
215 ///
216 /// Names this crate writes are ASCII, but a listing reads whatever bytes
217 /// the card holds, so a corrupt or foreign card can carry anything. Such
218 /// a name (anything that is not ASCII), or a `name_len` past the buffer, reads as `"?"`.
219 pub fn name(&self) -> &str {
220 match self.name.get(..self.name_len as usize) {
221 // SAFETY: ASCII is valid UTF-8. Checking byte-wise keeps `from_utf8` and its validator
222 // (about 1 KB) out of the image; a name that is not ASCII reads as "?".
223 Some(bytes) if bytes.is_ascii() => unsafe { core::str::from_utf8_unchecked(bytes) },
224 _ => "?",
225 }
226 }
227}
228
229// --------------------------------------------------------------------------
230// The filesystem handle. Method bodies live in `fs.rs`.
231// --------------------------------------------------------------------------
232
233/// A memory card with the standard PS1 filesystem on top of a [`Block`] device.
234pub struct Card<B: Block> {
235 pub(crate) dev: B,
236}
237
238impl<B: Block> Card<B> {
239 /// Wrap a block device. Does no I/O; call [`Card::is_formatted`] /
240 /// [`Card::format`] as needed.
241 pub fn new(dev: B) -> Self {
242 Card { dev }
243 }
244
245 /// Recover the underlying block device.
246 pub fn into_inner(self) -> B {
247 self.dev
248 }
249
250 /// Borrow the underlying block device.
251 pub fn device(&mut self) -> &mut B {
252 &mut self.dev
253 }
254}
255
256/// The save-container header written ahead of every payload so reads are
257/// self-describing. 16 bytes, little-endian.
258///
259/// ```text
260/// 0 "PMC1" magic
261/// 4 flags (u8) bit0 = payload is LZSS-compressed
262/// 5 reserved[3]
263/// 8 raw_len (u32) original payload length
264/// 12 stored_len(u32) bytes stored after this header
265/// ```
266pub(crate) const CONTAINER_MAGIC: [u8; 4] = *b"PMC1";
267pub(crate) const CONTAINER_LEN: usize = 16;
268pub(crate) const FLAG_COMPRESSED: u8 = 1 << 0;