pcenginecd_rust/
scsi.rs

1//! The drive's SCSI-class controller: bus signals, phases, the REQ/ACK handshake, the commands
2//! (`scsi.py`).
3//!
4//! The CD unit's controller is not emulated as a microcontroller (there is no second CPU on this
5//! machine); it is a bus state machine that the System Card drives through `$1800-$1802` and
6//! `$1808` [hw: pcetech 8; emu: Mesen2 `PceScsiBus.cpp`, Geargrafx `scsi_controller.cpp`,
7//! Mednafen `scsicd.cpp`, ares `pcd/scsi.cpp`, MAME `pce_cd.cpp` all do the same]. Everything
8//! here is time in **master clocks** (21.477272 MHz); the unit calls `run_to(mclk)` before
9//! register accesses and the bus then runs its own timers up to that instant.
10//!
11//! Signals (`$1800` read): D3 I/O, D4 C/D, D5 MSG, D6 REQ, D7 BSY. Phases and the signals they
12//! hold:
13//!
14//! | phase       | BSY | C/D | I/O | MSG | REQ | what the CPU does                      |
15//! | ----------- | --- | --- | --- | --- | --- | -------------------------------------- |
16//! | bus free    |     |     |     |     |     | writes `$1800` (selects the drive)     |
17//! | command     |  1  |  1  |     |     |  1  | writes command bytes to `$1801`        |
18//! | data in     |  1  |     |  1  |     | (1) | reads bytes from `$1801`/`$1808`       |
19//! | status      |  1  |  1  |  1  |     | (1) | reads the status byte                  |
20//! | message in  |  1  |  1  |  1  |  1  | (1) | reads the message byte                 |
21//! | busy        |  1  |     |     |     |     | waits (an audio command in progress)   |
22//!
23//! Every byte is a REQ/ACK handshake: the drive raises REQ, the CPU sets ACK (`$1802` bit 7),
24//! the drive drops REQ, the CPU drops ACK. IRQ2 sources (`$1803` bits): data-in 0x40 and
25//! status/message 0x20 are REQ held in those phases (`CdUnit` turns the levels into IRQ2).
26//!
27//! The timings are `ScsiSwitches` (the reference's class attributes), all provisional (U8): the
28//! only measurements of this hardware are Shadoff's seek table (tier 3) and the test ROMs
29//! Mesen2's author ran on a real console (tier 5, claimed in his source comments).
30//!
31//! Differences forced by Rust:
32//!
33//! - **The bus owns the audio player** (`bus.cdda`), where the reference's bus and unit hold
34//!   the same object; the player's `on_good_status` callback is `cdda.good_status_due`, answered
35//!   here right after the player ran (`run_cdda`).
36//! - **The `irq` callback** into the unit is a list, `irq_changes`, of `(mask, level)` in the
37//!   order the reference would have called; the unit applies it after each call into the bus
38//!   (nothing the callback reads can change in between).
39//! - The command list `cmd`, the buffer `out` and the ports are bytes; a sector with no disc
40//!   in the drive (the reference asserts) reads as zeros.
41
42use std::collections::VecDeque;
43use std::rc::Rc;
44
45use pcengine_rust::machine::MASTER_HZ;
46use serde::{Deserialize, Serialize};
47
48use crate::cdda::CddaPlayer;
49use crate::disc::{from_bcd, lba_to_msf, msf_to_lba, relative_msf, to_bcd, Disc, DATA_SECTOR};
50use crate::seek::seek_time_ms;
51
52#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
53pub enum Phase {
54    BusFree,
55    Command,
56    DataIn,
57    MessageIn,
58    Status,
59    Busy,
60}
61
62impl Phase {
63    /// The reference's `Phase.value`.
64    pub fn value(self) -> &'static str {
65        match self {
66            Phase::BusFree => "bus free",
67            Phase::Command => "command",
68            Phase::DataIn => "data in",
69            Phase::MessageIn => "message in",
70            Phase::Status => "status",
71            Phase::Busy => "busy",
72        }
73    }
74}
75
76/// What a queued drive timer does when it fires.
77#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
78pub enum Update {
79    None,
80    CommandPhase,
81    Req,
82    DataInPhase,
83    GoodStatus,
84}
85
86// SCSI status byte
87pub const GOOD: u8 = 0x00;
88pub const CHECK_CONDITION: u8 = 0x02;
89
90// Commands the System Card issues [hw: pcetech 8]. REQUEST SENSE (0x03) is a standard SCSI-2
91// command the BIOS sends after commands; Mesen2 does not implement it (it answers Good with no
92// data), Mednafen sends an 18-byte fixed-format block (C14).
93pub const CMD_TEST_UNIT_READY: u8 = 0x00;
94pub const CMD_REQUEST_SENSE: u8 = 0x03;
95pub const CMD_READ: u8 = 0x08;
96pub const CMD_AUDIO_START: u8 = 0xD8;
97pub const CMD_AUDIO_END: u8 = 0xD9;
98pub const CMD_PAUSE: u8 = 0xDA;
99pub const CMD_READ_SUBQ: u8 = 0xDD;
100pub const CMD_READ_TOC: u8 = 0xDE;
101
102pub fn command_length(op: u8) -> Option<usize> {
103    match op {
104        CMD_TEST_UNIT_READY | CMD_REQUEST_SENSE | CMD_READ => Some(6),
105        CMD_AUDIO_START | CMD_AUDIO_END | CMD_PAUSE | CMD_READ_SUBQ | CMD_READ_TOC => Some(10),
106        _ => None,
107    }
108}
109
110// Sense keys / additional codes used (SCSI-2)
111pub const SENSE_NOT_READY: u8 = 0x02;
112pub const SENSE_ILLEGAL_REQUEST: u8 = 0x05;
113pub const ASC_MEDIUM_NOT_PRESENT: u8 = 0x3A;
114pub const ASC_INVALID_COMMAND: u8 = 0x20;
115pub const ASC_LBA_OUT_OF_RANGE: u8 = 0x21;
116
117/// Timing (master clocks), provisional; tier in the comment. The reference's `ScsiBus` class
118/// attributes, with its defaults.
119///
120/// [emu: Mesen2, "approximations ... haven't been validated beyond what validator.pce checks"]
121/// Mesen2 counts these in units of 3 master clocks (one fast CPU cycle); converted here.
122#[derive(Clone, Copy, Debug, PartialEq)]
123pub struct ScsiSwitches {
124    /// tier 5: SEL to the drive entering the command phase
125    pub sel_to_command_phase: i64,
126    /// tier 5: REQ for the next command byte
127    pub next_command_byte_req: i64,
128    /// tier 5, deliberately ~100x shorter than the real spin-up
129    pub test_unit_ready: i64,
130    /// tier 5
131    pub toc_answer: i64,
132    /// tier 5
133    pub subq_answer: i64,
134    /// tier 5: last data byte taken to the good status
135    pub done_status: i64,
136    /// tier 5: SEL during data in ("verificator.pce")
137    pub abort_to_command: i64,
138    /// tier 5: an auto-ack pulse ("hardware measurements show ~1 us")
139    pub ack_clear: i64,
140    /// [hw: Red Book] single speed: 75 sectors a second; one sector's bytes are delivered this
141    /// often (tier 2 for the rate, the delivery phase is U8).
142    pub sector_clocks: i64,
143    /// [emu: Mesen2 comment, Sherlock Holmes] software that misses a sector waits for a
144    /// re-read; tier 5
145    pub reread_penalty_ms: i64,
146    /// The seek model is `seek.rs` (Shadoff's measurements, tier 3 for the shape).
147    pub seek_scale: f64,
148    /// Bytes in the READ TOC answers for kinds 0 (first/last track), 1 (lead-out), 2 (a
149    /// track). Mednafen sends 2, 3, 4 ("returned data lengths on real PCE are not confirmed",
150    /// its own comment); Mesen2 sends 4, 4, 4 (C15). Tier 5 both; the BIOS must read the same
151    /// number.
152    pub toc_answer_bytes: [usize; 3],
153    /// An opcode the drive does not know (C22): Good status with no data [emu: Mesen2,
154    /// Geargrafx], or CHECK CONDITION with ILLEGAL REQUEST / INVALID COMMAND for REQUEST SENSE
155    /// to report [emu: Mednafen `scsicd.cpp`; the SCSI-2 rule for an unsupported opcode, which
156    /// this drive is not known to follow]. True selects the second. Either way the answer comes
157    /// at the first byte (Mednafen first waits for its opcode group's CDB length).
158    pub unknown_command_check_condition: bool,
159}
160
161impl Default for ScsiSwitches {
162    fn default() -> Self {
163        ScsiSwitches {
164            sel_to_command_phase: 25_000 * 3,
165            next_command_byte_req: 1_000 * 3,
166            test_unit_ready: 150_000 * 3,
167            toc_answer: 3_000 * 3,
168            subq_answer: 1_000 * 3,
169            done_status: 1_000 * 3,
170            abort_to_command: 300_000 * 3,
171            ack_clear: 21,
172            sector_clocks: MASTER_HZ * DATA_SECTOR as i64 / 153_600,
173            reread_penalty_ms: 290,
174            seek_scale: 1.0,
175            toc_answer_bytes: [2, 3, 4],
176            unknown_command_check_condition: false,
177        }
178    }
179}
180
181/// Signals, phase, timers and the command set. `irq_changes` collects (mask, level) when the
182/// REQ-held-in-a-phase conditions change (mask 0x40 data in, 0x20 status/message).
183#[derive(Serialize, Deserialize)]
184pub struct ScsiBus {
185    #[serde(skip)]
186    pub disc: Option<Rc<Disc>>,
187    pub cdda: CddaPlayer,
188    #[serde(skip)]
189    pub switches: ScsiSwitches,
190    pub now: i64,
191    /// (mclk, text) of commands, for the tests and runs
192    #[serde(skip)]
193    pub log: Vec<(i64, String)>,
194    #[serde(skip)]
195    pub record_log: bool,
196    #[serde(skip)]
197    pub irq_changes: Vec<(u8, bool)>,
198    pub bsy: bool,
199    pub sel: bool,
200    pub cd: bool,
201    pub io: bool,
202    pub msg: bool,
203    pub req: bool,
204    pub ack: bool,
205    pub atn: bool,
206    pub rst: bool,
207    pub phase: Phase,
208    /// what the CPU wrote
209    pub data_port: u8,
210    /// what the drive presents
211    pub read_port: u8,
212    pub message_done: bool,
213    /// next LBA to deliver
214    pub sector: i64,
215    pub sectors_left: i64,
216    /// where the head is (for seek times)
217    pub last_lba: i64,
218    pub cmd: Vec<u8>,
219    pub out: VecDeque<u8>,
220    changed: bool,
221    update: Update,
222    update_at: Option<i64>,
223    read_at: Option<i64>,
224    ack_at: Option<i64>,
225    pub sense_key: u8,
226    pub sense_asc: u8,
227    irq_levels: (bool, bool),
228}
229
230fn soonest(times: [Option<i64>; 4]) -> Option<i64> {
231    times.into_iter().flatten().min()
232}
233
234impl ScsiBus {
235    pub fn new(disc: Option<Rc<Disc>>, mut cdda: CddaPlayer) -> ScsiBus {
236        cdda.disc = disc.clone();
237        let mut bus = ScsiBus {
238            disc,
239            cdda,
240            switches: ScsiSwitches::default(),
241            now: 0,
242            log: Vec::new(),
243            record_log: false,
244            irq_changes: Vec::new(),
245            bsy: false,
246            sel: false,
247            cd: false,
248            io: false,
249            msg: false,
250            req: false,
251            ack: false,
252            atn: false,
253            rst: false,
254            phase: Phase::BusFree,
255            data_port: 0,
256            read_port: 0,
257            message_done: false,
258            sector: 0,
259            sectors_left: 0,
260            last_lba: 0,
261            cmd: Vec::new(),
262            out: VecDeque::new(),
263            changed: false,
264            update: Update::None,
265            update_at: None,
266            read_at: None,
267            ack_at: None,
268            sense_key: 0,
269            sense_asc: 0,
270            irq_levels: (false, false),
271        };
272        // `irq_levels` and `rst` are set here, not by `reset` (the reference's issue 0001): the
273        // RST line is the CPU's (`$1804` bit 1), and a reset does not let go of it, so the drive
274        // stays in reset while the bit is held (Mesen2 the same).
275        bus.reset();
276        bus
277    }
278
279    /// Take a decoded state's place: the disc, the switches and the tooling stay this bus's.
280    pub(crate) fn restore(&mut self, mut saved: ScsiBus) {
281        saved.disc = self.disc.take();
282        saved.switches = self.switches;
283        saved.log = std::mem::take(&mut self.log);
284        saved.record_log = self.record_log;
285        saved.irq_changes = std::mem::take(&mut self.irq_changes);
286        let mut cdda = std::mem::take(&mut self.cdda);
287        cdda.restore(std::mem::take(&mut saved.cdda));
288        saved.cdda = cdda;
289        *self = saved;
290    }
291
292    // -- state ---------------------------------------------------------------------------------
293
294    pub fn reset(&mut self) {
295        self.bsy = false;
296        self.sel = false;
297        self.cd = false;
298        self.io = false;
299        self.msg = false;
300        self.req = false;
301        self.ack = false;
302        self.atn = false;
303        self.phase = Phase::BusFree;
304        self.data_port = 0;
305        self.read_port = 0;
306        self.message_done = false;
307        self.sector = 0;
308        self.sectors_left = 0;
309        self.last_lba = 0;
310        self.cmd = Vec::new();
311        self.out = VecDeque::new();
312        self.changed = false;
313        self.update = Update::None;
314        self.update_at = None;
315        self.read_at = None;
316        self.ack_at = None;
317        self.sense_key = 0;
318        self.sense_asc = 0;
319        self.cdda.stop();
320        self.update_irq(); // REQ is down: a level that was up is reported dropped (issue 0001)
321    }
322
323    /// `$1800` read: I/O D3, C/D D4, MSG D5, REQ D6, BSY D7 [emu: all].
324    pub fn status_bits(&self) -> u8 {
325        (if self.io { 0x08 } else { 0 })
326            | (if self.cd { 0x10 } else { 0 })
327            | (if self.msg { 0x20 } else { 0 })
328            | (if self.req { 0x40 } else { 0 })
329            | (if self.bsy { 0x80 } else { 0 })
330    }
331
332    pub fn current_lba(&self) -> i64 {
333        if self.cdda.active() {
334            self.cdda.position()
335        } else {
336            self.last_lba
337        }
338    }
339
340    // -- time ----------------------------------------------------------------------------------
341
342    pub fn next_event(&self) -> Option<i64> {
343        soonest([
344            self.update_at,
345            self.read_at,
346            self.ack_at,
347            self.cdda.next_event(),
348        ])
349    }
350
351    /// Run the player and answer the good statuses it asked for (the reference's player calls
352    /// `good_status` from inside its `run_to`).
353    fn run_cdda(&mut self, mclk: i64) {
354        self.cdda.run_to(mclk);
355        for _ in 0..std::mem::take(&mut self.cdda.good_status_due) {
356            self.good_status();
357        }
358    }
359
360    /// Fire every timer due at or before `mclk`, in time order.
361    pub fn run_to(&mut self, mclk: i64) {
362        while let Some(at) = self.next_event().filter(|&at| at <= mclk) {
363            self.now = self.now.max(at);
364            if self.cdda.next_event() == Some(at) {
365                self.run_cdda(at);
366            } else if self.ack_at == Some(at) {
367                self.ack_at = None;
368                self.set_ack_signal(false);
369            } else if self.update_at == Some(at) {
370                let kind = self.update;
371                self.update_at = None;
372                self.fire(kind);
373            } else if self.read_at == Some(at) {
374                self.read_at = None;
375                self.sector_ready();
376            }
377            self.settle();
378        }
379        self.now = self.now.max(mclk);
380        self.run_cdda(self.now);
381    }
382
383    fn queue(&mut self, kind: Update, delay: i64) {
384        if kind != self.update || self.update_at.is_none() {
385            self.update = kind;
386            self.update_at = Some(self.now + delay);
387        }
388    }
389
390    fn fire(&mut self, kind: Update) {
391        match kind {
392            Update::CommandPhase => self.set_phase(Phase::Command),
393            Update::Req => self.set_req_signal(true),
394            Update::DataInPhase => self.set_phase(Phase::DataIn),
395            Update::GoodStatus => self.good_status(),
396            Update::None => {}
397        }
398    }
399
400    // -- signals and phases ----------------------------------------------------------------------
401
402    /// The reference's `_set(req=...)`.
403    fn set_req_signal(&mut self, value: bool) {
404        if self.req != value {
405            self.req = value;
406            self.changed = true;
407        }
408        self.update_irq();
409    }
410
411    /// The reference's `_set(ack=...)`.
412    fn set_ack_signal(&mut self, value: bool) {
413        if self.ack != value {
414            self.ack = value;
415            self.changed = true;
416        }
417        self.update_irq();
418    }
419
420    fn update_irq(&mut self) {
421        let held = self.req && self.io && self.bsy;
422        // (data in 0x40, status/message 0x20)
423        let levels = (held && !self.cd, held && self.cd);
424        if levels != self.irq_levels {
425            if levels.0 != self.irq_levels.0 {
426                self.irq_changes.push((0x40, levels.0));
427            }
428            if levels.1 != self.irq_levels.1 {
429                self.irq_changes.push((0x20, levels.1));
430            }
431            self.irq_levels = levels;
432        }
433    }
434
435    fn set_phase(&mut self, phase: Phase) {
436        if self.phase == phase {
437            return;
438        }
439        self.update_at = None; // a phase change cancels a queued drive timer
440        self.changed = true;
441        self.phase = phase;
442        self.bsy = false;
443        self.cd = false;
444        self.io = false;
445        self.msg = false;
446        self.req = false;
447        match phase {
448            Phase::Command => {
449                self.read_at = None; // leaving data in stops any pending sector
450                self.sectors_left = 0;
451                self.bsy = true;
452                self.cd = true;
453                self.req = true;
454            }
455            Phase::DataIn => {
456                self.bsy = true;
457                self.io = true;
458            }
459            Phase::MessageIn => {
460                self.bsy = true;
461                self.cd = true;
462                self.io = true;
463                self.msg = true;
464                self.req = true;
465            }
466            Phase::Status => {
467                self.bsy = true;
468                self.cd = true;
469                self.io = true;
470                self.req = true;
471            }
472            Phase::Busy => self.bsy = true,
473            Phase::BusFree => {}
474        }
475        self.update_irq();
476    }
477
478    /// Enter the status phase with `status`; `length` message bytes follow.
479    pub fn status_message(&mut self, status: u8, message: u8, length: usize) {
480        self.out = std::iter::repeat_n(message, length).collect();
481        self.message_done = false;
482        self.read_port = status;
483        self.set_phase(Phase::Status);
484    }
485
486    pub fn good_status(&mut self) {
487        self.status_message(GOOD, 0, 1);
488        self.settle();
489    }
490
491    // -- CPU side ------------------------------------------------------------------------------
492
493    /// A write to `$1800`: SEL pulses. From any phase but data in this starts a command.
494    pub fn select(&mut self) {
495        self.sel = true;
496        self.changed = true;
497        self.settle();
498        self.sel = false;
499        self.changed = true;
500        self.settle();
501    }
502
503    pub fn write_data(&mut self, value: u8) {
504        self.data_port = value;
505    }
506
507    pub fn read_data(&self) -> u8 {
508        if matches!(self.phase, Phase::Status | Phase::DataIn | Phase::MessageIn) {
509            return self.read_port;
510        }
511        self.data_port
512    }
513
514    pub fn set_ack(&mut self, level: bool) {
515        self.set_ack_signal(level);
516        self.settle();
517    }
518
519    /// A `$1808` data read: ACK for a moment, so the next byte is presented without the CPU's
520    /// own handshake [emu: Mesen2; the pulse width is its measurement].
521    pub fn pulse_ack(&mut self) {
522        self.set_ack_signal(true);
523        self.ack_at = Some(self.now + self.switches.ack_clear);
524        self.settle();
525    }
526
527    /// `$1804` bit 1: the SCSI RST line.
528    pub fn set_reset(&mut self, level: bool) {
529        self.rst = level;
530        self.changed = true;
531        self.settle();
532    }
533
534    // -- the state machine ---------------------------------------------------------------------
535
536    /// Run the phase logic until the signals stop changing (Mesen2's `UpdateState`).
537    fn settle(&mut self) {
538        while self.changed {
539            self.changed = false;
540            if self.rst {
541                self.reset();
542                return;
543            }
544            if self.sel {
545                self.update_at = None;
546                if self.phase != Phase::DataIn {
547                    self.queue(Update::CommandPhase, self.switches.sel_to_command_phase);
548                } else {
549                    // Aborting a transfer yields an 8-byte message, then the command phase
550                    // comes back on its own [emu: Mesen2 from scsitest.pce, verificator.pce]
551                    self.status_message(GOOD, 0, 8);
552                    self.queue(Update::CommandPhase, self.switches.abort_to_command);
553                    break;
554                }
555            } else {
556                match self.phase {
557                    Phase::Command => self.command_phase(),
558                    Phase::DataIn => self.data_in_phase(),
559                    Phase::Status => self.status_phase(),
560                    Phase::MessageIn => self.message_phase(),
561                    Phase::BusFree | Phase::Busy => {}
562                }
563            }
564        }
565    }
566
567    fn handshake_done(&self) -> bool {
568        !self.req && !self.ack
569    }
570
571    fn command_phase(&mut self) {
572        if self.req && self.ack {
573            self.set_req_signal(false);
574            self.cmd.push(self.data_port);
575        } else if self.handshake_done() && !self.cmd.is_empty() {
576            match command_length(self.cmd[0]) {
577                None => {
578                    // An unknown command (C22, `unknown_command_check_condition`)
579                    self.cmd.clear();
580                    if self.switches.unknown_command_check_condition {
581                        self.fail(SENSE_ILLEGAL_REQUEST, ASC_INVALID_COMMAND);
582                    } else {
583                        self.status_message(GOOD, 0, 1);
584                    }
585                }
586                Some(length) if self.cmd.len() >= length => {
587                    let cmd = std::mem::take(&mut self.cmd);
588                    self.execute(&cmd);
589                }
590                Some(_) => self.queue(Update::Req, self.switches.next_command_byte_req),
591            }
592        }
593    }
594
595    fn data_in_phase(&mut self) {
596        if self.req && self.ack {
597            self.set_req_signal(false);
598        } else if self.handshake_done() {
599            if let Some(byte) = self.out.pop_front() {
600                self.read_port = byte;
601                self.set_req_signal(true);
602            } else if self.sectors_left == 0 && self.read_at.is_none() {
603                self.queue(Update::GoodStatus, self.switches.done_status);
604            }
605        }
606    }
607
608    fn status_phase(&mut self) {
609        if self.req && self.ack {
610            self.set_req_signal(false);
611        } else if self.handshake_done() {
612            if let Some(byte) = self.out.pop_front() {
613                self.read_port = byte;
614                if self.out.is_empty() {
615                    self.set_phase(Phase::MessageIn);
616                } else {
617                    self.set_req_signal(true);
618                }
619            }
620        }
621    }
622
623    fn message_phase(&mut self) {
624        if self.req && self.ack {
625            self.set_req_signal(false);
626            self.message_done = true;
627        } else if self.handshake_done() && self.message_done {
628            self.message_done = false;
629            self.set_phase(Phase::BusFree);
630        }
631    }
632
633    // -- sector delivery -----------------------------------------------------------------------
634
635    fn sector_ready(&mut self) {
636        if !self.out.is_empty() {
637            // The program has not taken the last sector: the drive has to find it again.
638            let penalty = (MASTER_HZ * self.switches.reread_penalty_ms) as f64 / 1000.0;
639            self.read_at = Some(self.now + penalty as i64);
640            return;
641        }
642        self.out = match self.disc.as_ref() {
643            Some(disc) => disc.read_data(self.sector).into_iter().collect(),
644            None => std::iter::repeat_n(0, DATA_SECTOR).collect(),
645        };
646        self.last_lba = self.sector;
647        self.sector = (self.sector + 1) & 0x1FFFFF;
648        self.sectors_left -= 1;
649        self.read_at = (self.sectors_left != 0).then_some(self.now + self.switches.sector_clocks);
650        self.changed = true; // the data-in logic presents the first byte
651        self.set_phase(Phase::DataIn);
652    }
653
654    // -- the commands --------------------------------------------------------------------------
655
656    fn note(&mut self, cmd: &[u8]) {
657        if self.record_log {
658            let bytes: Vec<String> = cmd.iter().map(|b| format!("{b:02X}")).collect();
659            self.log
660                .push((self.now, format!("cmd {}", bytes.join(" "))));
661        }
662    }
663
664    fn fail(&mut self, key: u8, asc: u8) {
665        self.sense_key = key;
666        self.sense_asc = asc;
667        self.status_message(CHECK_CONDITION, 0, 1);
668    }
669
670    fn execute(&mut self, cmd: &[u8]) {
671        let op = cmd[0];
672        self.note(cmd);
673        let Some(disc) = self.disc.clone() else {
674            // no disc: TEST UNIT READY and every other command but REQUEST SENSE fail alike
675            if op == CMD_REQUEST_SENSE {
676                self.request_sense(cmd);
677            } else {
678                self.fail(SENSE_NOT_READY, ASC_MEDIUM_NOT_PRESENT);
679            }
680            return;
681        };
682        match op {
683            CMD_TEST_UNIT_READY => self.queue(Update::GoodStatus, self.switches.test_unit_ready),
684            CMD_REQUEST_SENSE => self.request_sense(cmd),
685            CMD_READ => self.read(cmd, &disc),
686            CMD_AUDIO_START => self.audio_start(cmd, &disc),
687            CMD_AUDIO_END => self.audio_end(cmd, &disc),
688            CMD_PAUSE => {
689                self.cdda.pause();
690                self.status_message(GOOD, 0, 1);
691            }
692            CMD_READ_SUBQ => self.read_subq(&disc),
693            CMD_READ_TOC => self.read_toc(cmd, &disc),
694            _ => {}
695        }
696    }
697
698    fn data_answer(&mut self, data: &[u8], delay: i64) {
699        self.out = data.iter().copied().collect();
700        self.queue(Update::DataInPhase, delay);
701    }
702
703    fn request_sense(&mut self, cmd: &[u8]) {
704        // Fixed-format sense data, SCSI-2: 0x70, segment, key, information[4], additional
705        // length, command-specific[4], ASC, ASCQ, FRU, sense-key specific[3]. The allocation
706        // length is cmd[4]; 0 means 4 bytes in SCSI-1 (C14: whether the drive honours it is
707        // unknown).
708        let mut block = [0u8; 18];
709        block[0] = 0x70;
710        block[2] = self.sense_key;
711        block[7] = 10;
712        block[12] = self.sense_asc;
713        let length = if cmd[4] != 0 { cmd[4] as usize } else { 4 };
714        self.sense_key = 0;
715        self.sense_asc = 0;
716        self.data_answer(&block[..length.min(block.len())], self.switches.subq_answer);
717    }
718
719    fn read(&mut self, cmd: &[u8], disc: &Disc) {
720        let lba = cmd[3] as i64 | (cmd[2] as i64) << 8 | ((cmd[1] & 0x1F) as i64) << 16;
721        let count = cmd[4] as i64;
722        if count == 0 {
723            self.status_message(GOOD, 0, 1);
724            return;
725        }
726        if lba >= disc.sector_count {
727            self.fail(SENSE_ILLEGAL_REQUEST, ASC_LBA_OUT_OF_RANGE);
728            return;
729        }
730        self.sector = lba;
731        self.sectors_left = count;
732        let seek = self.clocks(seek_time_ms(self.current_lba(), lba) * self.switches.seek_scale);
733        self.cdda.idle();
734        self.out.clear();
735        self.read_at = Some(self.now + seek + self.switches.sector_clocks);
736        // The phase goes to data in at once: Ys IV expects it soon after the command
737        // [emu: Mesen2 comment]. No REQ until the first sector is in the buffer.
738        self.set_phase(Phase::DataIn);
739    }
740
741    fn clocks(&self, ms: f64) -> i64 {
742        (MASTER_HZ as f64 * ms / 1000.0) as i64
743    }
744
745    /// The audio command's address; the mode is cmd[9] bits 7-6 [hw: pcetech 8; emu].
746    fn position(&self, cmd: &[u8], disc: &Disc) -> i64 {
747        match cmd[9] & 0xC0 {
748            // LBA
749            0x00 => (cmd[3] as i64) << 16 | (cmd[4] as i64) << 8 | cmd[5] as i64,
750            // MSF in BCD (absolute)
751            0x40 => msf_to_lba(from_bcd(cmd[2]), from_bcd(cmd[3]), from_bcd(cmd[4])),
752            // track number in BCD
753            0x80 => disc.track(from_bcd(cmd[2])).map_or(0, |track| track.start),
754            _ => 0,
755        }
756    }
757
758    fn audio_start(&mut self, cmd: &[u8], disc: &Disc) {
759        let start = self.position(cmd, disc);
760        if start >= disc.sector_count {
761            self.status_message(GOOD, 0, 1);
762            return;
763        }
764        let delay = self.clocks(seek_time_ms(self.current_lba(), start) * self.switches.seek_scale);
765        self.cdda.play(start, cmd[1] == 0, delay);
766        // Busy until playback starts; the player ends it with good status
767        self.set_phase(Phase::Busy);
768    }
769
770    fn audio_end(&mut self, cmd: &[u8], disc: &Disc) {
771        let end = self.position(cmd, disc);
772        let mode = cmd[1];
773        if mode == 0 {
774            self.cdda.stop();
775        } else if matches!(mode, 1..=3) {
776            self.cdda.set_end(end, mode);
777        }
778        if matches!(mode, 1 | 2) {
779            self.set_phase(Phase::Busy); // in mode 2 until playback ends
780        } else {
781            self.status_message(GOOD, 0, 1);
782        }
783    }
784
785    fn read_subq(&mut self, disc: &Disc) {
786        let lba = self.current_lba();
787        let track = disc.track_at(lba);
788        let number = track.map_or(0, |t| t.number);
789        let is_data = track.is_some_and(|t| t.is_data);
790        let rel = match track {
791            Some(t) if lba >= t.start => relative_msf(lba - t.start),
792            _ => (0, 0, 0),
793        };
794        let absolute = lba_to_msf(lba);
795        let data = [
796            self.cdda.status_code(),
797            0x01 | if is_data { 0x40 } else { 0 }, // ADR 1 (position), control bit 6 = data track
798            to_bcd(number),
799            1, // index
800            to_bcd(rel.0),
801            to_bcd(rel.1),
802            to_bcd(rel.2),
803            to_bcd(absolute.0),
804            to_bcd(absolute.1),
805            to_bcd(absolute.2),
806        ];
807        self.data_answer(&data, self.switches.subq_answer);
808    }
809
810    fn read_toc(&mut self, cmd: &[u8], disc: &Disc) {
811        let kind = cmd[1];
812        let msf = |lba: i64, last: u8| {
813            let (m, s, f) = lba_to_msf(lba);
814            [to_bcd(m), to_bcd(s), to_bcd(f), last]
815        };
816        let data: [u8; 4] = match kind {
817            // first and last track numbers
818            0 => [to_bcd(disc.first_track()), to_bcd(disc.last_track()), 0, 0],
819            // lead-out
820            1 => msf(disc.end_lba(), 0),
821            // a track's start and type
822            2 => {
823                let number = match from_bcd(cmd[2]) {
824                    0 => 1,
825                    number => number,
826                };
827                match disc.track(number) {
828                    None => msf(disc.end_lba(), 0),
829                    Some(track) => msf(track.start, if track.is_data { 4 } else { 0 }),
830                }
831            }
832            _ => {
833                self.status_message(GOOD, 0, 1);
834                return;
835            }
836        };
837        let want = self.switches.toc_answer_bytes[kind as usize].min(8);
838        let mut padded = [0u8; 8];
839        padded[..4].copy_from_slice(&data);
840        self.data_answer(&padded[..want], self.switches.toc_answer);
841    }
842}