Skip to main content

strat9_kernel/s9vm/
fdc.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! 82077AA-compatible floppy disk controller and 1.44 MiB drive model.
24//!
25//! The s9vm stub firmware services `INT 13h` from the host, so a guest never
26//! talks to the controller. A **real firmware** (SeaBIOS) implements `INT 13h`
27//! in its own 16-bit code and drives the FDC directly: DOR reset, command and
28//! parameter bytes through the FIFO, an IRQ 6 completion, and a DMA transfer
29//! through channel 2. This module models that command-level interface.
30//!
31//! # Modelled command set
32//!
33//! Only the commands SeaBIOS issues are implemented: `SPECIFY`,
34//! `RECALIBRATE`, `SENSE INTERRUPT`, `SEEK`, `READ ID`, `READ DATA`, `WRITE
35//! DATA` and `FORMAT TRACK` (accepted, but formatting a read-only test image
36//! does not mutate it). Unknown commands complete immediately with the invalid
37//! opcode status `0x80`, so a probe cannot hang.
38//!
39//! # DMA
40//!
41//! The controller does not touch memory. [`FloppyController::write`] returns an
42//! [`FdcEvent`]; a transfer event names the starting LBA and sector count, and
43//! the caller performs the channel-2 DMA through its own physical-memory view.
44//! The controller already queued the seven result bytes and raised its IRQ
45//! flag, so the completion is visible to the guest as soon as the transfer is
46//! done.
47//!
48//! # Geometry
49//!
50//! The image is a standard 80 x 2 x 18 x 512 floppy: 1 474 560 bytes and 2 880
51//! sectors. A CHS access outside that geometry returns a "sector not found"
52//! result instead of wrapping.
53
54/// Size of one floppy sector.
55pub const SECTOR_SIZE: usize = 512;
56
57use alloc::{vec, vec::Vec};
58
59/// Base of the floppy controller register window.
60pub const BASE_PORT: u16 = 0x3F0;
61/// Digital output register (motor, DMA/IRQ enable, reset, drive select).
62pub const DOR_PORT: u16 = 0x3F2;
63/// Main status register (read-only).
64pub const MSR_PORT: u16 = 0x3F4;
65/// FIFO data register (command, parameters and results).
66pub const DATA_PORT: u16 = 0x3F5;
67/// Configuration control register / digital input register.
68pub const DIR_PORT: u16 = 0x3F7;
69/// ISA interrupt line of the controller.
70pub const IRQ_LINE: u8 = 6;
71
72/// DOR bit 2: controller reset (0 = held in reset).
73pub const DOR_RESET: u8 = 0x04;
74/// DOR bit 3: DMA and interrupt enable.
75pub const DOR_IRQ_DMA: u8 = 0x08;
76/// Main status register: ready for a byte.
77pub const MSR_RQM: u8 = 0x80;
78/// Main status register: data direction (1 = controller to host).
79pub const MSR_DIO: u8 = 0x40;
80
81/// `SPECIFY`: 2 parameter bytes.
82pub const CMD_SPECIFY: u8 = 0x03;
83/// `RECALIBRATE`: 1 parameter byte.
84pub const CMD_RECALIBRATE: u8 = 0x07;
85/// `SENSE INTERRUPT STATUS`: no parameter, 2 result bytes.
86pub const CMD_SENSE_INTERRUPT: u8 = 0x08;
87/// `SEEK`: 2 parameter bytes.
88pub const CMD_SEEK: u8 = 0x0F;
89/// `READ ID`: 1 parameter, 7 result bytes.
90pub const CMD_READ_ID: u8 = 0x4A;
91/// `FORMAT TRACK`: 5 parameter bytes.
92pub const CMD_FORMAT_TRACK: u8 = 0x4D;
93/// `WRITE DATA`: 8 parameter bytes.
94pub const CMD_WRITE_DATA: u8 = 0xC5;
95/// `READ DATA`: 8 parameter bytes.
96pub const CMD_READ_DATA: u8 = 0xE6;
97
98/// Floppy geometry: cylinders.
99pub const CYLINDERS: u8 = 80;
100/// Floppy geometry: heads.
101pub const HEADS: u8 = 2;
102/// Floppy geometry: sectors per track.
103pub const SECTORS_PER_TRACK: u8 = 18;
104/// Total sectors of a 1.44 MiB image.
105pub const TOTAL_SECTORS: u64 = 2880;
106/// Data-transfer size code for 512-byte sectors.
107pub const SIZE_CODE_512: u8 = 2;
108
109/// A DMA transfer requested by a completed read or write command.
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111pub struct FdcTransfer {
112    /// True for a guest-to-controller (write) transfer.
113    pub write: bool,
114    /// First linear block address.
115    pub lba: u64,
116    /// Number of 512-byte sectors.
117    pub sectors: u16,
118}
119
120/// Outcome of a port write.
121#[derive(Debug, Clone, Copy, PartialEq, Eq)]
122pub enum FdcEvent {
123    /// Nothing observable happened.
124    None,
125    /// A command completed and raised IRQ 6.
126    Irq,
127    /// A command completed, raised IRQ 6 and needs a DMA transfer.
128    Transfer(FdcTransfer),
129}
130
131/// True if `port` belongs to the controller window.
132pub const fn handles_port(port: u16) -> bool {
133    matches!(port, BASE_PORT..=DATA_PORT | DIR_PORT)
134}
135
136/// State of the modelled controller and drive.
137#[derive(Debug, Clone, PartialEq, Eq)]
138pub struct FloppyController {
139    /// Image bytes (empty when no disk is present).
140    image: Vec<u8>,
141    /// Digital output register.
142    dor: u8,
143    /// Current cylinder of the selected drive.
144    cylinder: u8,
145    /// Command and parameter collection.
146    command: u8,
147    params: [u8; 8],
148    needed: u8,
149    received: u8,
150    /// Result FIFO.
151    result: [u8; 8],
152    result_len: u8,
153    result_pos: u8,
154    /// Pending IRQ 6.
155    irq: bool,
156    /// Data rate programmed through the DIR port.
157    data_rate: u8,
158    /// Last requested transfer (diagnostics).
159    last_transfer: Option<FdcTransfer>,
160}
161
162impl FloppyController {
163    /// Creates a controller with no media.
164    pub const fn new() -> Self {
165        Self {
166            image: Vec::new(),
167            dor: 0,
168            cylinder: 0,
169            command: 0,
170            params: [0; 8],
171            needed: 0,
172            received: 0,
173            result: [0; 8],
174            result_len: 0,
175            result_pos: 0,
176            irq: false,
177            data_rate: 0,
178            last_transfer: None,
179        }
180    }
181
182    /// Installs the floppy image. The image is copied: the controller owns it.
183    pub fn load_image(&mut self, image: &[u8]) {
184        self.image = image.to_vec();
185        self.reset();
186    }
187
188    /// True when no image is loaded.
189    pub fn is_empty(&self) -> bool {
190        self.image.is_empty()
191    }
192
193    /// Capacity of the loaded image, in 512-byte sectors.
194    pub fn sectors(&self) -> u64 {
195        (self.image.len() / SECTOR_SIZE) as u64
196    }
197
198    /// True if `port` belongs to the controller window.
199    pub const fn handles_port(port: u16) -> bool {
200        matches!(port, BASE_PORT..=DATA_PORT | DIR_PORT)
201    }
202
203    /// Current main status register.
204    pub fn status(&self) -> u8 {
205        let mut status = MSR_RQM | (self.dor & 0x03);
206        if self.result_pos < self.result_len {
207            status |= MSR_DIO;
208        }
209        status
210    }
211
212    /// Reads one controller port.
213    pub fn read(&mut self, port: u16) -> Option<u8> {
214        match port {
215            0x3F0 | 0x3F1 | 0x3F3 => Some(0xFF),
216            DOR_PORT => Some(self.dor),
217            MSR_PORT => Some(self.status()),
218            DATA_PORT => {
219                if self.result_pos < self.result_len {
220                    let value = self.result[self.result_pos as usize];
221                    self.result_pos += 1;
222                    Some(value)
223                } else {
224                    Some(0)
225                }
226            }
227            DIR_PORT => Some(if self.image.is_empty() { 0x00 } else { 0x80 }),
228            _ => None,
229        }
230    }
231
232    /// Writes one controller port.
233    pub fn write(&mut self, port: u16, value: u8) -> FdcEvent {
234        match port {
235            DOR_PORT => self.write_dor(value),
236            DATA_PORT => self.push_byte(value),
237            DIR_PORT => {
238                self.data_rate = value & 0x03;
239                FdcEvent::None
240            }
241            // The FDC has no writable register at 0x3F0/0x3F1/0x3F3; the
242            // write is accepted and discarded so a probe cannot spin.
243            _ => FdcEvent::None,
244        }
245    }
246
247    /// Takes the pending IRQ-6 request.
248    pub fn take_irq(&mut self) -> bool {
249        let pending = self.irq;
250        self.irq = false;
251        pending
252    }
253
254    /// Last transfer requested by the controller.
255    pub const fn last_transfer(&self) -> Option<FdcTransfer> {
256        self.last_transfer
257    }
258
259    /// Reads one sector into `out`. Returns false for an out-of-range LBA.
260    pub fn read_sector(&self, lba: u64, out: &mut [u8; SECTOR_SIZE]) -> bool {
261        let Some(start) = (lba as usize).checked_mul(SECTOR_SIZE) else {
262            return false;
263        };
264        let Some(end) = start.checked_add(SECTOR_SIZE) else {
265            return false;
266        };
267        let Some(bytes) = self.image.get(start..end) else {
268            return false;
269        };
270        out.copy_from_slice(bytes);
271        true
272    }
273
274    /// Writes one sector. Returns false for an out-of-range LBA.
275    pub fn write_sector(&mut self, lba: u64, bytes: &[u8; SECTOR_SIZE]) -> bool {
276        let Some(start) = (lba as usize).checked_mul(SECTOR_SIZE) else {
277            return false;
278        };
279        let Some(end) = start.checked_add(SECTOR_SIZE) else {
280            return false;
281        };
282        let Some(slot) = self.image.get_mut(start..end) else {
283            return false;
284        };
285        slot.copy_from_slice(bytes);
286        true
287    }
288
289    /// Clears the command and result state (not the media).
290    fn reset(&mut self) {
291        self.cylinder = 0;
292        self.command = 0;
293        self.needed = 0;
294        self.received = 0;
295        self.result_len = 0;
296        self.result_pos = 0;
297        self.last_transfer = None;
298        self.irq = false;
299    }
300
301    /// Handles a DOR write, including the reset transition.
302    fn write_dor(&mut self, value: u8) -> FdcEvent {
303        let was_reset = self.dor & DOR_RESET == 0;
304        self.dor = value;
305        if value & DOR_RESET == 0 {
306            self.reset();
307            return FdcEvent::None;
308        }
309        if was_reset {
310            // Releasing reset completes controller initialisation: the real
311            // chip raises IRQ 6 once, and SeaBIOS waits for it before sending
312            // the four SENSE INTERRUPT polls.
313            self.reset();
314            self.irq = true;
315            return FdcEvent::Irq;
316        }
317        FdcEvent::None
318    }
319
320    /// Consumes one FIFO byte: the command byte first, then its parameters.
321    fn push_byte(&mut self, value: u8) -> FdcEvent {
322        // A new command is accepted only when no result is waiting and no
323        // parameter is outstanding: the guest always drains results first.
324        if self.needed == 0 && self.received == 0 && self.result_pos >= self.result_len {
325            self.command = value;
326            self.needed = parameter_count(value);
327            self.received = 0;
328            self.result_len = 0;
329            self.result_pos = 0;
330            if self.needed == 0 {
331                return self.execute();
332            }
333            return FdcEvent::None;
334        }
335        if self.received < self.needed && (self.received as usize) < self.params.len() {
336            self.params[self.received as usize] = value;
337            self.received += 1;
338            if self.received == self.needed {
339                return self.execute();
340            }
341        }
342        FdcEvent::None
343    }
344
345    /// Runs the collected command and queues its results.
346    fn execute(&mut self) -> FdcEvent {
347        let command = self.command;
348        let params = self.params;
349        self.command = 0;
350        self.needed = 0;
351        self.received = 0;
352        self.result_len = 0;
353        self.result_pos = 0;
354        let mut event = FdcEvent::None;
355
356        match command {
357            CMD_SPECIFY => {}
358            CMD_SENSE_INTERRUPT => {
359                self.queue(&[0x20, self.cylinder]);
360            }
361            CMD_RECALIBRATE => {
362                self.cylinder = 0;
363                self.irq = true;
364                event = FdcEvent::Irq;
365            }
366            CMD_SEEK => {
367                self.cylinder = params[1];
368                self.irq = true;
369                event = FdcEvent::Irq;
370            }
371            CMD_READ_ID => {
372                let head = (params[0] >> 2) & 0x01;
373                let drive = params[0] & 0x03;
374                self.queue(&[
375                    0x20 | (head << 2) | drive,
376                    0,
377                    0,
378                    self.cylinder,
379                    head,
380                    1,
381                    SIZE_CODE_512,
382                ]);
383                self.irq = true;
384                event = FdcEvent::Irq;
385            }
386            CMD_READ_DATA | CMD_WRITE_DATA => {
387                let transfer = self.data_transfer(command, &params);
388                match transfer {
389                    Some((request, result)) => {
390                        self.queue(&result);
391                        self.last_transfer = Some(request);
392                        self.irq = true;
393                        event = FdcEvent::Transfer(request);
394                    }
395                    None => {
396                        // ST0 = abnormal termination, ST1 = no data / no
397                        // address mark: reported as a normal command failure.
398                        self.queue(&[0x40, 0x04, 0x00, params[1], params[2], params[3], 2]);
399                        self.irq = true;
400                        event = FdcEvent::Irq;
401                    }
402                }
403            }
404            CMD_FORMAT_TRACK => {
405                self.queue(&[
406                    0x20 | (params[0] & 0x07),
407                    0,
408                    0,
409                    self.cylinder,
410                    (params[0] >> 2) & 1,
411                    params[2],
412                    SIZE_CODE_512,
413                ]);
414                self.irq = true;
415                event = FdcEvent::Irq;
416            }
417            _ => {
418                // Invalid opcode: status 0x80, no transfer.
419                self.queue(&[0x80]);
420                self.irq = true;
421                event = FdcEvent::Irq;
422            }
423        }
424        event
425    }
426
427    /// Decodes a READ/WRITE parameter block into a transfer and result bytes.
428    fn data_transfer(&self, command: u8, params: &[u8; 8]) -> Option<(FdcTransfer, [u8; 7])> {
429        let drive = params[0] & 0x03;
430        let head = params[2] & (HEADS - 1);
431        let cylinder = params[1];
432        let sector = params[3];
433        let eot = params[5];
434        if cylinder >= CYLINDERS
435            || sector == 0
436            || sector > SECTORS_PER_TRACK
437            || eot < sector
438            || eot > SECTORS_PER_TRACK
439        {
440            return None;
441        }
442        let count = u16::from(eot - sector + 1);
443        let lba = u64::from(cylinder) * u64::from(HEADS) * u64::from(SECTORS_PER_TRACK)
444            + u64::from(head) * u64::from(SECTORS_PER_TRACK)
445            + u64::from(sector - 1);
446        if lba + u64::from(count) > self.sectors() {
447            return None;
448        }
449        let transfer = FdcTransfer {
450            write: command == CMD_WRITE_DATA,
451            lba,
452            sectors: count,
453        };
454        let result = [
455            0x20 | (head << 2) | drive,
456            0,
457            0,
458            cylinder,
459            head,
460            sector,
461            SIZE_CODE_512,
462        ];
463        Some((transfer, result))
464    }
465
466    /// Appends bytes to the result FIFO.
467    fn queue(&mut self, bytes: &[u8]) {
468        self.result_len = bytes.len().min(self.result.len()) as u8;
469        self.result[..self.result_len as usize].copy_from_slice(&bytes[..self.result_len as usize]);
470        self.result_pos = 0;
471    }
472}
473
474impl Default for FloppyController {
475    fn default() -> Self {
476        Self::new()
477    }
478}
479
480/// Number of parameter bytes that follow `command`.
481pub const fn parameter_count(command: u8) -> u8 {
482    match command {
483        CMD_SPECIFY => 2,
484        CMD_RECALIBRATE => 1,
485        CMD_SENSE_INTERRUPT => 0,
486        CMD_SEEK => 2,
487        CMD_READ_ID => 1,
488        CMD_FORMAT_TRACK => 5,
489        CMD_WRITE_DATA | CMD_READ_DATA => 8,
490        _ => 0,
491    }
492}
493
494/// Builds a deterministic, zero-filled 1.44 MiB floppy image.
495///
496/// Host-test helper; the kernel embeds the FreeDOS image instead.
497pub fn blank_image() -> Vec<u8> {
498    vec![0u8; TOTAL_SECTORS as usize * SECTOR_SIZE]
499}