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

psx_io/cd/
pause.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2//! Pausing the drive and knowing it has stopped: the silicon protocol, once.
3//!
4//! Pause is a two-response command. The first response (INT3) comes
5//! about 33,000 system clocks after the command and carries status `0x22`,
6//! "still reading". The second (INT2) says the drive has actually stopped, and on
7//! the project console it comes **a long time later**: out of a read, counted from
8//! the first response, 5.33 sector periods at the first sector, 6.17 after a far
9//! seek and 8.39 once the head has settled, i.e. 1.2 to 3.9 million system clocks
10//! (hardware-tests v2.7, run FB89, records 0x340 to 0x3B8). An emulator that
11//! completes a Pause in tens of thousands of clocks hides all of it, which is how
12//! three games shipped code that gave up after a few hundred thousand and read
13//! `0x22` as a failed stop (OoT froze in Link's House on the console, 2026-10-19).
14//!
15//! What else the console does, all measured:
16//!
17//! * A command sent between the two responses (GetStat, 4 of 4 trials) cancels the
18//!   second one for good. Proving the stop by asking for the status therefore
19//!   replaces waiting for INT2; it does not add to it.
20//! * A Pause sent while a read is still seeking is refused with INT5 (status
21//!   `0x03`, once `0x43`) and no INT3, six of six; the read carries on, so the
22//!   Pause has to be sent again once the seek is over. The status byte cannot
23//!   say when that is (it reads `0x03`, neither seeking nor reading, five times
24//!   of six), but the first data sector of the read can.
25//! * A GetStat at the first response reads `0x22` and one 230,000 clocks later
26//!   `0x02`, long before INT2. The reading bit is therefore not a stop signal
27//!   by itself, and [`pause_until_stopped`] uses it only after INT2 has failed
28//!   to come.
29//!
30//! [`pause_until_stopped`] is the whole protocol over the small [`PauseDrive`]
31//! trait, so the host tests can play the console's timings against it:
32//! send, wait for INT2 up to [`COMPLETE_SPINS`], fall back to polling the status
33//! when INT2 never shows, and on a refusal wait the seek out and send again.
34
35use psx_hw::cd::{STAT_PLAYING, STAT_READING, STAT_SEEKING};
36
37/// Spins of the status register to wait for the second response of a Pause.
38///
39/// A spin of the polled readers costs about 24 system clocks on the console, so
40/// this is about 24 million clocks (0.7 s): over six times the slowest completion
41/// measured (3.84 million out of a settled single-speed read), and still bounded so
42/// a dead drive cannot hang a loader. Even at an optimistic 5 clocks a spin it is
43/// 5 million. Reaching the bound is a failure path; the normal wait ends at INT2.
44pub const COMPLETE_SPINS: u32 = 1_000_000;
45
46/// Times the status is asked, one command each (about 20,000 clocks), when the
47/// second response did not come: about 20 million clocks (0.6 s).
48pub const STATUS_POLLS: u32 = 1_000;
49
50/// Spins to wait for the first data sector of a read whose Pause was refused,
51/// i.e. for its seek to end: the slowest seek measured is 310 ms, about 440,000
52/// spins at 24 clocks each.
53pub const SEEK_SPINS: u32 = 1_000_000;
54
55/// Pauses sent at most, counting the first. A refusal waits the seek out and
56/// retries; three is enough for a seek that began between two tries.
57pub const ATTEMPTS: u32 = 3;
58
59/// The first answer to a Pause.
60#[derive(Clone, Copy, Debug, PartialEq, Eq)]
61pub enum PauseAnswer {
62    /// INT3: the drive took the command; INT2 follows when it has stopped.
63    Acknowledged,
64    /// INT5: refused, the head is mid-seek. The read carries on.
65    Refused,
66    /// No answer within the command's own wait.
67    Silent,
68}
69
70/// The wait for the second answer.
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub enum Completion {
73    /// INT2: the drive has stopped.
74    Arrived,
75    /// INT5 instead of INT2.
76    Error,
77    /// Neither within the bound.
78    TimedOut,
79}
80
81/// Why a Pause could not be proven.
82#[derive(Clone, Copy, Debug, PartialEq, Eq)]
83pub enum PauseFailure {
84    /// The Pause was never acknowledged (no drive, tray open, dead controller).
85    NoAnswer,
86    /// Refused with INT5 on every try, or the second response was INT5.
87    Refused,
88    /// Acknowledged, but neither INT2 nor a status without an active bit came
89    /// within the bounds: the drive is still reading, seeking or playing.
90    NeverStopped,
91}
92
93impl PauseFailure {
94    /// A stable one-byte code for [`SectorReader::diagnostics`](super::reader::SectorReader::diagnostics)
95    /// and on-screen reports.
96    pub const fn code(self) -> u8 {
97        match self {
98            PauseFailure::NoAnswer => 1,
99            PauseFailure::Refused => 2,
100            PauseFailure::NeverStopped => 3,
101        }
102    }
103}
104
105/// What [`pause_until_stopped`] needs from the controller. Each method is one
106/// polled controller step; the implementor owns masking and acknowledging.
107pub trait PauseDrive {
108    /// Send Pause and wait for its first response.
109    fn send_pause(&mut self) -> PauseAnswer;
110    /// Wait up to `spins` for the second response. Data sectors still arriving
111    /// from the interrupted read are consumed and acknowledged meanwhile.
112    fn wait_completion(&mut self, spins: u32) -> Completion;
113    /// GetStat: the status byte, `None` when it did not answer. Cancels a
114    /// second response still pending.
115    fn status(&mut self) -> Option<u8>;
116    /// After a refusal: wait up to `spins` for the read to deliver its first
117    /// sector (consuming it), which ends the seek. `false` if none came.
118    fn wait_seek_end(&mut self, spins: u32) -> bool;
119}
120
121/// Pause the drive and return only when it has stopped.
122///
123/// `Ok` means the second response arrived, or the status reported no reading,
124/// seeking or playing bit. The drive is then idle and spun up.
125pub fn pause_until_stopped(drive: &mut impl PauseDrive) -> Result<(), PauseFailure> {
126    let mut refused = false;
127    for _ in 0..ATTEMPTS {
128        match drive.send_pause() {
129            PauseAnswer::Silent => return Err(PauseFailure::NoAnswer),
130            PauseAnswer::Refused => {
131                refused = true;
132                // The read carries on through the seek; send again once it is over.
133                drive.wait_seek_end(SEEK_SPINS);
134            }
135            PauseAnswer::Acknowledged => match drive.wait_completion(COMPLETE_SPINS) {
136                Completion::Arrived => return Ok(()),
137                Completion::Error => refused = true,
138                Completion::TimedOut => {
139                    // INT2 never came (lost, or later than any measured). Ask.
140                    return if wait_until_idle(drive) {
141                        Ok(())
142                    } else {
143                        Err(PauseFailure::NeverStopped)
144                    };
145                }
146            },
147        }
148    }
149    if refused {
150        Err(PauseFailure::Refused)
151    } else {
152        Err(PauseFailure::NeverStopped)
153    }
154}
155
156/// Status bits that mean the drive is doing something.
157const ACTIVE: u8 = STAT_PLAYING | STAT_SEEKING | STAT_READING;
158
159/// Ask for the status until no active bit is set. `false` when the polls run
160/// out or the drive stops answering.
161fn wait_until_idle(drive: &mut impl PauseDrive) -> bool {
162    for _ in 0..STATUS_POLLS {
163        match drive.status() {
164            Some(status) if status & ACTIVE == 0 => return true,
165            Some(_) => {}
166            None => return false,
167        }
168    }
169    false
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    /// The console's Pause, in spins (one status read, about 24 clocks, is one
177    /// spin; one GetStat is about 800 spins). The timeline starts at the
178    /// first `send_pause`.
179    struct Console {
180        /// Spins from the acknowledge to INT2, `None` when INT2 never comes.
181        completes_after: Option<u32>,
182        /// Spins from the acknowledge until the status stops saying reading.
183        status_clears_after: u32,
184        /// Spins of a seek that refuses a Pause, counted from the first send.
185        seeking_for: u32,
186        seek_waits: u32,
187        /// Spins since the first send.
188        now: u32,
189        /// Pause commands sent.
190        sends: u32,
191        statuses: u32,
192        /// Spin at which the accepted Pause was acknowledged.
193        acked_at: Option<u32>,
194        /// A GetStat has cancelled the second response.
195        cancelled: bool,
196        silent: bool,
197    }
198
199    /// One GetStat in spins: 19,500 clocks over 24 per spin.
200    const GETSTAT_SPINS: u32 = 800;
201
202    impl Console {
203        fn new(completes_after: Option<u32>) -> Self {
204            Console {
205                completes_after,
206                status_clears_after: completes_after.unwrap_or(0),
207                seeking_for: 0,
208                seek_waits: 0,
209                now: 0,
210                sends: 0,
211                statuses: 0,
212                acked_at: None,
213                cancelled: false,
214                silent: false,
215            }
216        }
217    }
218
219    impl PauseDrive for Console {
220        fn send_pause(&mut self) -> PauseAnswer {
221            self.sends += 1;
222            if self.silent {
223                return PauseAnswer::Silent;
224            }
225            if self.now < self.seeking_for {
226                self.now += 1_500; // the INT5 answer
227                return PauseAnswer::Refused;
228            }
229            self.now += 1_400; // the acknowledge, 33,000 clocks
230            self.acked_at = Some(self.now);
231            self.cancelled = false;
232            PauseAnswer::Acknowledged
233        }
234
235        fn wait_completion(&mut self, spins: u32) -> Completion {
236            let acked = self.acked_at.expect("a wait follows an acknowledge");
237            match self.completes_after {
238                Some(after) if !self.cancelled && after <= spins => {
239                    self.now = acked + after;
240                    Completion::Arrived
241                }
242                _ => {
243                    self.now += spins;
244                    Completion::TimedOut
245                }
246            }
247        }
248
249        fn status(&mut self) -> Option<u8> {
250            self.statuses += 1;
251            self.now += GETSTAT_SPINS;
252            // A command between the two responses cancels the second.
253            self.cancelled = true;
254            let reading = self
255                .acked_at
256                .is_none_or(|acked| self.now < acked + self.status_clears_after);
257            Some(if reading { STAT_READING | 0x02 } else { 0x02 })
258        }
259
260        fn wait_seek_end(&mut self, spins: u32) -> bool {
261            self.seek_waits += 1;
262            // The first sector arrives when the seek ends, if within `spins`.
263            let first_sector = self.seeking_for.saturating_add(4_700);
264            if first_sector <= self.now.saturating_add(spins) {
265                self.now = self.now.max(first_sector);
266                true
267            } else {
268                self.now += spins;
269                false
270            }
271        }
272    }
273
274    /// 3.84 million clocks (the slowest, single speed, settled head) in spins.
275    const SLOWEST: u32 = 3_840_000 / 24;
276
277    #[test]
278    fn the_bounds_cover_the_slowest_measured_completion_with_margin() {
279        // 24 clocks a spin on the console; even at a quarter of that it holds.
280        assert!(u64::from(COMPLETE_SPINS) * 24 > 6 * 3_840_000);
281        assert!(u64::from(COMPLETE_SPINS) * 5 >= 5_000_000);
282        // The wait the three games used (16,384 spins) was a tenth of the worst case.
283        const { assert!(16_384 < SLOWEST) };
284        // Longer than the slowest seek measured (310 ms = 10.5 million clocks).
285        assert!(u64::from(SEEK_SPINS) * 24 > 10_500_000);
286    }
287
288    #[test]
289    fn a_pause_that_completes_at_the_slowest_measured_time_is_waited_for() {
290        let mut console = Console::new(Some(SLOWEST));
291        assert_eq!(pause_until_stopped(&mut console), Ok(()));
292        assert_eq!(console.sends, 1);
293        assert_eq!(console.statuses, 0, "no GetStat: it would cancel INT2");
294    }
295
296    #[test]
297    fn the_old_sixteen_thousand_spin_wait_gives_up_on_every_measured_completion() {
298        // `SectorReader::stop` waits 16,384 spins for INT2 and goes on: every
299        // completion measured on the console is later than that, so a caller
300        // that needs the drive stopped cannot take that wait as the answer.
301        for clocks in [
302            1_220_000u32,
303            1_420_000,
304            1_690_000,
305            1_930_000,
306            2_420_000,
307            3_840_000,
308        ] {
309            let spins = clocks / 24;
310            assert!(spins > 16_384, "{clocks} clocks");
311            let mut console = Console::new(Some(spins));
312            assert_eq!(console.send_pause(), PauseAnswer::Acknowledged);
313            assert_eq!(console.wait_completion(16_384), Completion::TimedOut);
314        }
315    }
316
317    #[test]
318    fn an_idle_drive_stops_at_once() {
319        let mut console = Console::new(Some(340));
320        assert_eq!(pause_until_stopped(&mut console), Ok(()));
321    }
322
323    #[test]
324    fn a_lost_second_response_is_settled_by_the_status() {
325        let mut console = Console::new(None);
326        // Still reading when the wait for INT2 gives up, stopped a few asks later.
327        console.status_clears_after = COMPLETE_SPINS + 5 * GETSTAT_SPINS;
328        assert_eq!(pause_until_stopped(&mut console), Ok(()));
329        assert!(
330            console.statuses >= 5,
331            "it asked until the reading bit cleared"
332        );
333        assert_eq!(console.sends, 1, "the Pause is not sent again");
334    }
335
336    #[test]
337    fn a_drive_that_never_stops_is_reported_not_waited_for_forever() {
338        let mut console = Console::new(None);
339        console.status_clears_after = u32::MAX / 2;
340        assert_eq!(
341            pause_until_stopped(&mut console),
342            Err(PauseFailure::NeverStopped)
343        );
344        assert_eq!(console.statuses, STATUS_POLLS);
345    }
346
347    #[test]
348    fn a_pause_refused_during_the_seek_is_sent_again_after_it() {
349        let mut console = Console::new(Some(SLOWEST));
350        console.seeking_for = 10_500_000 / 24; // 310 ms, the slowest seek
351        assert_eq!(pause_until_stopped(&mut console), Ok(()));
352        assert_eq!(console.sends, 2, "refused once, then accepted");
353        assert_eq!(
354            console.seek_waits, 1,
355            "it waited for the first sector, not the status"
356        );
357        assert_eq!(console.statuses, 0);
358    }
359
360    #[test]
361    fn a_refusal_that_never_ends_stops_after_the_attempts() {
362        let mut console = Console::new(Some(SLOWEST));
363        console.seeking_for = u32::MAX / 2;
364        assert_eq!(
365            pause_until_stopped(&mut console),
366            Err(PauseFailure::Refused)
367        );
368        assert_eq!(console.sends, ATTEMPTS);
369    }
370
371    #[test]
372    fn a_drive_that_does_not_answer_is_not_retried() {
373        let mut console = Console::new(Some(1));
374        console.silent = true;
375        assert_eq!(
376            pause_until_stopped(&mut console),
377            Err(PauseFailure::NoAnswer)
378        );
379        assert_eq!(console.sends, 1);
380    }
381
382    #[test]
383    fn failure_codes_are_distinct_and_nonzero() {
384        let codes = [
385            PauseFailure::NoAnswer.code(),
386            PauseFailure::Refused.code(),
387            PauseFailure::NeverStopped.code(),
388        ];
389        assert!(codes.iter().all(|&c| c != 0));
390        assert_ne!(codes[0], codes[1]);
391        assert_ne!(codes[1], codes[2]);
392        assert_ne!(codes[0], codes[2]);
393    }
394}