psx_io/cd/reader.rs
1// SPDX-License-Identifier: GPL-2.0-or-later
2//! Polled CD-ROM data-sector reads: seek, stream and pop 2048-byte sectors.
3//!
4//! [`SectorReader`] holds the [`Cd`] token and drives the controller through
5//! its register steps, so the register map, the IRQ acknowledge order and the
6//! BCD arithmetic exist once, in [`super`]. What it adds is the command
7//! sequence the pack loader and the FMV streamer have run on silicon: a
8//! SetMode-then-Setloc-then-ReadN start with every IRQ masked and every FIFO
9//! in a known state, a wait loop that drains stale responses (and a stale
10//! data sector into a bounce buffer) before it acknowledges them, and a Pause
11//! that leaves the drive spun up. The comments that record silicon findings
12//! travel with the code.
13//!
14//! Sectors come out of the data FIFO by CPU reads (PIO), not DMA channel 3.
15//! The CL1/CL2 silicon probes convicted the chopping-burst DMA path on real
16//! hardware: the transfer is a state-dependent lottery, and the channel can
17//! latch its start bit and stay busy forever while moving nothing, which read
18//! as all-zero sectors. PIO is the recipe the same probes proved byte-perfect:
19//! arm the data request, wait until the FIFO reports data, pop all 2048 bytes.
20//! It costs about 1.3 ms more per sector than a working DMA, and it cannot
21//! wedge the DMA controller.
22//!
23//! # What `prepare` does to the machine
24//!
25//! [`SectorReader::prepare`] polls the controller's own IRQ flags, so it
26//! keeps CD-ROM interrupts away from the CPU for the length of a stream:
27//!
28//! * `I_MASK` is set to VBlank-only (by `prepare`, and again by each
29//! `start_read`) until [`SectorReader::stop`] puts the previous value back,
30//! plus whatever [`irq::keep_enabled_while_polling`] holds. Every other
31//! source stops reaching the CPU in between: a CD-ROM IRQ with no handler would otherwise be an unhandled-IRQ
32//! storm.
33//! * The latched CD-ROM `I_STAT` bit is acked and the controller's five IRQ
34//! enables are switched on, then every pending controller IRQ is acked.
35//! * On the first `prepare` of a reader, IRQs latched by earlier activity (the
36//! BIOS disc boot's file load) are drained. Pausing instead would hang on
37//! an emulator that has no active read to pause.
38//! * `SetMode` is sent: double speed and 2048-byte user data by default.
39//!
40//! No DMA channel is enabled: nothing here uses one.
41
42use super::lba_to_bcd_msf;
43use super::pause::{self, Completion, PauseAnswer, PauseDrive, PauseFailure};
44use crate::irq;
45use crate::periph::Cd;
46use psx_hw::cd::irq::{
47 ACKNOWLEDGE as IRQ_ACK, COMPLETE as IRQ_COMPLETE, DATA_END as IRQ_DATA_END,
48 DATA_READY as IRQ_DATA_READY, ERROR as IRQ_ERROR,
49};
50use psx_hw::cd::{
51 CMD_DEMUTE, CMD_PAUSE, CMD_READN, CMD_SEEKL, CMD_SETFILTER, CMD_SETLOC, CMD_SETMODE,
52 MODE_DOUBLE_SPEED,
53};
54
55/// One CD sector's user data in 32-bit words.
56pub const SECTOR_WORDS: usize = 2048 / 4;
57
58/// `SetMode` byte for double-speed 2048-byte sectors.
59const MODE_DATA_DOUBLE_SPEED: u8 = MODE_DOUBLE_SPEED;
60
61// Poll limits, tuned on silicon. `DATA_POLL` covers a worst-case seek at
62// double speed.
63const ACK_POLL: u32 = 16_384;
64const PARAM_POLL: u32 = 16_384;
65const DATA_POLL: u32 = 4_000_000;
66const CLEANUP_POLL: u32 = 16_384;
67/// Response bytes drained at most. The FIFO holds 16, but on heavy streaming
68/// the controller (or an emulator) can wedge it "not empty", and an unbounded
69/// drain would hang the loader.
70const DRAIN_LIMIT: u32 = 256;
71
72/// Every controller IRQ enable, which `prepare` and a started read switch on.
73const ALL_IRQS_ENABLED: u8 = psx_hw::cd::irq::ALL;
74
75/// [`SectorReader::diagnostics`] cause byte: the drive raised INT5; the
76/// snapshot carries the error response's status and error-code bytes.
77pub const DIAG_CD_ERROR: u8 = 0x05;
78/// [`SectorReader::diagnostics`] cause byte: the wait spun out; the snapshot
79/// carries the raw status register and the last IRQ flag seen.
80pub const DIAG_TIMEOUT: u8 = 0xff;
81/// [`SectorReader::diagnostics`] cause byte: the parameter FIFO never freed up.
82pub const DIAG_PARAM_STUCK: u8 = 0xfe;
83/// [`SectorReader::diagnostics`] cause byte: [`SectorReader::stop_proved`] could
84/// not prove the drive stopped; the snapshot's status byte is
85/// [`PauseFailure::code`] and the command byte is `CMD_PAUSE`.
86pub const DIAG_PAUSE: u8 = 0xfd;
87/// [`SectorReader::diagnostics`] command byte standing in for a `read_sector`
88/// wait (ReadN is streaming; no command byte is in flight).
89pub const DIAG_SITE_READ: u8 = 0xd0;
90
91/// Called from every spin of every polled wait in this module, see [`set_idle_hook`].
92///
93/// In `.data`, not `.bss`: a chain-loader image has no `.bss` zeroed for it.
94#[cfg_attr(target_arch = "mips", link_section = ".data")]
95static mut IDLE_HOOK: Option<fn()> = None;
96
97/// Install (or with `None` remove) a function the polled reader calls from every
98/// spin of every wait it makes (a seek, the next sector of a read, a command's
99/// acknowledge) and so between the sectors of any load built on it.
100///
101/// It is how a program keeps something moving while it blocks on the disc: the
102/// `psx-loading` widget polls from here, so one hook animates every polled load
103/// the program does, whichever crate issues it (pack table scans and chunk reads
104/// included). The hook runs with the drive owned by the reader: it must not
105/// touch the CD controller, and it must return at once when there is nothing to
106/// do, because it runs thousands of times a second. It is global, one at a time.
107pub fn set_idle_hook(hook: Option<fn()>) {
108 // SAFETY: a plain store to a private static; the guest is single threaded and
109 // no interrupt handler reads it.
110 unsafe { IDLE_HOOK = hook };
111}
112
113#[inline]
114fn run_idle_hook() {
115 // SAFETY: as `set_idle_hook`.
116 if let Some(hook) = unsafe { IDLE_HOOK } {
117 hook();
118 }
119}
120
121enum Wait {
122 Matched,
123 CdError,
124 Timeout,
125}
126
127/// The interrupt mask a stream replaced, kept until it ends.
128#[derive(Debug, Default)]
129struct SavedMask(Option<u32>);
130
131impl SavedMask {
132 /// Remember `current`, unless a mask is already kept: a second `prepare`
133 /// before `stop` sees the stream's own VBlank-only mask, which is not the
134 /// caller's.
135 fn keep(&mut self, current: u32) {
136 if self.0.is_none() {
137 self.0 = Some(current);
138 }
139 }
140
141 fn take(&mut self) -> Option<u32> {
142 self.0.take()
143 }
144}
145
146/// Blocking, polled CD-ROM sector reader.
147///
148/// Owns the CD token, plus the state a polled stream needs: whether the
149/// first `prepare` has drained boot-time IRQs, the interrupt mask to put back
150/// at `stop`, and a one-sector bounce buffer that an unexpected data-ready IRQ
151/// is drained into (the data FIFO must be emptied before the ack or the
152/// controller wedges). Create one reader and reuse it for the program's
153/// lifetime; a fresh reader merely repeats the harmless first-time drain.
154///
155/// Typical use is not these raw methods but `psx_pack::cd::load_chunk` on top.
156/// The raw sequence is: `prepare()`, `start_read(lba)`, N times
157/// `read_sector(&mut buf)`, `stop()`.
158///
159/// The reader owns the drive, so nothing else can command it meanwhile:
160///
161/// ```compile_fail,E0382
162/// use psx_io::cd::reader::SectorReader;
163/// use psx_io::periph::Cd;
164///
165/// // SAFETY: the doctest never runs a command; it only has to compile.
166/// let mut cd = unsafe { Cd::steal() };
167/// let mut reader = SectorReader::with_cd(cd);
168/// // The token moved into the reader, so this is a use after move.
169/// let _ = cd.play_track(2);
170/// reader.stop();
171/// ```
172pub struct SectorReader {
173 cd: Cd,
174 prepared: bool,
175 /// Mode byte the last prepare() set; re-sent inside every BIOS-bracket
176 /// read start, because that is what the BIOS does.
177 mode: u8,
178 saved_mask: SavedMask,
179 discard: [u32; SECTOR_WORDS],
180 /// Last failure snapshot: `[cause, status, command, flag-or-error]`.
181 /// Written on every failure path so a caller with only a screen to
182 /// print on (the demo-disc loader) can say what the drive did.
183 diag: [u8; 4],
184}
185
186impl SectorReader {
187 /// A reader that has not yet drained boot-time IRQs. `const` so it can
188 /// sit in a `static`.
189 pub const fn with_cd(cd: Cd) -> Self {
190 SectorReader {
191 cd,
192 prepared: false,
193 mode: MODE_DATA_DOUBLE_SPEED,
194 saved_mask: SavedMask(None),
195 discard: [0; SECTOR_WORDS],
196 diag: [0; 4],
197 }
198 }
199
200 /// [`with_cd`](Self::with_cd) on a token the caller does not hold.
201 #[deprecated(note = "use `SectorReader::with_cd` with the `Cd` token")]
202 pub const fn new() -> Self {
203 // SAFETY: a token is a logic guard, not a memory-safety one (see
204 // `crate::periph`), and the old constructor never took one.
205 Self::with_cd(unsafe { Cd::steal() })
206 }
207
208 /// Give the token back, restoring the interrupt mask first if a stream
209 /// is still open. Call [`stop`](Self::stop) first to also pause the drive.
210 pub fn release(mut self) -> Cd {
211 self.restore_irq_mask();
212 self.cd
213 }
214
215 /// The token, lent for commands outside the reader's own sequences (the
216 /// drive's audio mixer, a status poll). The reader stays borrowed meanwhile.
217 pub fn cd_mut(&mut self) -> &mut Cd {
218 &mut self.cd
219 }
220
221 /// The last failure snapshot packed big-endian:
222 /// `cause<<24 | status<<16 | command<<8 | flag_or_error`. Zero when
223 /// nothing has failed yet. Causes are the `DIAG_*` constants; for
224 /// [`DIAG_CD_ERROR`] the status/flag bytes are the INT5 response pair,
225 /// otherwise status is the raw status register at failure and the low
226 /// byte is the last IRQ flag seen.
227 pub fn diagnostics(&self) -> u32 {
228 u32::from_be_bytes(self.diag)
229 }
230
231 /// Pop one sector's 2048 bytes from the data FIFO into `buffer`.
232 ///
233 /// Arms the data request, waits (bounded) until the FIFO reports data,
234 /// then pops byte by byte. The words are written with volatile stores, in
235 /// order, so the pops and the stores interleave as on silicon.
236 fn pop_sector(cd: &mut Cd, buffer: &mut [u32; SECTOR_WORDS]) {
237 cd.request_data();
238 // The FIFO fills shortly after the request; the bound covers a slow
239 // drive without letting a dead one hang the caller.
240 let mut spins = 0;
241 crate::diag::wait_begin(crate::diag::site::CD_FIFO, 0);
242 while !cd.is_data_fifo_ready() && spins < DATA_POLL {
243 spins += 1;
244 }
245 if spins >= DATA_POLL {
246 crate::diag::wait_timeout(crate::diag::site::CD_FIFO, 0, DATA_POLL);
247 } else {
248 crate::diag::wait_end();
249 }
250 crate::diag::cd_sector();
251 for word in buffer.iter_mut() {
252 let b0 = cd.read_data_byte() as u32;
253 let b1 = cd.read_data_byte() as u32;
254 let b2 = cd.read_data_byte() as u32;
255 let b3 = cd.read_data_byte() as u32;
256 // SAFETY: `word` is a live, aligned `&mut u32` into `buffer`.
257 unsafe { core::ptr::write_volatile(word, (b3 << 24) | (b2 << 16) | (b1 << 8) | b0) };
258 }
259 }
260
261 /// Clear an IRQ we were not waiting for. A stale `DataReady` must have its
262 /// sector popped (into the reader's bounce buffer) before the ack, or the
263 /// data FIFO stays occupied and later reads misalign.
264 fn ack_unexpected(&mut self, flag: u8) {
265 match flag {
266 IRQ_DATA_READY => {
267 Self::pop_sector(&mut self.cd, &mut self.discard);
268 self.cd.drain_response_limited(DRAIN_LIMIT);
269 self.cd.acknowledge_irq(IRQ_DATA_READY);
270 }
271 IRQ_COMPLETE | IRQ_ACK | IRQ_DATA_END => {
272 self.cd.drain_response_limited(DRAIN_LIMIT);
273 self.cd.acknowledge_irq(flag);
274 }
275 _ => {
276 self.cd.drain_response_limited(DRAIN_LIMIT);
277 self.cd.acknowledge_all_and_reset_parameters();
278 }
279 }
280 }
281
282 fn wait_irq(&mut self, expected: u8, limit: u32) -> Wait {
283 self.wait_irq_with(expected, limit, &mut || {})
284 }
285
286 /// [`wait_irq`](Self::wait_irq) calling `idle` once per spin, before the
287 /// controller is looked at again, so a caller can keep servicing something
288 /// else (the pad) through a wait that runs longer than a frame.
289 fn wait_irq_with(&mut self, expected: u8, limit: u32, idle: &mut dyn FnMut()) -> Wait {
290 let site = if expected == IRQ_DATA_READY {
291 crate::diag::site::CD_SECTOR
292 } else {
293 crate::diag::site::CD_RESPONSE
294 };
295 crate::diag::wait_begin(site, expected as u32);
296 let mut spins = 0;
297 while spins < limit {
298 idle();
299 run_idle_hook();
300 let flag = self.cd.irq_flag_value();
301 if flag == expected {
302 crate::diag::wait_end();
303 return Wait::Matched;
304 }
305 // Some drives raise the data FIFO before (or without) latching the
306 // DataReady flag; treat visible data as a match.
307 if expected == IRQ_DATA_READY && self.cd.is_data_fifo_ready() {
308 crate::diag::wait_end();
309 return Wait::Matched;
310 }
311 if flag == IRQ_ERROR {
312 crate::diag::wait_end();
313 return Wait::CdError;
314 }
315 if flag != 0 {
316 self.ack_unexpected(flag);
317 }
318 spins += 1;
319 }
320 crate::diag::wait_timeout(site, expected as u32, limit);
321 Wait::Timeout
322 }
323
324 /// Record an INT5: its response pair (status, error code) is read before
325 /// the drain throws it away.
326 fn note_drive_error(&mut self, command: u8) {
327 let status = self.cd.read_response_byte();
328 let code = self.cd.read_response_byte();
329 self.diag = [DIAG_CD_ERROR, status, command, code];
330 crate::diag::cd_error(status, code);
331 }
332
333 /// Record a wait that spun out.
334 fn note_timeout(&mut self, command: u8) {
335 let status = self.cd.status_register();
336 let flag = self.cd.irq_flag_value();
337 self.diag = [DIAG_TIMEOUT, status, command, flag];
338 crate::diag::cd_timeout(u32::from_be_bytes(self.diag));
339 }
340
341 /// Dispatch one command with controller IRQs masked and every FIFO in a
342 /// known state, then wait for `expected` and ack it. The mask/ack ordering
343 /// is load-bearing on silicon; do not reorder.
344 fn send_command(&mut self, command: u8, params: &[u8], expected: u8, limit: u32) -> bool {
345 matches!(
346 self.send_command_waiting(command, params, expected, limit),
347 Some(Wait::Matched)
348 )
349 }
350
351 /// [`send_command`](Self::send_command) saying how the wait ended; `None`
352 /// when the command never went out (the parameter FIFO stayed full).
353 fn send_command_waiting(
354 &mut self,
355 command: u8,
356 params: &[u8],
357 expected: u8,
358 limit: u32,
359 ) -> Option<Wait> {
360 let saved = self.cd.irq_enable_mask();
361 self.cd.set_irq_enable_mask(0);
362 self.cd.acknowledge_all_and_reset_parameters();
363 self.cd.drain_response_limited(DRAIN_LIMIT);
364 // Reset the parameter FIFO before queueing parameters.
365 self.cd.reset_parameter_fifo();
366 for ¶m in params {
367 if !self.cd.wait_parameter_room(PARAM_POLL) {
368 self.diag = [DIAG_PARAM_STUCK, self.cd.status_register(), command, 0];
369 self.cd.set_irq_enable_mask(saved);
370 return None;
371 }
372 self.cd.send_parameter_byte(param);
373 }
374 self.cd.send_command_byte(command);
375 let outcome = self.wait_irq(expected, limit);
376 match outcome {
377 Wait::Matched => {
378 self.cd.drain_response_limited(DRAIN_LIMIT);
379 self.cd.acknowledge_irq(expected);
380 }
381 Wait::CdError => {
382 self.note_drive_error(command);
383 self.cd.drain_response_limited(DRAIN_LIMIT);
384 self.cd.acknowledge_all_and_reset_parameters();
385 }
386 Wait::Timeout => self.note_timeout(command),
387 }
388 self.cd.set_irq_enable_mask(saved);
389 Some(outcome)
390 }
391
392 /// Set `I_MASK` to VBlank-only, keeping the caller's mask for
393 /// [`stop`](Self::stop), plus the sources [`irq::keep_enabled_while_polling`]
394 /// holds (the pad engine's). Idempotent within a stream.
395 fn enter_polling_mask(&mut self) {
396 self.saved_mask.keep(irq::mask());
397 irq::set_mask((1 << psx_hw::irq::source::VBLANK) | irq::polling_keep());
398 }
399
400 fn restore_irq_mask(&mut self) {
401 if let Some(mask) = self.saved_mask.take() {
402 irq::set_mask(mask_after_stream(mask, irq::polling_keep()));
403 }
404 }
405
406 /// Take over the controller for polled data reads and set
407 /// double-speed / 2048-byte-sector mode.
408 ///
409 /// Sets `I_MASK` to VBlank-only until [`stop`](Self::stop) puts the
410 /// previous mask back; see the module docs for the full list of side
411 /// effects. Call it only from code that owns interrupt policy, a polling
412 /// main loop, and not from an IRQ handler. No CD-ROM IRQ handler may be
413 /// installed while a stream runs.
414 ///
415 /// Returns `false` when the Setmode handshake times out (no drive, tray
416 /// open, dead controller); the reader is safe to retry.
417 pub fn prepare(&mut self) -> bool {
418 self.prepare_with_mode(MODE_DATA_DOUBLE_SPEED)
419 }
420
421 /// [`prepare`](Self::prepare) at single speed: half the throughput,
422 /// twice the per-sector margin. The demo-disc chain loader measured
423 /// silent payload corruption over hundreds of back-to-back
424 /// double-speed sectors on the project console (2026-08-01, the
425 /// loader's RAM checksum against the disc build); the header sector
426 /// alone always read clean, so the failure scales with sustained
427 /// rate, and a loader that takes three extra seconds beats one that
428 /// jumps into a corrupt payload.
429 pub fn prepare_single_speed(&mut self) -> bool {
430 self.prepare_with_mode(0x00)
431 }
432
433 /// [`prepare`](Self::prepare) with an explicit Setmode byte, for
434 /// streams that need more than plain data: e.g. `0x80 | 0x40 | 0x08`
435 /// (double speed, XA-ADPCM on, file/channel filter) plays interleaved
436 /// XA audio through the SPU while video sectors still arrive as data.
437 pub fn prepare_mode(&mut self, mode: u8) -> bool {
438 self.prepare_with_mode(mode)
439 }
440
441 /// Setfilter: the XA file and channel whose audio sectors the drive
442 /// plays when the mode has the filter bit set.
443 pub fn set_filter(&mut self, file: u8, channel: u8) -> bool {
444 self.send_command(CMD_SETFILTER, &[file, channel], IRQ_ACK, ACK_POLL)
445 }
446
447 /// Unmute the drive: let CD-DA and XA-ADPCM reach the SPU. The drive
448 /// stays muted across programs, so a stream that plays XA audio must not
449 /// assume the last tenant left it unmuted.
450 #[doc(alias = "Demute")]
451 pub fn unmute(&mut self) -> bool {
452 self.send_command(CMD_DEMUTE, &[], IRQ_ACK, ACK_POLL)
453 }
454
455 fn prepare_with_mode(&mut self, mode: u8) -> bool {
456 self.mode = mode;
457 // Keep CD-ROM at the controller level and poll its IRQ flags
458 // manually, so DataReady cannot enter an unhandled CPU IRQ storm.
459 self.enter_polling_mask();
460 irq::acknowledge(1 << psx_hw::irq::source::CDROM);
461 self.cd.set_irq_enable_mask(ALL_IRQS_ENABLED);
462 self.cd.acknowledge_all_and_reset_parameters();
463 if !self.prepared {
464 // A BIOS disc boot has already finished its file load. Do not
465 // send Pause before our first stream; on real BIOS boot paths
466 // some emulators have no active read command to pause and
467 // never acknowledge it. Drain any already-latched data/ack
468 // instead.
469 let mut drained = 0;
470 while drained < 16 {
471 let flag = self.cd.irq_flag_value();
472 if flag == 0 {
473 break;
474 }
475 self.ack_unexpected(flag);
476 drained += 1;
477 }
478 self.cd.acknowledge_all_and_reset_parameters();
479 self.prepared = true;
480 }
481 // Purge whatever the previous tenant left in the data FIFO by
482 // dropping the data request (writing 0 resets the data FIFO). The
483 // demo-disc chain loader's header read came back with shifted bytes
484 // on silicon (magic mismatch, identical every attempt) after the
485 // menu's earlier disc reads; leftover FIFO bytes are the only state
486 // that survives the IRQ drain above, and an emulator FIFO never holds
487 // any, which is why this cannot reproduce headless.
488 self.cd.clear_data_request();
489 self.send_command(CMD_SETMODE, &[mode], IRQ_ACK, ACK_POLL)
490 }
491
492 /// Setloc to a program-relative `lba`, shifted by [`crate::disc_base`]
493 /// to where this program's image actually landed on a multi-program disc.
494 fn set_location(&mut self, lba: u32) -> bool {
495 crate::diag::cd_start(crate::disc_base::shift_lba(lba));
496 let [minute, second, frame] = lba_to_bcd_msf(crate::disc_base::shift_lba(lba));
497 self.send_command(CMD_SETLOC, &[minute, second, frame], IRQ_ACK, ACK_POLL)
498 }
499
500 /// Seek to `lba` (Setloc with BCD MSF) and start a ReadN stream.
501 /// [`prepare`](Self::prepare) must have succeeded first.
502 ///
503 /// `lba` is relative to the start of this program's own disc image; on a
504 /// multi-program disc [`crate::disc_base`] shifts it to where that image
505 /// actually landed.
506 pub fn start_read(&mut self, lba: u32) -> bool {
507 // A caller that prepared once and starts several streams still gets
508 // the polling mask for each, and `stop` still puts its own back.
509 self.enter_polling_mask();
510 if !self.set_location(lba) {
511 return false;
512 }
513 if !self.send_command(CMD_READN, &[], IRQ_ACK, ACK_POLL) {
514 return false;
515 }
516 self.cd.set_irq_enable_mask(ALL_IRQS_ENABLED);
517 true
518 }
519
520 /// [`start_read`](Self::start_read) the way the real BIOS starts one:
521 /// SetLoc, then an EXPLICIT SeekL waited to completion, then ReadN.
522 ///
523 /// Traced from a real SCPH-1001 boot (2026-08-01, emulator CD command
524 /// log): the BIOS brackets every read -- even a single sector -- as
525 /// SetLoc/SeekL/SetMode/ReadN/Pause. The implicit seek a bare
526 /// SetLoc+ReadN performs starts data flowing while the mech is still
527 /// settling; the same console that corrupts our sustained implicit-seek
528 /// streams loads 1.4 MB EXEs through the BIOS bracket without fault.
529 pub fn start_read_seek_first(&mut self, lba: u32, seek_poll: u32) -> bool {
530 self.start_read_seek_first_with(lba, seek_poll, &mut || {})
531 }
532
533 /// [`start_read_seek_first`](Self::start_read_seek_first) calling `idle`
534 /// while it waits for the seek to complete. A long seek (the head crossing
535 /// the disc) takes several frames, and the command sequence is otherwise
536 /// the same, in the same order; `idle` must not touch the CD controller.
537 pub fn start_read_seek_first_with(
538 &mut self,
539 lba: u32,
540 seek_poll: u32,
541 idle: &mut dyn FnMut(),
542 ) -> bool {
543 self.enter_polling_mask();
544 if !self.set_location(lba) {
545 return false;
546 }
547 // SeekL acks (INT3) then completes (INT2) once the head has
548 // settled on the target; only then is ReadN issued, so the
549 // drive never streams during mech settle.
550 if !self.send_command(CMD_SEEKL, &[], IRQ_ACK, ACK_POLL) {
551 return false;
552 }
553 match self.wait_irq_with(IRQ_COMPLETE, seek_poll, idle) {
554 Wait::Matched => {}
555 Wait::CdError | Wait::Timeout => return false,
556 }
557 self.cd.acknowledge_irq(IRQ_COMPLETE);
558 // The BIOS re-sends SetMode inside every bracket, between the
559 // seek completion and ReadN; every one of its ReadN commands in
560 // the trace is prefixed SetLoc,SeekL,SetMode. Match it exactly.
561 let mode = self.mode;
562 if !self.send_command(CMD_SETMODE, &[mode], IRQ_ACK, ACK_POLL) {
563 return false;
564 }
565 if !self.send_command(CMD_READN, &[], IRQ_ACK, ACK_POLL) {
566 return false;
567 }
568 self.cd.set_irq_enable_mask(ALL_IRQS_ENABLED);
569 true
570 }
571
572 /// Block until the next sector of the running ReadN stream is ready, then
573 /// pop its 2048 bytes into `buffer`. `false` on drive error or timeout
574 /// (the stream is acked/cleaned up; follow with [`stop`](Self::stop)). A
575 /// read must be running (a successful [`start_read`](Self::start_read)).
576 pub fn read_sector(&mut self, buffer: &mut [u32; SECTOR_WORDS]) -> bool {
577 match self.wait_irq(IRQ_DATA_READY, DATA_POLL) {
578 Wait::Matched => {}
579 Wait::CdError => {
580 self.note_drive_error(DIAG_SITE_READ);
581 crate::diag::cd_read_failed(self.diagnostics());
582 self.cd.drain_response_limited(DRAIN_LIMIT);
583 self.cd.acknowledge_all_and_reset_parameters();
584 return false;
585 }
586 Wait::Timeout => {
587 self.note_timeout(DIAG_SITE_READ);
588 crate::diag::cd_read_failed(self.diagnostics());
589 self.cd.drain_response_limited(DRAIN_LIMIT);
590 self.cd.acknowledge_all_and_reset_parameters();
591 return false;
592 }
593 }
594 Self::pop_sector(&mut self.cd, buffer);
595 self.cd.drain_response_limited(DRAIN_LIMIT);
596 self.cd.acknowledge_irq(IRQ_DATA_READY);
597 true
598 }
599
600 /// Non-blocking [`read_sector`](Self::read_sector): check the controller
601 /// once and, if the next sector of the running ReadN stream is ready,
602 /// pop its 2048 bytes into `buffer` and ack it.
603 ///
604 /// `Ok(true)` means `buffer` holds a new sector, `Ok(false)` that none
605 /// has arrived yet. `Err(())` is a drive error; the stream is acked and
606 /// the caller should [`stop`](Self::stop) (the diag snapshot is set as
607 /// for `read_sector`).
608 ///
609 /// Streaming consumers (FMV) call this between units of other work so
610 /// the drive never runs ahead of the CPU by more than the controller can
611 /// hold. At double speed a sector lands every ~6.7 ms.
612 #[allow(
613 clippy::result_unit_err,
614 reason = "the failure detail is in `diagnostics`; callers only branch on it"
615 )]
616 pub fn try_read_sector(&mut self, buffer: &mut [u32; SECTOR_WORDS]) -> Result<bool, ()> {
617 let flag = self.cd.irq_flag_value();
618 if flag == IRQ_ERROR {
619 self.note_drive_error(DIAG_SITE_READ);
620 self.cd.drain_response_limited(DRAIN_LIMIT);
621 self.cd.acknowledge_all_and_reset_parameters();
622 return Err(());
623 }
624 if flag != IRQ_DATA_READY && !self.cd.is_data_fifo_ready() {
625 if flag != 0 {
626 self.ack_unexpected(flag);
627 }
628 return Ok(false);
629 }
630 Self::pop_sector(&mut self.cd, buffer);
631 self.cd.drain_response_limited(DRAIN_LIMIT);
632 self.cd.acknowledge_irq(IRQ_DATA_READY);
633 Ok(true)
634 }
635
636 /// Pause the ReadN stream (keeps the drive spun up), ack everything and
637 /// put the interrupt mask [`prepare`](Self::prepare) replaced back.
638 /// Safe to call after failures; it tolerates a drive with no active read.
639 ///
640 /// **This returns after the Pause is acknowledged, not when the drive has
641 /// stopped.** On the console the second response comes 1.2 to 3.9 million
642 /// system clocks later (see [`pause`](super::pause)); waiting here would
643 /// charge every chunk of a table scan that long. That is safe for the next
644 /// command of a read sequence (any command cancels the pending second
645 /// response, and a data sector still in flight is drained by the waits),
646 /// and wrong for a caller that then asks the drive for its state: a GetStat
647 /// right after still says "reading". Use [`stop_proved`](Self::stop_proved)
648 /// when the drive has to be quiet before anything else happens.
649 pub fn stop(&mut self) {
650 if self.send_command(CMD_PAUSE, &[], IRQ_ACK, CLEANUP_POLL) {
651 let _ = self.wait_irq(IRQ_COMPLETE, CLEANUP_POLL);
652 self.cd.drain_response_limited(DRAIN_LIMIT);
653 self.cd.acknowledge_irq(IRQ_COMPLETE);
654 }
655 self.cd.acknowledge_all_and_reset_parameters();
656 // Last, so a CD-ROM IRQ still latched cannot reach the CPU through
657 // the restored mask.
658 self.restore_irq_mask();
659 }
660
661 /// [`stop`](Self::stop), then wait until the drive has really stopped, with
662 /// the protocol the console needs ([`pause::pause_until_stopped`]): wait for
663 /// the second response up to [`pause::COMPLETE_SPINS`], settle by status
664 /// when it never comes, and send the Pause again after a seek that refused
665 /// it. Takes up to about 60 ms of drive time after a long read at double
666 /// speed and 115 ms at single speed; in a failure it takes up to a second.
667 ///
668 /// On `Err` the interrupt mask is restored all the same and
669 /// [`diagnostics`](Self::diagnostics) carries [`DIAG_PAUSE`] with the
670 /// [`PauseFailure::code`]. The caller decides whether to retry or give up.
671 pub fn stop_proved(&mut self) -> Result<(), PauseFailure> {
672 let result = pause::pause_until_stopped(&mut ReaderPause(self));
673 if let Err(failure) = result {
674 self.diag = [DIAG_PAUSE, failure.code(), CMD_PAUSE, 0];
675 }
676 self.cd.acknowledge_all_and_reset_parameters();
677 self.restore_irq_mask();
678 result
679 }
680}
681
682/// [`SectorReader`] as the drive of [`pause::pause_until_stopped`].
683struct ReaderPause<'a>(&'a mut SectorReader);
684
685impl PauseDrive for ReaderPause<'_> {
686 fn send_pause(&mut self) -> PauseAnswer {
687 match self
688 .0
689 .send_command_waiting(CMD_PAUSE, &[], IRQ_ACK, CLEANUP_POLL)
690 {
691 Some(Wait::Matched) => PauseAnswer::Acknowledged,
692 Some(Wait::CdError) => PauseAnswer::Refused,
693 Some(Wait::Timeout) | None => PauseAnswer::Silent,
694 }
695 }
696
697 fn wait_completion(&mut self, spins: u32) -> Completion {
698 let reader = &mut *self.0;
699 match reader.wait_irq(IRQ_COMPLETE, spins) {
700 Wait::Matched => {
701 reader.cd.drain_response_limited(DRAIN_LIMIT);
702 reader.cd.acknowledge_irq(IRQ_COMPLETE);
703 Completion::Arrived
704 }
705 Wait::CdError => {
706 reader.note_drive_error(CMD_PAUSE);
707 reader.cd.drain_response_limited(DRAIN_LIMIT);
708 reader.cd.acknowledge_all_and_reset_parameters();
709 Completion::Error
710 }
711 Wait::Timeout => Completion::TimedOut,
712 }
713 }
714
715 fn status(&mut self) -> Option<u8> {
716 let response = self.0.cd.try_status(ACK_POLL)?;
717 response.bytes().first().copied()
718 }
719
720 fn wait_seek_end(&mut self, spins: u32) -> bool {
721 let reader = &mut *self.0;
722 match reader.wait_irq(IRQ_DATA_READY, spins) {
723 Wait::Matched => {
724 // wait_irq also matches on a ready FIFO with no flag; pop either way.
725 reader.ack_unexpected(IRQ_DATA_READY);
726 true
727 }
728 Wait::CdError => {
729 reader.cd.drain_response_limited(DRAIN_LIMIT);
730 reader.cd.acknowledge_all_and_reset_parameters();
731 false
732 }
733 Wait::Timeout => false,
734 }
735 }
736}
737
738#[allow(
739 deprecated,
740 reason = "the old no-argument constructor is what Default always meant"
741)]
742impl Default for SectorReader {
743 fn default() -> Self {
744 Self::new()
745 }
746}
747
748/// The `I_MASK` to put back when a polled stream ends: the one it found, plus
749/// the sources a driver installed meanwhile asked to keep
750/// ([`irq::keep_enabled_while_polling`]). Restoring the saved word alone would
751/// drop a source (the pad engine's) that was switched on during the stream.
752const fn mask_after_stream(saved: u32, keep: u32) -> u32 {
753 saved | keep
754}
755
756#[cfg(test)]
757mod tests {
758 use super::*;
759
760 #[test]
761 fn a_source_kept_during_the_stream_survives_its_end() {
762 // The pad engine installed mid-stream: its bits were not in the mask
763 // the reader saved, and must not be dropped when it is put back.
764 assert_eq!(mask_after_stream(0b0101, 0b1000_0000), 0b1000_0101);
765 assert_eq!(mask_after_stream(0b0101, 0), 0b0101);
766 }
767
768 #[test]
769 fn the_reader_owns_the_token_and_hands_it_back() {
770 // SAFETY: a test-local token on the host. Releasing a reader that never
771 // prepared touches no register (no mask is saved to restore).
772 let reader = SectorReader::with_cd(unsafe { Cd::steal() });
773 assert_eq!(reader.diagnostics(), 0);
774 let _token: Cd = reader.release();
775 }
776
777 #[test]
778 fn a_reader_fits_a_static_because_the_constructor_is_const() {
779 // SAFETY: a test-local token on the host; the static is never used.
780 static _READER: SectorReader = SectorReader::with_cd(unsafe { Cd::steal() });
781 }
782
783 #[test]
784 fn a_second_prepare_keeps_the_callers_mask_not_the_streams() {
785 let mut saved = SavedMask::default();
786 saved.keep(0x0000_0305); // the caller's mask
787 saved.keep(1 << psx_hw::irq::source::VBLANK); // a second prepare's view
788 assert_eq!(saved.take(), Some(0x0000_0305));
789 assert_eq!(saved.take(), None, "stop restores once");
790 saved.keep(0x42);
791 assert_eq!(saved.take(), Some(0x42), "a new stream saves afresh");
792 }
793
794 #[test]
795 fn the_idle_hook_runs_when_set_and_not_after_it_is_removed() {
796 use core::sync::atomic::{AtomicU32, Ordering};
797 static CALLS: AtomicU32 = AtomicU32::new(0);
798 fn count() {
799 CALLS.fetch_add(1, Ordering::Relaxed);
800 }
801 run_idle_hook();
802 assert_eq!(CALLS.load(Ordering::Relaxed), 0, "no hook, no call");
803 set_idle_hook(Some(count));
804 run_idle_hook();
805 run_idle_hook();
806 assert_eq!(CALLS.load(Ordering::Relaxed), 2);
807 set_idle_hook(None);
808 run_idle_hook();
809 assert_eq!(CALLS.load(Ordering::Relaxed), 2);
810 }
811
812 #[test]
813 fn the_sector_is_2048_bytes_of_words() {
814 assert_eq!(SECTOR_WORDS * 4, 2048);
815 }
816}