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

psx_mc/
job.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2//! A card operation spread over game frames.
3//!
4//! [`Card::write`] on a [`HardwareCard`](crate::HardwareCard) holds the CPU
5//! for the whole operation: a directory read is a frame transaction of about
6//! 5 ms, a write is one plus the card's commit time, and a save is dozens of
7//! them. Called from a game loop that is a freeze of seconds.
8//!
9//! A [`CardJob`] runs the same filesystem code in three bounded phases and
10//! never does more than one card transaction per [`step`](CardJob::step):
11//!
12//! 1. **Probe**: the directory (frames `0..16`) is read into the job, one
13//!    frame per step.
14//! 2. **Plan**: the caller's closure runs the ordinary [`Card`] operations
15//!    (`format`, `write`, `delete`, ...) against a [`Staged`] card, which serves
16//!    reads from the cached directory and the writes already queued, and queues
17//!    every write instead of sending it. No card is touched and the cost is
18//!    CPU only, in one step.
19//! 3. **Write**: the queued frames are sent in the order the filesystem code
20//!    wrote them, one per step. After each, the card is left alone for
21//!    [`SETTLE_VBLANKS`] while it commits to flash; steps that land inside the
22//!    wait return [`Step::Waiting`] without touching the port.
23//!
24//! The queue keeps the filesystem's write order, so the guarantees of
25//! [`Card::write`] hold at every point: the old save stays whole until the new
26//! one is complete, and the new file appears with its first directory entry
27//! last. A card pulled between steps is in the same state it would be in if it
28//! had been pulled during the blocking call.
29//!
30//! The job does not own the port. Each [`step`](CardJob::step) is handed the
31//! device for that call alone, so a game keeps polling its pads between steps:
32//!
33//! ```text
34//! static mut JOB: CardJob<{ queue_frames(2048) }> = CardJob::new();
35//!
36//! job.begin();
37//! // every game frame:
38//! let mut card = HardwareCard::on_port(&mut port, Slot::One);
39//! match job.step(&mut card, vblank_count())? {
40//!     Step::NeedsPlan => job.plan(|c| c.write(NAME, TITLE, &save_bytes))?,
41//!     Step::Done => { /* saved */ }
42//!     _ => {}
43//! }
44//! ```
45
46use crate::fs::blocks_for;
47use crate::{Block, Card, Error, Result, CONTAINER_LEN, FRAME_COUNT, FRAME_SIZE};
48
49/// Directory frames a job reads before it plans: the `MC` header and the
50/// fifteen entries.
51pub const DIR_FRAMES: usize = 16;
52
53/// Frames a [`Card::format`] queues: the header, fifteen entries, the
54/// broken-sector list and the cleared tail of the directory block.
55pub const FORMAT_FRAMES: usize = 64;
56
57/// Video periods the card is left alone after each frame write, while it
58/// commits to flash. The blocking path (`HardwareCard::write_frame`) spins
59/// 400,000 status reads there, five to six video periods in the emulator and
60/// at least two by the reference drivers' rule; a job keeps the same wait,
61/// rounded up, by counting vblanks, so a game can spend it drawing instead.
62/// A job's wait can be changed with [`CardJob::with_settle_vblanks`].
63pub const SETTLE_VBLANKS: u32 = 8;
64
65/// Queue frames for one [`Card::write`] of a `payload_len`-byte save over an
66/// older copy of the same size: the title and icon frames, the data frames
67/// (container header included), one directory entry per block written, and
68/// one per block of the copy released afterwards. A format
69/// ([`FORMAT_FRAMES`]) or the deletion of another file is on top.
70pub const fn queue_frames(payload_len: usize) -> usize {
71    let total = CONTAINER_LEN + payload_len;
72    let blocks = blocks_for(total);
73    2 + total.div_ceil(FRAME_SIZE) + 2 * blocks
74}
75
76/// What one [`CardJob::step`] did.
77#[derive(Copy, Clone, Debug, PartialEq, Eq)]
78pub enum Step {
79    /// No operation is in progress ([`CardJob::begin`] starts one).
80    Idle,
81    /// The card is committing its last write; the port was not touched.
82    Waiting,
83    /// One directory frame was read.
84    Probing,
85    /// The directory is cached. Call [`CardJob::plan`]; nothing else moves
86    /// until it has been.
87    NeedsPlan,
88    /// One queued frame was written.
89    Writing,
90    /// Every frame is written and the card has finished committing the last.
91    Done,
92}
93
94/// The card as the planning closure sees it. Reads come from the writes
95/// queued so far, then from the cached directory; writes are queued, not
96/// sent. It is the [`Block`] under the `Card` that [`CardJob::plan`] passes.
97///
98/// It holds the directory only: a read of any other frame that no queued
99/// write covers fails with [`Error::OutOfRange`]. `format`, `write`, `delete`,
100/// `list`, `free_blocks` and `is_formatted` read nothing else. A write past
101/// the queue's capacity fails with [`Error::NoSpace`].
102pub struct Staged<'a, const N: usize>(&'a mut Stage<N>);
103
104// Every field is a whole number of words, so the all-zero job has no padding
105// bytes and the linker keeps a `static` one in `.bss`, not in the executable.
106#[repr(C)]
107struct Stage<const N: usize> {
108    len: u32,
109    frame: [u32; N],
110    dir: [[u8; FRAME_SIZE]; DIR_FRAMES],
111    data: [[u8; FRAME_SIZE]; N],
112}
113
114impl<const N: usize> Block for Staged<'_, N> {
115    fn read_frame(&mut self, frame: u16, out: &mut [u8; FRAME_SIZE]) -> Result<()> {
116        let stage = &*self.0;
117        for i in (0..stage.len as usize).rev() {
118            if stage.frame[i] == frame as u32 {
119                *out = stage.data[i];
120                return Ok(());
121            }
122        }
123        match stage.dir.get(frame as usize) {
124            Some(cached) => {
125                *out = *cached;
126                Ok(())
127            }
128            None => Err(Error::OutOfRange),
129        }
130    }
131
132    fn write_frame(&mut self, frame: u16, data: &[u8; FRAME_SIZE]) -> Result<()> {
133        if frame as usize >= FRAME_COUNT {
134            return Err(Error::OutOfRange);
135        }
136        let stage = &mut *self.0;
137        let at = stage.len as usize;
138        if at == N {
139            return Err(Error::NoSpace);
140        }
141        stage.frame[at] = frame as u32;
142        stage.data[at] = *data;
143        stage.len += 1;
144        Ok(())
145    }
146}
147
148#[derive(Copy, Clone, PartialEq, Eq)]
149#[repr(u32)]
150enum Phase {
151    Idle = 0,
152    /// Reading the directory frame at `cursor`.
153    Probe,
154    NeedsPlan,
155    /// Sending the queued frame at `cursor`.
156    Write,
157    /// Everything sent; waiting out the last commit.
158    Drain,
159}
160
161/// A save, format or delete run a little at a time. `N` is the number of
162/// frame writes it can queue (see [`queue_frames`] and [`FORMAT_FRAMES`]); the
163/// job holds `N` frames of 128 bytes plus the 2 KiB directory, so keep it in a
164/// `static`. The idle job is all zero bytes, so a `static` one costs no space
165/// in the executable.
166#[repr(C)]
167pub struct CardJob<const N: usize> {
168    phase: Phase,
169    cursor: u32,
170    /// The vblank count at which the card may be touched again.
171    ready_at: u32,
172    /// Commit wait in vblanks; 0 is [`SETTLE_VBLANKS`].
173    settle: u32,
174    stage: Stage<N>,
175}
176
177impl<const N: usize> CardJob<N> {
178    /// An idle job with the default [`SETTLE_VBLANKS`] commit wait.
179    pub const fn new() -> Self {
180        CardJob {
181            phase: Phase::Idle,
182            cursor: 0,
183            ready_at: 0,
184            settle: 0,
185            stage: Stage {
186                len: 0,
187                frame: [0; N],
188                dir: [[0; FRAME_SIZE]; DIR_FRAMES],
189                data: [[0; FRAME_SIZE]; N],
190            },
191        }
192    }
193
194    /// The same job with `vblanks` as the commit wait after each frame write,
195    /// for a card slower than the default allows for. 0 is the default.
196    pub const fn with_settle_vblanks(mut self, vblanks: u32) -> Self {
197        self.settle = vblanks;
198        self
199    }
200
201    fn settle_vblanks(&self) -> u32 {
202        if self.settle == 0 {
203            SETTLE_VBLANKS
204        } else {
205            self.settle
206        }
207    }
208
209    /// Start an operation: the next steps read the directory. Anything in
210    /// progress is dropped (what it had already written stays written).
211    pub fn begin(&mut self) {
212        self.stage.len = 0;
213        self.cursor = 0;
214        self.phase = Phase::Probe;
215    }
216
217    /// Drop the operation in progress. Frames already sent stay on the card.
218    pub fn abort(&mut self) {
219        self.stage.len = 0;
220        self.phase = Phase::Idle;
221    }
222
223    /// Whether an operation is in progress.
224    pub fn is_busy(&self) -> bool {
225        self.phase != Phase::Idle
226    }
227
228    /// How far along the operation is, 0 to 256: the directory read is the
229    /// first sixteenth and the frame writes the rest.
230    pub fn progress_q8(&self) -> u32 {
231        match self.phase {
232            Phase::Idle => 0,
233            Phase::Probe => self.cursor * 16 / DIR_FRAMES as u32,
234            Phase::NeedsPlan => 16,
235            Phase::Write => 16 + self.cursor * 240 / self.stage.len.max(1),
236            Phase::Drain => 256,
237        }
238    }
239
240    fn card_ready(&self, now: u32) -> bool {
241        now.wrapping_sub(self.ready_at) < 0x8000_0000
242    }
243
244    /// Advance by at most one card transaction. `now` is the vblank count
245    /// (`psx_rt::interrupts::vblank_count()`), which times the commit wait;
246    /// `dev` is the card for this call only.
247    ///
248    /// A card error ends the operation (the job is idle again) and is
249    /// returned.
250    pub fn step<B: Block>(&mut self, dev: &mut B, now: u32) -> Result<Step> {
251        match self.phase {
252            Phase::Idle => return Ok(Step::Idle),
253            Phase::NeedsPlan => return Ok(Step::NeedsPlan),
254            _ if !self.card_ready(now) => return Ok(Step::Waiting),
255            _ => {}
256        }
257        match self.phase {
258            Phase::Probe => {
259                let n = self.cursor as usize;
260                if let Err(e) = dev.read_frame(n as u16, &mut self.stage.dir[n]) {
261                    self.abort();
262                    return Err(e);
263                }
264                if n + 1 < DIR_FRAMES {
265                    self.cursor += 1;
266                } else {
267                    self.phase = Phase::NeedsPlan;
268                }
269                Ok(Step::Probing)
270            }
271            Phase::Write => {
272                let i = self.cursor as usize;
273                let sent =
274                    dev.write_frame_unsettled(self.stage.frame[i] as u16, &self.stage.data[i]);
275                if let Err(e) = sent {
276                    self.abort();
277                    return Err(e);
278                }
279                self.ready_at = now.wrapping_add(self.settle_vblanks());
280                if i + 1 < self.stage.len as usize {
281                    self.cursor += 1;
282                } else {
283                    self.phase = Phase::Drain;
284                }
285                Ok(Step::Writing)
286            }
287            // `Idle` and `NeedsPlan` returned above, and `Drain` is the only
288            // phase left once the card is ready.
289            _ => {
290                self.stage.len = 0;
291                self.phase = Phase::Idle;
292                Ok(Step::Done)
293            }
294        }
295    }
296
297    /// Run the filesystem operations for this job on a [`Staged`] card, after
298    /// [`step`](Self::step) has returned [`Step::NeedsPlan`]. The closure sees
299    /// the card as it was probed and may read what it has written; its result
300    /// is passed through.
301    ///
302    /// On `Ok` the queued writes are sent by the following steps. On `Err` the
303    /// job is idle again and nothing was written, so a caller that wants to
304    /// act on the error (ask before formatting a blank card, say) starts a new
305    /// operation with [`begin`](Self::begin).
306    ///
307    /// Out of order, this returns [`Error::Protocol`] and changes nothing.
308    pub fn plan<R>(
309        &mut self,
310        build: impl FnOnce(&mut Card<Staged<'_, N>>) -> Result<R>,
311    ) -> Result<R> {
312        if self.phase != Phase::NeedsPlan {
313            return Err(Error::Protocol);
314        }
315        self.stage.len = 0;
316        let mut card = Card::new(Staged(&mut self.stage));
317        match build(&mut card) {
318            Ok(value) => {
319                self.cursor = 0;
320                self.phase = if self.stage.len == 0 {
321                    Phase::Drain
322                } else {
323                    Phase::Write
324                };
325                Ok(value)
326            }
327            Err(e) => {
328                self.abort();
329                Err(e)
330            }
331        }
332    }
333}
334
335impl<const N: usize> Default for CardJob<N> {
336    fn default() -> Self {
337        Self::new()
338    }
339}
340
341#[cfg(test)]
342mod tests;