Skip to main content

ide/
lib.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Legacy PCI/ISA IDE controller emulator (PIIX4-compatible).
5//!
6//! Emulates the storage portion of an Intel PIIX4 (82371AB) PCI-to-ISA bridge
7//! with two IDE channels (primary + secondary), each supporting up to two
8//! devices. PCI vendor/device ID: `8086:7111`.
9//!
10//! # Drive types
11//!
12//! - **ATA hard drives** — use [`Disk`] for I/O. Support
13//!   PIO and DMA modes, 28-bit and 48-bit LBA, `IDENTIFY DEVICE`, `FLUSH CACHE`.
14//! - **ATAPI optical drives** — use `PACKET COMMAND` (0xA0) to transport SCSI
15//!   CDBs over the ATA interface, delegating to [`AsyncScsiDisk`].
16//!
17//! # Port I/O
18//!
19//! Primary channel: 0x1F0–0x1F7 + 0x3F6. Secondary: 0x170–0x177 + 0x376.
20//! Bus master DMA via PCI BAR4 (PRD scatter-gather table).
21//!
22//! # Enlightened I/O
23//!
24//! Microsoft-specific optimization: enlightened INT13 commands via ports
25//! 0x1E0 (primary) and 0x160 (secondary). The guest writes an
26//! `EnlightenedInt13Command` packet GPA, collapsing the multi-exit register
27//! programming sequence into a single VM exit. Uses the `DeferredWrite`
28//! pattern for async completion.
29
30#![expect(missing_docs)]
31#![forbid(unsafe_code)]
32
33mod drive;
34mod protocol;
35
36use crate::drive::save_restore::DriveSaveRestore;
37use crate::protocol::BusMasterReg;
38use crate::protocol::DeviceControlReg;
39use crate::protocol::IdeCommand;
40use crate::protocol::IdeConfigSpace;
41use crate::protocol::Status;
42use chipset_device::ChipsetDevice;
43use chipset_device::io::IoError;
44use chipset_device::io::IoResult;
45use chipset_device::io::deferred::DeferredWrite;
46use chipset_device::io::deferred::defer_write;
47use chipset_device::pci::ByteEnabledDwordRead;
48use chipset_device::pci::ByteEnabledDwordWrite;
49use chipset_device::pci::PciConfigSpace;
50use chipset_device::pio::ControlPortIoIntercept;
51use chipset_device::pio::PortIoIntercept;
52use chipset_device::pio::RegisterPortIoIntercept;
53use chipset_device::poll_device::PollDevice;
54use disk_backend::Disk;
55use drive::DiskDrive;
56use drive::DriveRegister;
57use guestmem::GuestMemory;
58use ide_resources::IdePath;
59use inspect::Inspect;
60use inspect::InspectMut;
61use open_enum::open_enum;
62use pci_core::spec::cfg_space::Command;
63use pci_core::spec::cfg_space::HEADER_TYPE_00_SIZE;
64use pci_core::spec::cfg_space::HeaderType00;
65use protocol::BusMasterCommandReg;
66use protocol::BusMasterStatusReg;
67use scsi::CdbFlags;
68use scsi::ScsiOp;
69use scsi_core::AsyncScsiDisk;
70use scsi_defs as scsi;
71use std::fmt::Debug;
72use std::mem::offset_of;
73use std::ops::RangeInclusive;
74use std::sync::Arc;
75use std::task::Context;
76use thiserror::Error;
77use vmcore::device_state::ChangeDeviceState;
78use vmcore::line_interrupt::LineInterrupt;
79use zerocopy::IntoBytes;
80
81open_enum! {
82    pub enum IdeIoPort: u16 {
83        PRI_ENLIGHTENED = 0x1E0,
84        PRI_DATA = 0x1F0,
85        PRI_ERROR_FEATURES = 0x1F1,
86        PRI_SECTOR_COUNT = 0x1F2,
87        PRI_SECTOR_NUM = 0x1F3,
88        PRI_CYLINDER_LSB = 0x1F4,
89        PRI_CYLINDER_MSB = 0x1F5,
90        PRI_DEVICE_HEAD = 0x1F6,
91        PRI_STATUS_CMD = 0x1F7,
92        PRI_ALT_STATUS_DEVICE_CTL = 0x3F6,
93        SEC_ENLIGHTENED = 0x160,
94        SEC_DATA = 0x170,
95        SEC_ERROR_FEATURES = 0x171,
96        SEC_SECTOR_COUNT = 0x172,
97        SEC_SECTOR_NUM = 0x173,
98        SEC_CYLINDER_LSB = 0x174,
99        SEC_CYLINDER_MSB = 0x175,
100        SEC_DEVICE_HEAD = 0x176,
101        SEC_STATUS_CMD = 0x177,
102        SEC_ALT_STATUS_DEVICE_CTL = 0x376,
103    }
104}
105
106enum Port {
107    Data,
108    Drive(DriveRegister),
109    Enlightened,
110    BusMaster(BusMasterReg),
111}
112
113#[derive(Debug, Copy, Clone, PartialEq, Eq, Inspect)]
114enum DmaType {
115    /// Read from guest memory.
116    Read,
117    /// Write to guest memory.
118    Write,
119}
120
121#[derive(Debug, Inspect)]
122struct BusMasterState {
123    #[inspect(hex)]
124    cmd_status_reg: u32,
125    #[inspect(hex)]
126    port_addr_reg: u32,
127    #[inspect(hex)]
128    timing_reg: u32,
129    #[inspect(hex)]
130    secondary_timing_reg: u32,
131    #[inspect(hex)]
132    dma_ctl_reg: u32,
133}
134
135// bus master
136const DEFAULT_BUS_MASTER_PORT_ADDR_REG: u32 = 0x0000_0001;
137const DEFAULT_BUS_MASTER_CMD_STATUS_REG: u32 = 0x0280_0000;
138
139impl BusMasterState {
140    fn new() -> Self {
141        Self {
142            cmd_status_reg: DEFAULT_BUS_MASTER_CMD_STATUS_REG,
143            port_addr_reg: DEFAULT_BUS_MASTER_PORT_ADDR_REG,
144            // Enable IDE decode at startup, don't wait for the BIOS (this is
145            // not actually configurable with our hardware).
146            //
147            // TODO: define a bitfield, hard wire these bits to 1 so that they
148            // can't be cleared.
149            timing_reg: 0x80008000,
150            secondary_timing_reg: 0,
151            dma_ctl_reg: 0,
152        }
153    }
154}
155
156#[derive(Debug, Default, Inspect)]
157struct ChannelBusMasterState {
158    command_reg: BusMasterCommandReg,
159    status_reg: BusMasterStatusReg,
160    #[inspect(hex)]
161    desc_table_ptr: u32,
162    dma_state: Option<DmaState>,
163    dma_error: bool,
164}
165
166impl ChannelBusMasterState {
167    fn dma_io_type(&self) -> DmaType {
168        if self.command_reg.write() {
169            DmaType::Write
170        } else {
171            DmaType::Read
172        }
173    }
174}
175
176/// PCI-based IDE controller
177pub struct IdeDevice {
178    /// IDE controllers can support up to two IDE channels (primary and secondary)
179    /// with up to two devices (drives) per channel for a total of four IDE devices.
180    channels: [Channel; 2],
181    bus_master_state: BusMasterState,
182    bus_master_pio_dynamic: Box<dyn ControlPortIoIntercept>,
183}
184
185impl InspectMut for IdeDevice {
186    fn inspect_mut(&mut self, req: inspect::Request<'_>) {
187        req.respond()
188            .field_mut("primary", &mut self.channels[0])
189            .field_mut("secondary", &mut self.channels[1])
190            .field("bus_master_state", &self.bus_master_state);
191    }
192}
193
194#[derive(Inspect, Debug)]
195struct EnlightenedCdWrite {
196    #[inspect(skip)]
197    deferred: DeferredWrite,
198    old_adapter_control_reg: u8,
199    guest_address: u64,
200    old_features_reg: u8,
201    data_buffer: u32,
202    skip_bytes_head: u16,
203    byte_count: u32,
204    block_count: u16,
205    drive_index: usize,
206}
207
208#[derive(Inspect, Debug)]
209struct EnlightenedHddWrite {
210    #[inspect(skip)]
211    deferred: DeferredWrite,
212    old_adapter_control_reg: u8,
213    guest_address: u64,
214    drive_index: usize,
215}
216
217#[derive(Debug, Inspect)]
218#[inspect(tag = "drive_type")]
219enum EnlightenedWrite {
220    Hard(#[inspect(rename = "write")] EnlightenedHddWrite),
221    Optical(#[inspect(rename = "write")] EnlightenedCdWrite),
222}
223
224#[derive(Debug, Error)]
225pub enum NewDeviceError {
226    #[error("disk too large: {0} bytes")]
227    DiskTooLarge(u64),
228}
229
230impl IdeDevice {
231    /// Creates an IDE device from the provided channel drive configuration.
232    pub fn new(
233        guest_memory: GuestMemory,
234        register_pio: &mut dyn RegisterPortIoIntercept,
235        primary_channel_drives: [Option<DriveMedia>; 2],
236        secondary_channel_drives: [Option<DriveMedia>; 2],
237        primary_line_interrupt: LineInterrupt,
238        secondary_line_interrupt: LineInterrupt,
239    ) -> Result<Self, NewDeviceError> {
240        let channels = [
241            Channel::new(
242                primary_channel_drives,
243                ChannelType::Primary,
244                primary_line_interrupt,
245                guest_memory.clone(),
246            )?,
247            Channel::new(
248                secondary_channel_drives,
249                ChannelType::Secondary,
250                secondary_line_interrupt,
251                guest_memory,
252            )?,
253        ];
254
255        Ok(Self {
256            channels,
257            bus_master_state: BusMasterState::new(),
258            bus_master_pio_dynamic: register_pio.new_io_region("ide bus master", 16),
259        })
260    }
261
262    fn parse_port(&self, io_port: u16) -> Option<(Port, usize)> {
263        match IdeIoPort(io_port) {
264            IdeIoPort::PRI_ENLIGHTENED => Some((Port::Enlightened, 0)),
265            IdeIoPort::PRI_DATA => Some((Port::Data, 0)),
266            IdeIoPort::PRI_ERROR_FEATURES => Some((Port::Drive(DriveRegister::ErrorFeatures), 0)),
267            IdeIoPort::PRI_SECTOR_COUNT => Some((Port::Drive(DriveRegister::SectorCount), 0)),
268            IdeIoPort::PRI_SECTOR_NUM => Some((Port::Drive(DriveRegister::LbaLow), 0)),
269            IdeIoPort::PRI_CYLINDER_LSB => Some((Port::Drive(DriveRegister::LbaMid), 0)),
270            IdeIoPort::PRI_CYLINDER_MSB => Some((Port::Drive(DriveRegister::LbaHigh), 0)),
271            IdeIoPort::PRI_DEVICE_HEAD => Some((Port::Drive(DriveRegister::DeviceHead), 0)),
272            IdeIoPort::PRI_STATUS_CMD => Some((Port::Drive(DriveRegister::StatusCmd), 0)),
273            IdeIoPort::PRI_ALT_STATUS_DEVICE_CTL => {
274                Some((Port::Drive(DriveRegister::AlternateStatusDeviceControl), 0))
275            }
276            IdeIoPort::SEC_ENLIGHTENED => Some((Port::Enlightened, 1)),
277            IdeIoPort::SEC_DATA => Some((Port::Data, 1)),
278            IdeIoPort::SEC_ERROR_FEATURES => Some((Port::Drive(DriveRegister::ErrorFeatures), 1)),
279            IdeIoPort::SEC_SECTOR_COUNT => Some((Port::Drive(DriveRegister::SectorCount), 1)),
280            IdeIoPort::SEC_SECTOR_NUM => Some((Port::Drive(DriveRegister::LbaLow), 1)),
281            IdeIoPort::SEC_CYLINDER_LSB => Some((Port::Drive(DriveRegister::LbaMid), 1)),
282            IdeIoPort::SEC_CYLINDER_MSB => Some((Port::Drive(DriveRegister::LbaHigh), 1)),
283            IdeIoPort::SEC_DEVICE_HEAD => Some((Port::Drive(DriveRegister::DeviceHead), 1)),
284            IdeIoPort::SEC_STATUS_CMD => Some((Port::Drive(DriveRegister::StatusCmd), 1)),
285            IdeIoPort::SEC_ALT_STATUS_DEVICE_CTL => {
286                Some((Port::Drive(DriveRegister::AlternateStatusDeviceControl), 1))
287            }
288            io_port
289                if (IdeIoPort::PRI_ENLIGHTENED..=IdeIoPort::PRI_STATUS_CMD).contains(&io_port) =>
290            {
291                None
292            }
293            io_port
294                if (IdeIoPort::SEC_ENLIGHTENED..=IdeIoPort::SEC_STATUS_CMD).contains(&io_port) =>
295            {
296                None
297            }
298            _ => {
299                if self.bus_master_state.cmd_status_reg
300                    & protocol::PCI_CONFIG_STATUS_IO_SPACE_ENABLE_MASK
301                    == 0
302                {
303                    return None;
304                }
305
306                // If the port does not match any of the statically registered IO ports then
307                // the port is part of the dynamically registered bus master range. The IDE
308                // bus master range spans 16 ports with the first 8 corresponding to the primary
309                // IDE channel.
310                Some((
311                    Port::BusMaster(BusMasterReg(io_port & 0x7)),
312                    (io_port as usize & 0x8) >> 3,
313                ))
314            }
315        }
316    }
317}
318
319impl Channel {
320    fn enlightened_port_write(
321        &mut self,
322        data: &[u8],
323        bus_master_state: &BusMasterState,
324    ) -> IoResult {
325        if data.len() != 4 {
326            return IoResult::Err(IoError::InvalidAccessSize);
327        }
328
329        if self.enlightened_write.is_some() {
330            tracelimit::error_ratelimited!("enlightened write while one is in progress, ignoring");
331            return IoResult::Ok;
332        }
333
334        // Read the EnlightenedInt13Command packet directly from guest ram
335        let addr = u32::from_ne_bytes(data.try_into().unwrap());
336
337        let eint13_cmd = match self
338            .guest_memory
339            .read_plain::<protocol::EnlightenedInt13Command>(addr as u64)
340        {
341            Ok(cmd) => cmd,
342            Err(err) => {
343                tracelimit::error_ratelimited!(
344                    error = &err as &dyn std::error::Error,
345                    "failed to read enlightened IO command"
346                );
347                return IoResult::Ok;
348            }
349        };
350
351        // Write out the drive-head register FIRST because that is used to
352        // select the current drive.
353        self.write_drive_register(
354            DriveRegister::DeviceHead,
355            eint13_cmd.device_head.into(),
356            bus_master_state,
357        );
358
359        if let Some(status) = self.current_drive_status() {
360            if status.err() {
361                tracelimit::warn_ratelimited!(
362                    "drive is in error state, ignoring enlightened command",
363                );
364                return IoResult::Ok;
365            } else if status.bsy() || status.drq() {
366                tracelimit::warn_ratelimited!(
367                    "command is already pending on this drive, ignoring enlightened command"
368                );
369                return IoResult::Ok;
370            }
371        }
372
373        let result = if let Some(drive_type) = self.current_drive_type() {
374            match drive_type {
375                DriveType::Optical => {
376                    self.enlightened_cd_command(addr.into(), eint13_cmd, bus_master_state)
377                }
378                DriveType::Hard => {
379                    self.enlightened_hdd_command(addr.into(), eint13_cmd, bus_master_state)
380                }
381            }
382        } else {
383            tracelimit::warn_ratelimited!(
384                eint13_cmd = ?eint13_cmd,
385                drive_idx = self.state.current_drive_idx,
386                "Enlightened IO command: No attached drive"
387            );
388            IoResult::Ok
389        };
390
391        self.post_drive_access(bus_master_state);
392        result
393    }
394
395    fn enlightened_hdd_command(
396        &mut self,
397        guest_address: u64,
398        eint13_cmd: protocol::EnlightenedInt13Command,
399        bus_master_state: &BusMasterState,
400    ) -> IoResult {
401        let mut lba48 = eint13_cmd.lba_high as u64;
402        lba48 <<= 32;
403        lba48 |= eint13_cmd.lba_low as u64;
404
405        tracing::trace!(
406            command = ?eint13_cmd.command,
407            lba = lba48,
408            block_count = eint13_cmd.block_count,
409            buffer = eint13_cmd.data_buffer,
410            guest_address,
411            "enlightened hdd command"
412        );
413
414        // The enlightened INT13 path is a DMA-only fast path used by
415        // the Hyper-V BIOS. Non-DMA commands (PIO reads/writes,
416        // IDENTIFY_DEVICE, etc.) would leave the drive with a PIO
417        // buffer that DMA can't drain, causing the deferred write to
418        // never complete.
419        let cmd = eint13_cmd.command;
420        if !matches!(
421            cmd,
422            IdeCommand::READ_DMA
423                | IdeCommand::READ_DMA_ALT
424                | IdeCommand::WRITE_DMA
425                | IdeCommand::WRITE_DMA_ALT
426                | IdeCommand::READ_DMA_EXT
427                | IdeCommand::WRITE_DMA_EXT
428                | IdeCommand::WRITE_DMA_FUA_EXT
429        ) {
430            tracelimit::warn_ratelimited!(?cmd, "ignoring non-DMA command in enlightened path");
431            return IoResult::Ok;
432        }
433
434        // Write out the PRD register for the bus master
435        self.write_bus_master_reg(
436            BusMasterReg::TABLE_PTR,
437            eint13_cmd.data_buffer.as_bytes(),
438            bus_master_state,
439        )
440        .unwrap();
441
442        // Now that we know what the IDE command is, disambiguate between
443        // 28-bit LBA and 48-bit LBA
444        if cmd == IdeCommand::READ_DMA_EXT || cmd == IdeCommand::WRITE_DMA_EXT {
445            // 48-bit LBA, high 24 bits of logical block address
446            self.write_drive_register(
447                DriveRegister::LbaLow,
448                (eint13_cmd.lba_low >> 24) as u8,
449                bus_master_state,
450            );
451
452            self.write_drive_register(
453                DriveRegister::LbaMid,
454                eint13_cmd.lba_high as u8,
455                bus_master_state,
456            );
457
458            self.write_drive_register(
459                DriveRegister::LbaHigh,
460                (eint13_cmd.lba_high >> 8) as u8,
461                bus_master_state,
462            );
463
464            // 48-bit LBA, high 8 bits of sector count
465            // Write the low-byte of the sector count
466            self.write_drive_register(
467                DriveRegister::SectorCount,
468                (eint13_cmd.block_count >> 8) as u8,
469                bus_master_state,
470            );
471        }
472
473        // Write the low-byte of the sector count
474        self.write_drive_register(
475            DriveRegister::SectorCount,
476            eint13_cmd.block_count as u8,
477            bus_master_state,
478        );
479
480        // Finish writing the LBA low bytes to the FIFOs
481        self.write_drive_register(
482            DriveRegister::LbaLow,
483            eint13_cmd.lba_low as u8,
484            bus_master_state,
485        );
486        self.write_drive_register(
487            DriveRegister::LbaMid,
488            (eint13_cmd.lba_low >> 8) as u8,
489            bus_master_state,
490        );
491        self.write_drive_register(
492            DriveRegister::LbaHigh,
493            (eint13_cmd.lba_low >> 16) as u8,
494            bus_master_state,
495        );
496
497        // Make sure that the IDE channel will not cause an interrupt since this
498        // enlightened operation is intended to be 100% synchronous.
499        let old_adapter_control_reg = self.state.shadow_adapter_control_reg;
500        self.write_drive_register(
501            DriveRegister::AlternateStatusDeviceControl,
502            DeviceControlReg::new()
503                .with_interrupt_mask(true)
504                .into_bits(),
505            bus_master_state,
506        );
507
508        // Start the dma engine.
509        let mut bus_master_flags = BusMasterCommandReg::new().with_start(true);
510        if cmd == IdeCommand::READ_DMA_EXT
511            || cmd == IdeCommand::READ_DMA
512            || cmd == IdeCommand::READ_DMA_ALT
513        {
514            // set rw flag to 1 to inticate that bus master is performing a read
515            bus_master_flags.set_write(true);
516        }
517
518        self.write_bus_master_reg(
519            BusMasterReg::COMMAND,
520            &[bus_master_flags.into_bits() as u8],
521            bus_master_state,
522        )
523        .unwrap();
524
525        // Start the IDE command
526        self.write_drive_register(DriveRegister::StatusCmd, cmd.0, bus_master_state);
527
528        // Defer the write.
529        let (write, token) = defer_write();
530        self.enlightened_write = Some(EnlightenedWrite::Hard(EnlightenedHddWrite {
531            deferred: write,
532            old_adapter_control_reg,
533            guest_address,
534            drive_index: self.state.current_drive_idx,
535        }));
536
537        tracing::trace!(enlightened_write = ?self.enlightened_write, "enlightened_hdd_command");
538        if let Some(status) = self.current_drive_status() {
539            if status.drq() {
540                tracelimit::warn_ratelimited!(
541                    "command is waiting for data read from guest or data write to guest"
542                );
543                return IoResult::Ok;
544            }
545        }
546        IoResult::Defer(token)
547    }
548
549    fn enlightened_cd_command(
550        &mut self,
551        guest_address: u64,
552        eint13_cmd: protocol::EnlightenedInt13Command,
553        bus_master_state: &BusMasterState,
554    ) -> IoResult {
555        tracing::trace!(
556            guest_address,
557            command = ?eint13_cmd,
558            "enlightened cd command"
559        );
560
561        // Save the old Precompensation byte because we must NOT use traditional DMA
562        // with this command. Just read the bytes into the track cache so we can use
563        // WriteRamBytes to move them to the guest.
564        let old_features_reg = self.state.shadow_features_reg;
565        self.write_drive_register(DriveRegister::ErrorFeatures, 0, bus_master_state);
566
567        // Make sure that any code path through the IDE completion and error code does NOT
568        // generate an interrupt. This enlightenment is intended to operate completely
569        // synchronously.
570        let old_adapter_control_reg = self.state.shadow_adapter_control_reg;
571        self.write_drive_register(
572            DriveRegister::AlternateStatusDeviceControl,
573            DeviceControlReg::new()
574                .with_interrupt_mask(true)
575                .into_bits(),
576            bus_master_state,
577        );
578
579        // Start the Atapi packet command
580        self.write_drive_register(
581            DriveRegister::StatusCmd,
582            IdeCommand::PACKET_COMMAND.0,
583            bus_master_state,
584        );
585
586        // Construct the SCSI command packet in the single sector buffer that
587        // we're about to dispatch.
588        let cdb = scsi::Cdb10 {
589            operation_code: ScsiOp::READ,
590            flags: CdbFlags::new(),
591            logical_block: eint13_cmd.lba_low.into(),
592            reserved2: 0,
593            transfer_blocks: eint13_cmd.block_count.into(),
594            control: 0,
595        };
596
597        // Assume the device is configured for 12-byte commands.
598        let mut command = [0; 12];
599        command[..cdb.as_bytes().len()].copy_from_slice(cdb.as_bytes());
600
601        // Spawn the IO read which eventually puts the data into the track cache
602        // Wait synchronously for the command to complete reading the data into the track cache.
603        self.write_drive_data(command.as_bytes(), bus_master_state);
604
605        // Defer the write.
606        let (write, token) = defer_write();
607        self.enlightened_write = Some(EnlightenedWrite::Optical(EnlightenedCdWrite {
608            deferred: write,
609            old_adapter_control_reg,
610            guest_address,
611            old_features_reg,
612            data_buffer: eint13_cmd.data_buffer,
613            skip_bytes_head: eint13_cmd.skip_bytes_head,
614            byte_count: eint13_cmd.byte_count,
615            block_count: eint13_cmd.block_count,
616            drive_index: self.state.current_drive_idx,
617        }));
618
619        tracing::trace!(enlightened_write = ?self.enlightened_write, "enlightened_cd_command");
620        if let Some(status) = self.current_drive_status() {
621            if status.drq() {
622                tracelimit::warn_ratelimited!(
623                    "command is waiting for data read from guest or data write to guest"
624                );
625                return IoResult::Ok;
626            }
627        }
628        IoResult::Defer(token)
629    }
630
631    fn complete_enlightened_hdd_write(
632        &mut self,
633        write: EnlightenedHddWrite,
634        bus_master_state: &BusMasterState,
635    ) {
636        // Stop the dma engine (probably stopped already, but this mimics the BIOS
637        // code which this enlightenment replaces).
638        self.write_bus_master_reg(BusMasterReg::COMMAND, &[0], bus_master_state)
639            .unwrap();
640
641        // Clear the pending interrupt and read status.
642        let status = self.read_drive_register(DriveRegister::StatusCmd, bus_master_state);
643        let status = Status::from_bits(status);
644
645        if status.err() {
646            // If there was an error, copy back the status into the enlightened INT13 command in
647            // the guest so that the guest can check it.
648            if let Err(err) = self.guest_memory.write_at(
649                write.guest_address
650                    + offset_of!(protocol::EnlightenedInt13Command, result_status) as u64,
651                &[status.into_bits()],
652            ) {
653                tracelimit::error_ratelimited!(
654                    ?status,
655                    error = &err as &dyn std::error::Error,
656                    "failed to write eint13 status back"
657                );
658            }
659        }
660
661        // Possibly re-enable IDE channel interrupts for the next operation
662        self.write_drive_register(
663            DriveRegister::AlternateStatusDeviceControl,
664            write.old_adapter_control_reg,
665            bus_master_state,
666        );
667
668        write.deferred.complete();
669    }
670
671    fn complete_enlightened_cd_write(
672        &mut self,
673        write: EnlightenedCdWrite,
674        bus_master_state: &BusMasterState,
675    ) {
676        // Clear the pending interrupt and read status.
677        let status = self.read_drive_register(DriveRegister::StatusCmd, bus_master_state);
678        let status = Status::from_bits(status);
679
680        if status.err() {
681            // If there was an error, copy back the status into the enlightened INT13 command in
682            // the guest so that the guest can check it.
683            if let Err(err) = self.guest_memory.write_at(
684                write.guest_address
685                    + offset_of!(protocol::EnlightenedInt13Command, result_status) as u64,
686                &[status.into_bits()],
687            ) {
688                tracelimit::error_ratelimited!(
689                    ?status,
690                    error = &err as &dyn std::error::Error,
691                    "failed to write eint13 status back"
692                );
693            }
694        } else {
695            let mut remaining =
696                (write.block_count as u32 * protocol::CD_DRIVE_SECTOR_BYTES) as usize;
697
698            // Skip over the unused portion of the result.
699            let skip = (write.skip_bytes_head as usize).min(remaining);
700            remaining -= skip;
701            self.skip_drive_data(skip, bus_master_state);
702
703            // Read the requested part of the result.
704            let byte_count = (write.byte_count as usize).min(remaining);
705            remaining -= byte_count;
706
707            let mut copied = 0;
708            while copied < byte_count {
709                let mut buf = [0; 512];
710                let len = (byte_count - copied).min(buf.len());
711                let buf = &mut buf[..len];
712                self.read_drive_data(buf, bus_master_state);
713                if let Err(err) = self
714                    .guest_memory
715                    .write_at((write.data_buffer as u64).wrapping_add(copied as u64), buf)
716                {
717                    tracelimit::warn_ratelimited!(
718                        error = &err as &dyn std::error::Error,
719                        "failed to write enlightened result to guest memory"
720                    );
721                }
722                copied += buf.len();
723            }
724
725            // Read any remaining data to prepare the device for the next command.
726            self.skip_drive_data(remaining, bus_master_state);
727        }
728
729        // Restore the precompensation setting which existed prior to this read
730        self.write_drive_register(
731            DriveRegister::ErrorFeatures,
732            write.old_features_reg,
733            bus_master_state,
734        );
735
736        // Possibly re-enable IDE channel interrupts for the next operation
737        self.write_drive_register(
738            DriveRegister::AlternateStatusDeviceControl,
739            write.old_adapter_control_reg,
740            bus_master_state,
741        );
742
743        tracing::trace!("enlightened cd write completed");
744        write.deferred.complete();
745    }
746
747    fn perform_dma_memory_phase(&mut self) {
748        let Some(drive) = &mut self.drives[self.state.current_drive_idx] else {
749            return;
750        };
751
752        if self.bus_master_state.dma_error {
753            if drive.handle_read_dma_descriptor_error() {
754                self.bus_master_state.dma_error = false;
755            }
756            return;
757        }
758
759        let mut dma_avail = match drive.dma_request() {
760            Some((dma_type, avail)) if *dma_type == self.bus_master_state.dma_io_type() => {
761                avail as u32
762            }
763            _ => {
764                // No active, appropriate DMA buffer.
765                return;
766            }
767        };
768
769        let Some(dma) = &mut self.bus_master_state.dma_state else {
770            return;
771        };
772
773        while dma_avail > 0 {
774            // If the number of bytes left in the transfer is zero, we need to read the next Dma descriptor
775            if dma.transfer_bytes_left == 0 {
776                assert!(!dma.transfer_complete);
777
778                // The descriptor table pointer points to a table of Dma
779                // scatter/gather descriptors built by the operating system.
780                // This table tells us where the place the incoming data for
781                // reads or where to get the outgoing data for writes. The
782                // last valid table entry will have the high bit of the
783                // EndOfTable field set.
784                let descriptor_addr: u64 = self
785                    .bus_master_state
786                    .desc_table_ptr
787                    .wrapping_add(8 * (dma.descriptor_idx as u32))
788                    .into();
789
790                let cur_desc_table_entry = match self
791                    .guest_memory
792                    .read_plain::<protocol::BusMasterDmaDesc>(descriptor_addr)
793                {
794                    Ok(cur_desc_table_entry) => cur_desc_table_entry,
795                    Err(err) => {
796                        self.bus_master_state.dma_state = None;
797                        if !drive.handle_read_dma_descriptor_error() {
798                            self.bus_master_state.dma_error = true;
799                        }
800                        tracelimit::error_ratelimited!(
801                            error = &err as &dyn std::error::Error,
802                            "dma descriptor read error"
803                        );
804                        return;
805                    }
806                };
807
808                tracing::trace!(entry = ?cur_desc_table_entry, "read dma desc");
809
810                dma.transfer_bytes_left = cur_desc_table_entry.byte_count.into();
811                // A zero byte length implies 64Kb
812                if cur_desc_table_entry.byte_count == 0 {
813                    dma.transfer_bytes_left = 0x10000;
814                }
815
816                dma.transfer_base_addr = cur_desc_table_entry.mem_physical_base.into();
817                dma.transfer_complete = (cur_desc_table_entry.end_of_table & 0x80) != 0;
818
819                // Increment to the next descriptor.
820                dma.descriptor_idx += 1;
821                if dma.transfer_complete {
822                    dma.descriptor_idx = 0;
823                }
824            }
825
826            // Transfer byte count is limited by the transfer size and the number of bytes in our IDE buffer.
827            let bytes_to_transfer = dma_avail.min(dma.transfer_bytes_left);
828
829            assert!(bytes_to_transfer != 0);
830
831            if let Err(err) = drive.dma_transfer(
832                &self.guest_memory,
833                dma.transfer_base_addr,
834                bytes_to_transfer as usize,
835            ) {
836                // The guest pointed the DMA engine at memory it can't access.
837                // Stop the transfer and raise the bus master DMA error, just as
838                // real hardware would on a failed bus access.
839                self.bus_master_state.dma_state = None;
840                if !drive.handle_read_dma_descriptor_error() {
841                    self.bus_master_state.dma_error = true;
842                }
843                tracelimit::error_ratelimited!(
844                    error = &err as &dyn std::error::Error,
845                    "dma transfer memory access error"
846                );
847                return;
848            }
849
850            dma_avail -= bytes_to_transfer;
851            dma.transfer_base_addr += bytes_to_transfer as u64;
852            dma.transfer_bytes_left -= bytes_to_transfer;
853            if dma.transfer_bytes_left == 0 && dma.transfer_complete {
854                if dma_avail > 0 {
855                    // If descriptor table ended before buffer was exhausted, advance buffer to end to indicate completion of operation
856                    drive.set_prd_exhausted();
857                    drive.dma_advance_buffer(dma_avail as usize);
858                }
859                tracing::trace!("dma transfer is complete");
860                self.bus_master_state.dma_state = None;
861                break;
862            }
863        }
864    }
865}
866
867impl ChangeDeviceState for IdeDevice {
868    fn start(&mut self) {}
869
870    async fn stop(&mut self) {}
871
872    async fn reset(&mut self) {
873        self.bus_master_pio_dynamic.unmap();
874        self.bus_master_state = BusMasterState::new();
875        for channel in &mut self.channels {
876            channel.reset();
877        }
878    }
879}
880
881impl ChipsetDevice for IdeDevice {
882    fn supports_pio(&mut self) -> Option<&mut dyn PortIoIntercept> {
883        Some(self)
884    }
885
886    fn supports_pci(&mut self) -> Option<&mut dyn PciConfigSpace> {
887        Some(self)
888    }
889
890    fn supports_poll_device(&mut self) -> Option<&mut dyn PollDevice> {
891        Some(self)
892    }
893}
894
895impl PollDevice for IdeDevice {
896    fn poll_device(&mut self, cx: &mut Context<'_>) {
897        for channel in &mut self.channels {
898            channel.poll_device(cx, &self.bus_master_state);
899        }
900    }
901}
902
903impl PortIoIntercept for IdeDevice {
904    fn io_read(&mut self, io_port: u16, data: &mut [u8]) -> IoResult {
905        match self.parse_port(io_port) {
906            Some((port, index)) => match port {
907                Port::Data => {
908                    self.channels[index].read_drive_data(data, &self.bus_master_state);
909                    IoResult::Ok
910                }
911                Port::Drive(register) => {
912                    data[0] =
913                        self.channels[index].read_drive_register(register, &self.bus_master_state);
914                    IoResult::Ok
915                }
916                Port::Enlightened => IoResult::Err(IoError::InvalidRegister),
917                Port::BusMaster(offset) => self.channels[index].read_bus_master_reg(offset, data),
918            },
919            None => IoResult::Err(IoError::InvalidRegister),
920        }
921    }
922
923    fn io_write(&mut self, io_port: u16, data: &[u8]) -> IoResult {
924        match self.parse_port(io_port) {
925            Some((port, index)) => match port {
926                Port::Data => {
927                    self.channels[index].write_drive_data(data, &self.bus_master_state);
928                    IoResult::Ok
929                }
930                Port::Drive(register) => {
931                    self.channels[index].write_drive_register(
932                        register,
933                        data[0],
934                        &self.bus_master_state,
935                    );
936                    IoResult::Ok
937                }
938                Port::Enlightened => {
939                    self.channels[index].enlightened_port_write(data, &self.bus_master_state)
940                }
941                Port::BusMaster(offset) => {
942                    self.channels[index].write_bus_master_reg(offset, data, &self.bus_master_state)
943                }
944            },
945            None => IoResult::Err(IoError::InvalidRegister),
946        }
947    }
948
949    fn get_static_regions(&mut self) -> &[(&str, RangeInclusive<u16>)] {
950        &[
951            (
952                "ide primary channel",
953                IdeIoPort::PRI_ENLIGHTENED.0..=IdeIoPort::PRI_STATUS_CMD.0,
954            ),
955            (
956                "ide primary channel control",
957                IdeIoPort::PRI_ALT_STATUS_DEVICE_CTL.0..=IdeIoPort::PRI_ALT_STATUS_DEVICE_CTL.0,
958            ),
959            (
960                "ide secondary channel",
961                IdeIoPort::SEC_ENLIGHTENED.0..=IdeIoPort::SEC_STATUS_CMD.0,
962            ),
963            (
964                "ide secondary channel control",
965                IdeIoPort::SEC_ALT_STATUS_DEVICE_CTL.0..=IdeIoPort::SEC_ALT_STATUS_DEVICE_CTL.0,
966            ),
967        ]
968    }
969}
970
971impl PciConfigSpace for IdeDevice {
972    fn pci_cfg_read(&mut self, offset: u16, mut value: ByteEnabledDwordRead<'_>) -> IoResult {
973        value.set(if offset < HEADER_TYPE_00_SIZE {
974            match HeaderType00(offset) {
975                HeaderType00::DEVICE_VENDOR => protocol::BX_PCI_ISA_BRIDGE_IDE_IDREG_VALUE,
976                HeaderType00::STATUS_COMMAND => self.bus_master_state.cmd_status_reg,
977                HeaderType00::CLASS_REVISION => protocol::BX_PCI_IDE_CLASS_WORD,
978                HeaderType00::BAR4 => self.bus_master_state.port_addr_reg,
979                offset => {
980                    tracing::debug!(?offset, "undefined type00 header read");
981                    0
982                }
983            }
984        } else {
985            match IdeConfigSpace(offset) {
986                IdeConfigSpace::PRIMARY_TIMING_REG_ADDR => self.bus_master_state.timing_reg,
987                IdeConfigSpace::SECONDARY_TIMING_REG_ADDR => {
988                    self.bus_master_state.secondary_timing_reg
989                }
990                IdeConfigSpace::UDMA_CTL_REG_ADDR => self.bus_master_state.dma_ctl_reg,
991                IdeConfigSpace::MANUFACTURE_ID_REG_ADDR => {
992                    // This is a private versioning register, and no one is supposed to use it.
993                    // But a real Triton chipset returns this value...
994                    0x00000F30
995                }
996                offset => {
997                    // Allow reads from undefined areas.
998                    tracing::trace!(?offset, "undefined ide pci config space read");
999                    return IoResult::Err(IoError::InvalidRegister);
1000                }
1001            }
1002        });
1003
1004        tracing::trace!(?offset, ?value, "ide pci config space read");
1005        IoResult::Ok
1006    }
1007
1008    fn pci_cfg_write(&mut self, offset: u16, value: ByteEnabledDwordWrite) -> IoResult {
1009        if offset < HEADER_TYPE_00_SIZE {
1010            let offset = HeaderType00(offset);
1011            tracing::trace!(?offset, ?value, "ide pci config space write");
1012
1013            const BUS_MASTER_IO_ENABLE_MASK: u32 = Command::new()
1014                .with_pio_enabled(true)
1015                .with_bus_master(true)
1016                .into_bits() as u32;
1017
1018            match offset {
1019                HeaderType00::STATUS_COMMAND => {
1020                    // Several bits are used to reset status bits when written as 1s.
1021                    let value = value.merge(self.bus_master_state.cmd_status_reg);
1022                    self.bus_master_state.cmd_status_reg &= !(0x38000000 & value);
1023                    // Only allow writes to two bits (0 and 2). All other bits are read-only.
1024                    self.bus_master_state.cmd_status_reg &= !BUS_MASTER_IO_ENABLE_MASK;
1025
1026                    self.bus_master_state.cmd_status_reg |= value & BUS_MASTER_IO_ENABLE_MASK;
1027
1028                    // Is the io address space enabled for bus mastering and is bus mastering enabled?
1029                    if (self.bus_master_state.cmd_status_reg
1030                        & protocol::CFCS_BUS_MASTER_IO_ENABLE_MASK)
1031                        != protocol::CFCS_BUS_MASTER_IO_ENABLE_MASK
1032                    {
1033                        self.bus_master_pio_dynamic.unmap();
1034                        tracing::trace!("disabling bus master io range");
1035                    } else {
1036                        // Install the callbacks for the current bus primary I/O port range (which
1037                        // is dynamically configurable through PCI config registers)
1038                        let first_port = (self.bus_master_state.port_addr_reg as u16) & 0xFFF0;
1039                        tracing::trace!(?first_port, "enabling bus master range");
1040
1041                        // Change the io range for the bus master registers. Some of the bus master
1042                        // registers can be cached on writes.
1043                        self.bus_master_pio_dynamic.map(first_port);
1044                    }
1045                }
1046                HeaderType00::BAR4 => {
1047                    // Only allow writes to bits 4 to 15
1048                    let value = value.merge(self.bus_master_state.port_addr_reg);
1049                    self.bus_master_state.port_addr_reg =
1050                        (value & 0x0000FFF0) | DEFAULT_BUS_MASTER_PORT_ADDR_REG;
1051                }
1052                _ => tracing::debug!(?offset, "undefined type00 header write"),
1053            }
1054        } else {
1055            let offset = IdeConfigSpace(offset);
1056            tracing::trace!(?offset, ?value, "ide pci config space write");
1057
1058            match offset {
1059                IdeConfigSpace::PRIMARY_TIMING_REG_ADDR => {
1060                    value.merge_into(&mut self.bus_master_state.timing_reg)
1061                }
1062                IdeConfigSpace::SECONDARY_TIMING_REG_ADDR => {
1063                    value.merge_into(&mut self.bus_master_state.secondary_timing_reg)
1064                }
1065                IdeConfigSpace::UDMA_CTL_REG_ADDR => {
1066                    value.merge_into(&mut self.bus_master_state.dma_ctl_reg)
1067                }
1068                _ => tracing::trace!(?offset, "undefined ide pci config space write"),
1069            }
1070        }
1071
1072        IoResult::Ok
1073    }
1074
1075    fn suggested_bdf(&mut self) -> Option<(u8, u8, u8)> {
1076        Some((0, 7, 1)) // as per PIIX4 spec
1077    }
1078}
1079
1080/// IDE Channel
1081enum ChannelType {
1082    Primary,
1083    Secondary,
1084}
1085
1086#[derive(Inspect)]
1087#[inspect(tag = "drive_type")]
1088pub enum DriveMedia {
1089    HardDrive(#[inspect(rename = "backend")] Disk),
1090    OpticalDrive(#[inspect(rename = "backend")] Arc<dyn AsyncScsiDisk>),
1091}
1092
1093impl DriveMedia {
1094    pub fn hard_disk(disk: Disk) -> Self {
1095        DriveMedia::HardDrive(disk)
1096    }
1097
1098    pub fn optical_disk(scsi_disk: Arc<dyn AsyncScsiDisk>) -> Self {
1099        DriveMedia::OpticalDrive(scsi_disk)
1100    }
1101}
1102
1103#[derive(Debug, Default, Inspect)]
1104struct ChannelState {
1105    current_drive_idx: usize,
1106    shadow_adapter_control_reg: u8,
1107    shadow_features_reg: u8,
1108}
1109
1110#[derive(InspectMut)]
1111struct Channel {
1112    #[inspect(mut, with = "inspect_drives")]
1113    drives: [Option<DiskDrive>; 2],
1114    interrupt: LineInterrupt,
1115    state: ChannelState,
1116    bus_master_state: ChannelBusMasterState,
1117    enlightened_write: Option<EnlightenedWrite>,
1118    guest_memory: GuestMemory,
1119    #[inspect(skip)]
1120    channel: u8,
1121}
1122
1123fn inspect_drives(drives: &mut [Option<DiskDrive>]) -> impl '_ + InspectMut {
1124    inspect::adhoc_mut(|req| {
1125        let mut resp = req.respond();
1126        for (i, drive) in drives.iter_mut().enumerate() {
1127            resp.field_mut(&i.to_string(), drive);
1128        }
1129    })
1130}
1131
1132impl Channel {
1133    fn new(
1134        channel_drives: [Option<DriveMedia>; 2],
1135        channel_type: ChannelType,
1136        interrupt: LineInterrupt,
1137        guest_memory: GuestMemory,
1138    ) -> Result<Self, NewDeviceError> {
1139        let [primary_media, secondary_media] = channel_drives;
1140
1141        let channel_number = match channel_type {
1142            ChannelType::Primary => 0,
1143            ChannelType::Secondary => 1,
1144        };
1145
1146        Ok(Self {
1147            drives: [
1148                primary_media
1149                    .map(|media| {
1150                        DiskDrive::new(
1151                            media,
1152                            IdePath {
1153                                channel: channel_number,
1154                                drive: 0,
1155                            },
1156                        )
1157                    })
1158                    .transpose()?,
1159                secondary_media
1160                    .map(|media| {
1161                        DiskDrive::new(
1162                            media,
1163                            IdePath {
1164                                channel: channel_number,
1165                                drive: 1,
1166                            },
1167                        )
1168                    })
1169                    .transpose()?,
1170            ],
1171            interrupt,
1172            state: ChannelState::default(),
1173            bus_master_state: ChannelBusMasterState::default(),
1174            enlightened_write: None,
1175            guest_memory,
1176            channel: channel_number,
1177        })
1178    }
1179
1180    fn reset(&mut self) {
1181        tracelimit::info_ratelimited!(channel = self.channel, "channel reset");
1182        self.interrupt.set_level(false);
1183        self.state = ChannelState::default();
1184        self.bus_master_state = ChannelBusMasterState::default();
1185        for drive in self.drives.iter_mut().flatten() {
1186            drive.reset();
1187        }
1188    }
1189
1190    fn poll_device(&mut self, cx: &mut Context<'_>, bus_master_state: &BusMasterState) {
1191        for drive in self.drives.iter_mut().flatten() {
1192            drive.poll_device(cx);
1193        }
1194        self.post_drive_access(bus_master_state);
1195    }
1196
1197    fn current_drive_status(&mut self) -> Option<Status> {
1198        if let Some(drive) = &mut self.drives[self.state.current_drive_idx] {
1199            let status = drive.read_register(DriveRegister::AlternateStatusDeviceControl);
1200            Some(Status::from_bits(status))
1201        } else {
1202            None
1203        }
1204    }
1205
1206    fn drive_status(&mut self, drive_index: usize) -> Status {
1207        // Reading the values from Status register without clearing any bits
1208        assert!(self.drives[drive_index].is_some());
1209        let status = self.drives[drive_index]
1210            .as_mut()
1211            .unwrap()
1212            .read_register(DriveRegister::AlternateStatusDeviceControl);
1213        Status::from_bits(status)
1214    }
1215
1216    fn current_drive_type(&self) -> Option<DriveType> {
1217        self.drives[self.state.current_drive_idx]
1218            .as_ref()
1219            .map(|drive| drive.drive_type())
1220    }
1221
1222    fn drive_type(&mut self, drive_index: usize) -> DriveType {
1223        assert!(self.drives[drive_index].is_some());
1224        self.drives[drive_index]
1225            .as_ref()
1226            .map(|drive| drive.drive_type())
1227            .unwrap()
1228    }
1229
1230    fn post_drive_access(&mut self, bus_master_state: &BusMasterState) {
1231        // DMA first, since this may affect the other operations.
1232        self.perform_dma_memory_phase();
1233
1234        // Enlightened writes.
1235        if let Some(enlightened_write) = &self.enlightened_write {
1236            let drive_index = match enlightened_write {
1237                EnlightenedWrite::Hard(enlightened_hdd_write) => enlightened_hdd_write.drive_index,
1238                EnlightenedWrite::Optical(enlightened_cd_write) => enlightened_cd_write.drive_index,
1239            };
1240
1241            let status = self.drive_status(drive_index);
1242            let completed = match self.drive_type(drive_index) {
1243                DriveType::Hard => !(status.bsy() || status.drq()),
1244                DriveType::Optical => status.drdy(),
1245            };
1246            if completed {
1247                // The command is done.
1248                let write = self.enlightened_write.take().unwrap();
1249                match write {
1250                    EnlightenedWrite::Hard(write) => {
1251                        self.complete_enlightened_hdd_write(write, bus_master_state)
1252                    }
1253                    EnlightenedWrite::Optical(write) => {
1254                        self.complete_enlightened_cd_write(write, bus_master_state)
1255                    }
1256                }
1257            }
1258        }
1259
1260        // Update interrupt state.
1261        let interrupt = self
1262            .drives
1263            .iter()
1264            .flatten()
1265            .any(|drive| drive.interrupt_pending());
1266        if interrupt {
1267            tracing::trace!(channel = self.channel, interrupt, "post_drive_access");
1268            self.bus_master_state.status_reg.set_interrupt(true);
1269        }
1270        self.interrupt.set_level(interrupt);
1271    }
1272
1273    /// Returns Ok(true) if an interrupt should be delivered. The whole result
1274    /// of this should be passed to `io_port_completion`
1275    fn read_drive_register(
1276        &mut self,
1277        port: DriveRegister,
1278        bus_master_state: &BusMasterState,
1279    ) -> u8 {
1280        // Call the selected drive, but fall back to drive 0 if drive 1 is not present.
1281        let mut drive = self.drives[self.state.current_drive_idx].as_mut();
1282        if drive.is_none() {
1283            drive = self.drives[0].as_mut();
1284        }
1285
1286        let data = if let Some(drive) = drive {
1287            // Fill with zeroes if the drive doesn't write it (which can happen for some registers if
1288            // the device is not selected).
1289            drive.read_register(port)
1290        } else {
1291            // Returns 0x7f if neither device is present. This is align with ATA-5 "Devices shall not have a pull-up resistor on DD7"
1292            // Note: Legacy implementation returns 0xff in this case.
1293            0x7f
1294        };
1295
1296        tracing::trace!(?port, ?data, channel = self.channel, "io port read");
1297        self.post_drive_access(bus_master_state);
1298        data
1299    }
1300
1301    /// Returns Ok(true) if an interrupt should be delivered. The whole result
1302    /// of this should be passed to `io_port_completion` except in the case of
1303    /// the enlightened port path.
1304    fn write_drive_register(
1305        &mut self,
1306        port: DriveRegister,
1307        data: u8,
1308        bus_master_state: &BusMasterState,
1309    ) {
1310        tracing::trace!(?port, ?data, channel = self.channel, "io port write");
1311
1312        match port {
1313            DriveRegister::DeviceHead => {
1314                // Shadow the device bit for use in the DMA engine.
1315                self.state.current_drive_idx = ((data >> 4) & 1) as usize;
1316            }
1317            DriveRegister::AlternateStatusDeviceControl => {
1318                // Save this for restoring in the enlightened path.
1319                self.state.shadow_adapter_control_reg = data;
1320                let v = DeviceControlReg::from_bits_truncate(data);
1321                if v.reset() && (self.drives[0].is_some() || self.drives[1].is_some()) {
1322                    self.state = ChannelState::default();
1323                }
1324            }
1325            DriveRegister::ErrorFeatures => {
1326                // Save this for restoring in the enlightened path.
1327                self.state.shadow_features_reg = data;
1328            }
1329            _ => {}
1330        }
1331
1332        // Call both drives.
1333        if let Some(drive) = &mut self.drives[1] {
1334            drive.write_register(port, data);
1335        }
1336        if let Some(drive) = &mut self.drives[0] {
1337            drive.write_register(port, data);
1338        }
1339
1340        self.post_drive_access(bus_master_state);
1341    }
1342
1343    fn read_drive_data(&mut self, data: &mut [u8], bus_master_state: &BusMasterState) {
1344        // Call the selected drive, but fall back to drive 0 if drive 1 is not present.
1345        let mut drive = self.drives[self.state.current_drive_idx].as_mut();
1346        if drive.is_none() {
1347            drive = self.drives[0].as_mut();
1348        }
1349
1350        data.fill(0xff);
1351        // DD7 must be low to conform to the ATA spec.
1352        data[0] = 0x7f;
1353
1354        if let Some(drive) = drive {
1355            drive.pio_read(data);
1356        };
1357
1358        self.post_drive_access(bus_master_state);
1359    }
1360
1361    fn skip_drive_data(&mut self, mut len: usize, bus_master_state: &BusMasterState) {
1362        let mut buf = [0; 512];
1363        while len > 0 {
1364            let this_len = len.min(buf.len());
1365            let buf = &mut buf[..this_len];
1366            self.read_drive_data(buf, bus_master_state);
1367            len -= buf.len();
1368        }
1369    }
1370
1371    fn write_drive_data(&mut self, data: &[u8], bus_master_state: &BusMasterState) {
1372        if let Some(drive) = &mut self.drives[0] {
1373            drive.pio_write(data);
1374        }
1375        if let Some(drive) = &mut self.drives[1] {
1376            drive.pio_write(data);
1377        }
1378        self.post_drive_access(bus_master_state);
1379    }
1380
1381    fn read_bus_master_reg(&mut self, bus_master_reg: BusMasterReg, data: &mut [u8]) -> IoResult {
1382        let data_len = data.len();
1383        match bus_master_reg {
1384            BusMasterReg::COMMAND => match data_len {
1385                1 | 2 => data.copy_from_slice(
1386                    &self.bus_master_state.command_reg.into_bits().to_ne_bytes()[..data_len],
1387                ),
1388                _ => return IoResult::Err(IoError::InvalidAccessSize),
1389            },
1390            BusMasterReg::STATUS => {
1391                let mut status = self.bus_master_state.status_reg;
1392
1393                if self.bus_master_state.dma_state.is_some() {
1394                    status.set_active(true);
1395                }
1396
1397                match data_len {
1398                    1 | 2 => data.copy_from_slice(&status.into_bits().to_ne_bytes()[..data_len]),
1399                    _ => return IoResult::Err(IoError::InvalidAccessSize),
1400                }
1401            }
1402            BusMasterReg::TABLE_PTR => match data_len {
1403                2 | 4 => data.copy_from_slice(
1404                    &self.bus_master_state.desc_table_ptr.to_ne_bytes()[..data_len],
1405                ),
1406                _ => return IoResult::Err(IoError::InvalidAccessSize),
1407            },
1408            BusMasterReg::TABLE_PTR2 => {
1409                if data_len == 2 {
1410                    data.copy_from_slice(&self.bus_master_state.desc_table_ptr.to_ne_bytes()[2..4]);
1411                } else {
1412                    return IoResult::Err(IoError::InvalidAccessSize);
1413                }
1414            }
1415            _ => return IoResult::Err(IoError::InvalidRegister),
1416        }
1417
1418        tracing::trace!(?bus_master_reg, ?data, "bus master register read");
1419        IoResult::Ok
1420    }
1421
1422    fn write_bus_master_reg(
1423        &mut self,
1424        bus_master_reg: BusMasterReg,
1425        data: &[u8],
1426        bus_master_state: &BusMasterState,
1427    ) -> IoResult {
1428        let value: u64 = match data.len() {
1429            1 => u8::from_ne_bytes(data.as_bytes().try_into().unwrap()).into(),
1430            2 => u16::from_ne_bytes(data.as_bytes().try_into().unwrap()).into(),
1431            4 => u32::from_ne_bytes(data.as_bytes().try_into().unwrap()).into(),
1432            _ => return IoResult::Err(IoError::InvalidAccessSize),
1433        };
1434
1435        tracing::trace!(?bus_master_reg, value, "bus master register write");
1436
1437        match bus_master_reg {
1438            BusMasterReg::COMMAND => {
1439                // A write to this register will begin/end a dma transfer
1440                // and control its direction (write vs. read).
1441                if data.len() > 2 {
1442                    return IoResult::Err(IoError::InvalidAccessSize);
1443                }
1444
1445                let old_value = self.bus_master_state.command_reg;
1446                // TODO: make sure all bits that should be preserved are defined.
1447                let mut new_value = BusMasterCommandReg::from_bits_truncate(value as u32);
1448
1449                // The read/write bit is marked as read-only when dma is active.
1450                if old_value.start() {
1451                    // Set the new value of the read/write flag to match the
1452                    // existing value, regardless of the new value of the flag.
1453                    new_value.set_write(old_value.write());
1454                    if !new_value.start() {
1455                        self.bus_master_state.dma_state = None
1456                    }
1457                } else if new_value.start() {
1458                    self.bus_master_state.dma_state = Some(Default::default());
1459                };
1460
1461                self.bus_master_state.command_reg = new_value;
1462            }
1463            BusMasterReg::STATUS => {
1464                if data.len() > 2 {
1465                    return IoResult::Err(IoError::InvalidAccessSize);
1466                }
1467
1468                let value = BusMasterStatusReg::from_bits_truncate(value as u32);
1469                let old_value = self.bus_master_state.status_reg;
1470                let mut new_value = old_value.with_settable(value.settable());
1471
1472                // These bits are reset if a one is written
1473                if value.interrupt() {
1474                    new_value.set_interrupt(false);
1475                }
1476                if value.dma_error() {
1477                    new_value.set_dma_error(false);
1478                }
1479
1480                tracing::trace!(?old_value, ?new_value, "set bus master status");
1481                self.bus_master_state.status_reg = new_value;
1482            }
1483            BusMasterReg::TABLE_PTR => {
1484                if data.len() < 2 {
1485                    return IoResult::Err(IoError::InvalidAccessSize);
1486                }
1487
1488                if data.len() == 4 {
1489                    // Writing the whole 32-bits pointer with the lowest 2 bits zeroed-out.
1490                    self.bus_master_state.desc_table_ptr = value as u32 & 0xffff_fffc;
1491                } else {
1492                    // Writing the low 16-bits of the 32-bits pointer, with the
1493                    // lowest 2 bits zeroed-out
1494                    self.bus_master_state.desc_table_ptr = (self.bus_master_state.desc_table_ptr
1495                        & 0xffff_0000)
1496                        | (value as u32 & 0x0000_fffc);
1497                }
1498            }
1499            BusMasterReg::TABLE_PTR2 => {
1500                // Documentation doesn't mention this offset. Apparently OS/2 writes to this port.
1501                // Port not written to in recent Windows boot.
1502                self.bus_master_state.desc_table_ptr = (self.bus_master_state.desc_table_ptr
1503                    & 0xffff)
1504                    | ((value as u32 & 0xffff) << 16);
1505            }
1506            _ => return IoResult::Err(IoError::InvalidRegister),
1507        }
1508
1509        self.post_drive_access(bus_master_state);
1510        IoResult::Ok
1511    }
1512}
1513
1514#[derive(Debug, Copy, Clone, PartialEq)]
1515enum DriveType {
1516    Hard,
1517    Optical,
1518}
1519
1520#[derive(Debug, Default, Inspect)]
1521struct DmaState {
1522    descriptor_idx: u8,
1523    transfer_complete: bool,
1524    transfer_bytes_left: u32,
1525    transfer_base_addr: u64,
1526}
1527
1528mod save_restore {
1529    use super::*;
1530    use vmcore::save_restore::RestoreError;
1531    use vmcore::save_restore::SaveError;
1532    use vmcore::save_restore::SaveRestore;
1533
1534    mod state {
1535        use crate::drive::save_restore::state::SavedDriveState;
1536        use mesh::payload::Protobuf;
1537        use vmcore::save_restore::SavedStateRoot;
1538
1539        #[derive(Protobuf)]
1540        #[mesh(package = "storage.ide.controller")]
1541        pub struct SavedBusMasterState {
1542            #[mesh(1)]
1543            pub cmd_status_reg: u32,
1544            #[mesh(2)]
1545            pub port_addr_reg: u32,
1546            #[mesh(3)]
1547            pub timing_reg: u32,
1548            #[mesh(4)]
1549            pub secondary_timing_reg: u32,
1550            #[mesh(5)]
1551            pub dma_ctl_reg: u32,
1552        }
1553
1554        #[derive(Protobuf, SavedStateRoot)]
1555        #[mesh(package = "storage.ide.controller")]
1556        pub struct SavedState {
1557            #[mesh(1)]
1558            pub bus_master: SavedBusMasterState,
1559            #[mesh(2)]
1560            pub channel0: SavedChannelState,
1561            #[mesh(3)]
1562            pub channel1: SavedChannelState,
1563        }
1564
1565        #[derive(Protobuf)]
1566        #[mesh(package = "storage.ide.controller")]
1567        pub struct SavedDmaState {
1568            #[mesh(1)]
1569            pub descriptor_idx: u8,
1570            #[mesh(2)]
1571            pub transfer_complete: bool,
1572            #[mesh(3)]
1573            pub transfer_bytes_left: u32,
1574            #[mesh(4)]
1575            pub transfer_base_addr: u64,
1576        }
1577
1578        #[derive(Protobuf)]
1579        #[mesh(package = "storage.ide.controller")]
1580        pub struct SavedChannelBusMasterState {
1581            #[mesh(1)]
1582            pub command_reg: u32,
1583            #[mesh(2)]
1584            pub status_reg: u32,
1585            #[mesh(3)]
1586            pub desc_table_ptr: u32,
1587            #[mesh(4)]
1588            pub dma_state: Option<SavedDmaState>,
1589            #[mesh(5)]
1590            pub dma_error: bool,
1591        }
1592
1593        #[derive(Protobuf)]
1594        #[mesh(package = "storage.ide.controller")]
1595        pub struct SavedChannelState {
1596            #[mesh(1)]
1597            pub current_drive_idx: u8,
1598            #[mesh(2)]
1599            pub shadow_adapter_control_reg: u8,
1600            #[mesh(3)]
1601            pub shadow_features_reg: u8,
1602            #[mesh(4)]
1603            pub bus_master: SavedChannelBusMasterState,
1604            #[mesh(5)]
1605            pub drive0: Option<SavedDriveState>,
1606            #[mesh(6)]
1607            pub drive1: Option<SavedDriveState>,
1608        }
1609    }
1610
1611    impl SaveRestore for IdeDevice {
1612        type SavedState = state::SavedState;
1613
1614        fn save(&mut self) -> Result<Self::SavedState, SaveError> {
1615            let BusMasterState {
1616                cmd_status_reg,
1617                port_addr_reg,
1618                timing_reg,
1619                secondary_timing_reg,
1620                dma_ctl_reg,
1621            } = self.bus_master_state;
1622
1623            let bus_master = state::SavedBusMasterState {
1624                cmd_status_reg,
1625                port_addr_reg,
1626                timing_reg,
1627                secondary_timing_reg,
1628                dma_ctl_reg,
1629            };
1630
1631            let saved_state = state::SavedState {
1632                bus_master,
1633                channel0: self.channels[0].save()?,
1634                channel1: self.channels[1].save()?,
1635            };
1636
1637            Ok(saved_state)
1638        }
1639
1640        fn restore(&mut self, state: Self::SavedState) -> Result<(), RestoreError> {
1641            let state::SavedState {
1642                bus_master:
1643                    state::SavedBusMasterState {
1644                        cmd_status_reg,
1645                        port_addr_reg,
1646                        timing_reg,
1647                        secondary_timing_reg,
1648                        dma_ctl_reg,
1649                    },
1650                channel0,
1651                channel1,
1652            } = state;
1653
1654            self.bus_master_state = BusMasterState {
1655                cmd_status_reg,
1656                port_addr_reg,
1657                timing_reg,
1658                secondary_timing_reg,
1659                dma_ctl_reg,
1660            };
1661
1662            self.channels[0].restore(channel0)?;
1663            self.channels[1].restore(channel1)?;
1664
1665            Ok(())
1666        }
1667    }
1668
1669    #[derive(Debug, Error)]
1670    enum ChannelRestoreError {
1671        #[error("missing drive for state")]
1672        MissingDriveForState,
1673        #[error("missing state for drive")]
1674        MissingStateForDrive,
1675    }
1676
1677    impl Channel {
1678        fn save(&mut self) -> Result<state::SavedChannelState, SaveError> {
1679            // We wait for the completion of deferred IOs as part of pause.
1680            assert!(self.enlightened_write.is_none());
1681
1682            let ChannelState {
1683                current_drive_idx,
1684                shadow_adapter_control_reg,
1685                shadow_features_reg,
1686            } = self.state;
1687
1688            let ChannelBusMasterState {
1689                command_reg,
1690                status_reg,
1691                desc_table_ptr,
1692                dma_state,
1693                dma_error,
1694            } = &self.bus_master_state;
1695
1696            let saved_state = state::SavedChannelState {
1697                current_drive_idx: current_drive_idx as u8,
1698                shadow_adapter_control_reg,
1699                shadow_features_reg,
1700                bus_master: state::SavedChannelBusMasterState {
1701                    command_reg: command_reg.into_bits(),
1702                    status_reg: status_reg.into_bits(),
1703                    desc_table_ptr: *desc_table_ptr,
1704                    dma_state: dma_state.as_ref().map(|dma| {
1705                        let DmaState {
1706                            descriptor_idx,
1707                            transfer_complete,
1708                            transfer_bytes_left,
1709                            transfer_base_addr,
1710                        } = dma;
1711
1712                        state::SavedDmaState {
1713                            descriptor_idx: *descriptor_idx,
1714                            transfer_complete: *transfer_complete,
1715                            transfer_bytes_left: *transfer_bytes_left,
1716                            transfer_base_addr: *transfer_base_addr,
1717                        }
1718                    }),
1719                    dma_error: *dma_error,
1720                },
1721                drive0: self.drives[0]
1722                    .as_mut()
1723                    .map(|drive| drive.save())
1724                    .transpose()?,
1725                drive1: self.drives[1]
1726                    .as_mut()
1727                    .map(|drive| drive.save())
1728                    .transpose()?,
1729            };
1730
1731            Ok(saved_state)
1732        }
1733
1734        fn restore(&mut self, state: state::SavedChannelState) -> Result<(), RestoreError> {
1735            let state::SavedChannelState {
1736                current_drive_idx,
1737                shadow_adapter_control_reg,
1738                shadow_features_reg,
1739                bus_master:
1740                    state::SavedChannelBusMasterState {
1741                        command_reg,
1742                        status_reg,
1743                        desc_table_ptr,
1744                        dma_state,
1745                        dma_error,
1746                    },
1747                drive0,
1748                drive1,
1749            } = state;
1750
1751            self.state = ChannelState {
1752                current_drive_idx: current_drive_idx as usize,
1753                shadow_adapter_control_reg,
1754                shadow_features_reg,
1755            };
1756
1757            self.bus_master_state = ChannelBusMasterState {
1758                command_reg: BusMasterCommandReg::from_bits(command_reg),
1759                status_reg: BusMasterStatusReg::from_bits(status_reg),
1760                desc_table_ptr,
1761                dma_state: dma_state.map(|dma| {
1762                    let state::SavedDmaState {
1763                        descriptor_idx,
1764                        transfer_complete,
1765                        transfer_bytes_left,
1766                        transfer_base_addr,
1767                    } = dma;
1768
1769                    DmaState {
1770                        descriptor_idx,
1771                        transfer_complete,
1772                        transfer_bytes_left,
1773                        transfer_base_addr,
1774                    }
1775                }),
1776                dma_error,
1777            };
1778
1779            for (drive, state) in self.drives.iter_mut().zip([drive0, drive1]) {
1780                match (drive, state) {
1781                    (Some(drive), Some(state)) => drive.restore(state)?,
1782                    (None, None) => {}
1783                    (Some(_), None) => {
1784                        return Err(RestoreError::InvalidSavedState(
1785                            ChannelRestoreError::MissingStateForDrive.into(),
1786                        ));
1787                    }
1788                    (None, Some(_)) => {
1789                        return Err(RestoreError::InvalidSavedState(
1790                            ChannelRestoreError::MissingDriveForState.into(),
1791                        ));
1792                    }
1793                }
1794            }
1795
1796            Ok(())
1797        }
1798    }
1799}
1800
1801#[cfg(test)]
1802mod tests {
1803    use super::*;
1804    use crate::IdeIoPort;
1805    use crate::protocol::BusMasterDmaDesc;
1806    use crate::protocol::DeviceHeadReg;
1807    use crate::protocol::IdeCommand;
1808    use chipset_device::pio::ExternallyManagedPortIoIntercepts;
1809    use disk_file::FileDisk;
1810    use pal_async::async_test;
1811    use scsidisk::atapi_scsi::AtapiScsiDisk;
1812    use scsidisk::scsidvd::SimpleScsiDvd;
1813    use std::fs::File;
1814    use std::future::poll_fn;
1815    use std::io::Read;
1816    use std::io::Write;
1817    use std::task::Poll;
1818    use tempfile::NamedTempFile;
1819    use test_with_tracing::test;
1820    use zerocopy::FromBytes;
1821    use zerocopy::FromZeros;
1822    use zerocopy::IntoBytes;
1823
1824    #[derive(Debug, Inspect)]
1825    struct MediaGeometry {
1826        sectors_per_track: u32,
1827        cylinder_count: u32,
1828        head_count: u32,
1829        total_sectors: u64,
1830    }
1831
1832    impl MediaGeometry {
1833        fn new(total_sectors: u64, sector_size: u32) -> Result<Self, NewDeviceError> {
1834            if total_sectors > protocol::MAX_BYTES_48BIT_LBA / sector_size as u64 {
1835                return Err(NewDeviceError::DiskTooLarge(
1836                    total_sectors * sector_size as u64,
1837                ));
1838            }
1839            let hard_drive_sectors = total_sectors.min(protocol::MAX_CHS_SECTORS as u64);
1840            let mut sectors_per_track;
1841            let mut cylinders_times_heads;
1842            let mut head_count;
1843
1844            if hard_drive_sectors > (16 * 63 * 0xFFFF) {
1845                sectors_per_track = 255;
1846                head_count = 16;
1847                cylinders_times_heads = hard_drive_sectors / (sectors_per_track as u64);
1848            } else {
1849                sectors_per_track = 17;
1850                cylinders_times_heads = hard_drive_sectors / (sectors_per_track as u64);
1851
1852                head_count = std::cmp::max((cylinders_times_heads as u32).div_ceil(1024), 4);
1853
1854                if (cylinders_times_heads >= (head_count as u64) * 1024) || head_count > 16 {
1855                    // Always use 16 heads
1856                    head_count = 16;
1857                    sectors_per_track = 31;
1858                    cylinders_times_heads = hard_drive_sectors / (sectors_per_track as u64);
1859                }
1860
1861                if cylinders_times_heads >= (head_count as u64) * 1024 {
1862                    // Always use 16 heads
1863                    head_count = 16;
1864                    sectors_per_track = 63;
1865                    cylinders_times_heads = hard_drive_sectors / (sectors_per_track as u64);
1866                }
1867            }
1868            Ok(MediaGeometry {
1869                sectors_per_track,
1870                cylinder_count: (cylinders_times_heads / (head_count as u64)) as u32,
1871                head_count,
1872                total_sectors,
1873            })
1874        }
1875    }
1876
1877    struct CommandParams {
1878        sector_count: u8,
1879        sector_num: u8,
1880        cylinder_lsb: u8,
1881        cylinder_msb: u8,
1882        device_head: u8,
1883    }
1884
1885    #[expect(dead_code)]
1886    enum Addressing {
1887        Chs,
1888        Lba28Bit,
1889        Lba48Bit,
1890    }
1891
1892    fn ide_test_setup(
1893        guest_memory: Option<GuestMemory>,
1894        drive_type: DriveType,
1895    ) -> (IdeDevice, File, Vec<u32>, MediaGeometry) {
1896        let test_guest_mem = match guest_memory {
1897            Some(test_gm) => test_gm,
1898            None => GuestMemory::allocate(16 * 1024),
1899        };
1900
1901        // prep file (write 4GB, numbers 1-1048576 (1GB))
1902        let temp_file = NamedTempFile::new().unwrap();
1903        let mut handle1 = temp_file.reopen().unwrap();
1904        let handle2 = temp_file.reopen().unwrap();
1905        let data = (0..0x100000_u32).collect::<Vec<_>>();
1906        handle1.write_all(data.as_bytes()).unwrap();
1907
1908        let disk = Disk::new(FileDisk::open(handle1, false).unwrap()).unwrap();
1909        let geometry = MediaGeometry::new(disk.sector_count(), disk.sector_size()).unwrap();
1910
1911        let media = match drive_type {
1912            DriveType::Hard => DriveMedia::hard_disk(disk),
1913            DriveType::Optical => DriveMedia::optical_disk(Arc::new(AtapiScsiDisk::new(Arc::new(
1914                SimpleScsiDvd::new(Some(disk)),
1915            )))),
1916        };
1917
1918        let ide_device = IdeDevice::new(
1919            test_guest_mem,
1920            &mut ExternallyManagedPortIoIntercepts,
1921            [Some(media), None],
1922            [None, None],
1923            LineInterrupt::detached(),
1924            LineInterrupt::detached(),
1925        )
1926        .unwrap();
1927
1928        (ide_device, handle2, data, geometry)
1929    }
1930
1931    // IDE Test Host protocol functions
1932    fn get_status(ide_controller: &mut IdeDevice, dev_path: &IdePath) -> Status {
1933        let mut data = [0_u8; 1];
1934        ide_controller
1935            .io_read(
1936                io_port(IdeIoPort::PRI_STATUS_CMD, dev_path.channel.into()),
1937                &mut data,
1938            )
1939            .unwrap();
1940
1941        Status::from_bits(data[0])
1942    }
1943
1944    async fn check_status_loop(ide_device: &mut IdeDevice, dev_path: &IdePath) -> Status {
1945        // loop until device is not busy and is ready to transfer data.
1946        wait_for(ide_device, |ide_device| {
1947            let status: Status = get_status(ide_device, dev_path);
1948            (!status.bsy() && !status.drq()).then_some(status)
1949        })
1950        .await
1951    }
1952
1953    async fn check_command_ready(ide_device: &mut IdeDevice, dev_path: &IdePath) -> Status {
1954        // loop until device is not busy and is ready to transfer data.
1955        wait_for(ide_device, |ide_device| {
1956            let status: Status = get_status(ide_device, dev_path);
1957            (!status.bsy() && status.drdy()).then_some(status)
1958        })
1959        .await
1960    }
1961
1962    fn io_port(io_port: IdeIoPort, channel_idx: usize) -> u16 {
1963        if channel_idx == 0 {
1964            io_port.0
1965        } else {
1966            io_port.0 - IdeIoPort::PRI_DATA.0 + IdeIoPort::SEC_DATA.0
1967        }
1968    }
1969
1970    // Host: setup command parameters by writing to features, sector count/number,
1971    // cylinder low/high, dev/head registers
1972    fn write_command_params(
1973        controller: &mut IdeDevice,
1974        dev_path: &IdePath,
1975        sector: u32,
1976        sector_count: u8,
1977        addr: Addressing,
1978        geometry: &MediaGeometry,
1979    ) {
1980        let channel_idx: usize = dev_path.channel as usize;
1981
1982        let io_params = match addr {
1983            Addressing::Chs => {
1984                let sectors_per_track = geometry.sectors_per_track;
1985                let head_count = geometry.head_count;
1986
1987                let sector_num: u8 = ((sector % sectors_per_track) as u8) + 1;
1988                let cylinders: u16 = (sector / (head_count * sectors_per_track)) as u16;
1989                let cylinder_lsb: u8 = cylinders as u8;
1990                let cylinder_msb: u8 = (cylinders >> 8) as u8;
1991                let device_head: u8 = (sector / sectors_per_track % head_count) as u8;
1992
1993                CommandParams {
1994                    sector_count,
1995                    sector_num,
1996                    cylinder_lsb,
1997                    cylinder_msb,
1998                    device_head,
1999                }
2000            }
2001            Addressing::Lba28Bit => {
2002                let sector_num = sector as u8;
2003                let cylinder = (sector & 0x00FF_FF00) >> 8;
2004                let cylinder_lsb: u8 = cylinder as u8;
2005                let cylinder_msb: u8 = (cylinder >> 8) as u8;
2006                let device_head = DeviceHeadReg::new()
2007                    .with_head((sector >> 24) as u8)
2008                    .with_lba(true)
2009                    .into();
2010
2011                CommandParams {
2012                    sector_count,
2013                    sector_num,
2014                    cylinder_lsb,
2015                    cylinder_msb,
2016                    device_head,
2017                }
2018            }
2019            Addressing::Lba48Bit => todo!(),
2020        };
2021
2022        controller
2023            .io_write(
2024                io_port(IdeIoPort::PRI_SECTOR_COUNT, channel_idx),
2025                &[io_params.sector_count],
2026            )
2027            .unwrap();
2028        controller
2029            .io_write(
2030                io_port(IdeIoPort::PRI_SECTOR_NUM, channel_idx),
2031                &[io_params.sector_num],
2032            )
2033            .unwrap();
2034        controller
2035            .io_write(
2036                io_port(IdeIoPort::PRI_CYLINDER_LSB, channel_idx),
2037                &[io_params.cylinder_lsb],
2038            )
2039            .unwrap();
2040        controller
2041            .io_write(
2042                io_port(IdeIoPort::PRI_CYLINDER_MSB, channel_idx),
2043                &[io_params.cylinder_msb],
2044            )
2045            .unwrap();
2046        controller
2047            .io_write(
2048                io_port(IdeIoPort::PRI_DEVICE_HEAD, channel_idx),
2049                &[io_params.device_head],
2050            )
2051            .unwrap();
2052    }
2053
2054    // Host: Execute device selection protocol
2055    async fn device_select(ide_controller: &mut IdeDevice, dev_path: &IdePath) {
2056        check_status_loop(ide_controller, dev_path).await;
2057
2058        let dev_idx: u8 = dev_path.drive;
2059        ide_controller
2060            .io_write(
2061                io_port(IdeIoPort::PRI_DEVICE_HEAD, dev_path.channel.into()),
2062                &[dev_idx],
2063            )
2064            .unwrap();
2065
2066        check_status_loop(ide_controller, dev_path).await;
2067    }
2068
2069    // Host: Write command code to command register, wait 400ns before reading status register
2070    fn execute_command(ide_controller: &mut IdeDevice, dev_path: &IdePath, command: u8) {
2071        ide_controller
2072            .io_write(
2073                io_port(IdeIoPort::PRI_STATUS_CMD, dev_path.channel.into()),
2074                &[command],
2075            )
2076            .unwrap();
2077    }
2078
2079    fn execute_soft_reset_command(ide_controller: &mut IdeDevice, dev_path: &IdePath, command: u8) {
2080        ide_controller
2081            .io_write(
2082                io_port(
2083                    IdeIoPort::PRI_ALT_STATUS_DEVICE_CTL,
2084                    dev_path.channel.into(),
2085                ),
2086                &[command],
2087            )
2088            .unwrap();
2089    }
2090
2091    fn get_dma_state(ide_controller: &mut IdeDevice, dev_path: &IdePath) -> bool {
2092        // Returns true if DMA state exists, false if None
2093        ide_controller.channels[dev_path.channel as usize]
2094            .bus_master_state
2095            .dma_state
2096            .is_some()
2097    }
2098
2099    fn prep_ide_channel(ide_controller: &mut IdeDevice, drive_type: DriveType, dev_path: &IdePath) {
2100        match drive_type {
2101            DriveType::Hard => {
2102                // SET MULTIPLE MODE - sets number of sectors per block to 128
2103                // this is needed when computing IO sector count for a read/write
2104                execute_command(ide_controller, dev_path, IdeCommand::SET_MULTI_BLOCK_MODE.0);
2105            }
2106            DriveType::Optical => {
2107                // Optical is a ATAPI (PACKET) drive and does not support the SET_MULTI_BLOCK_MODE command
2108            }
2109        }
2110    }
2111
2112    // Waits for a condition on the IDE device, polling the device until then.
2113    async fn wait_for<T>(
2114        ide_device: &mut IdeDevice,
2115        mut f: impl FnMut(&mut IdeDevice) -> Option<T>,
2116    ) -> T {
2117        poll_fn(|cx| {
2118            ide_device.poll_device(cx);
2119            let r = f(ide_device);
2120            if let Some(r) = r {
2121                Poll::Ready(r)
2122            } else {
2123                Poll::Pending
2124            }
2125        })
2126        .await
2127    }
2128
2129    // IDE Command Tests
2130    // Command: WRITE SECTOR(S)
2131    #[async_test]
2132    async fn write_sectors_test() {
2133        const START_SECTOR: u32 = 0;
2134        const SECTOR_COUNT: u8 = 4;
2135
2136        let dev_path = IdePath::default();
2137        let (mut ide_device, mut disk, _file_contents, geometry) =
2138            ide_test_setup(None, DriveType::Hard);
2139
2140        // select device [0,0] = primary channel, primary drive
2141        device_select(&mut ide_device, &dev_path).await;
2142        prep_ide_channel(&mut ide_device, DriveType::Hard, &dev_path);
2143
2144        // write to first 4 sectors
2145        write_command_params(
2146            &mut ide_device,
2147            &dev_path,
2148            START_SECTOR,
2149            SECTOR_COUNT,
2150            Addressing::Lba28Bit,
2151            &geometry,
2152        );
2153
2154        execute_command(&mut ide_device, &dev_path, IdeCommand::WRITE_SECTORS.0);
2155
2156        // drive status should contain DRQ as data is ready to be exchanged with host
2157        let status = get_status(&mut ide_device, &dev_path);
2158        assert!(status.drq() && !status.bsy());
2159
2160        // PIO - writes to data port
2161        let data = &[0xFF_u8; 2][..];
2162        for _ in 0..SECTOR_COUNT {
2163            let status = check_command_ready(&mut ide_device, &dev_path).await;
2164            assert!(status.drq());
2165            assert!(!status.err());
2166            for _ in 0..protocol::HARD_DRIVE_SECTOR_BYTES / 2 {
2167                ide_device.io_write(IdeIoPort::PRI_DATA.0, data).unwrap();
2168            }
2169        }
2170
2171        let status = check_command_ready(&mut ide_device, &dev_path).await;
2172        assert!(!status.err());
2173        assert!(!status.drq());
2174
2175        let buffer =
2176            &mut [0_u8; (protocol::HARD_DRIVE_SECTOR_BYTES * SECTOR_COUNT as u32) as usize][..];
2177        disk.read_exact(buffer).unwrap();
2178        for byte in buffer {
2179            assert_eq!(*byte, 0xFF);
2180        }
2181    }
2182
2183    #[async_test]
2184    async fn software_reset_test() {
2185        const START_SECTOR: u32 = 0;
2186        const SECTOR_COUNT: u8 = 4;
2187
2188        let dev_path = IdePath::default();
2189        let (mut ide_device, _disk, _file_contents, geometry) =
2190            ide_test_setup(None, DriveType::Hard);
2191
2192        // select device [0,0] = primary channel, primary drive
2193        device_select(&mut ide_device, &dev_path).await;
2194        prep_ide_channel(&mut ide_device, DriveType::Hard, &dev_path);
2195
2196        // write to first 4 sectors
2197        write_command_params(
2198            &mut ide_device,
2199            &dev_path,
2200            START_SECTOR,
2201            SECTOR_COUNT,
2202            Addressing::Lba28Bit,
2203            &geometry,
2204        );
2205
2206        execute_command(&mut ide_device, &dev_path, IdeCommand::WRITE_SECTORS.0);
2207        // drive status should contain DRQ as data is ready to be exchanged with host
2208        let status = get_status(&mut ide_device, &dev_path);
2209        assert!(status.drq() && !status.bsy());
2210
2211        execute_soft_reset_command(&mut ide_device, &dev_path, IdeCommand::SOFT_RESET.0);
2212        let status = get_status(&mut ide_device, &dev_path);
2213        assert!(status.bsy());
2214    }
2215
2216    // Command: READ SECTOR(S)
2217    #[async_test]
2218    async fn read_sectors_test() {
2219        const START_SECTOR: u32 = 0;
2220        const SECTOR_COUNT: u8 = 4;
2221
2222        let dev_path = IdePath::default();
2223        let (mut ide_device, _disk, file_contents, geometry) =
2224            ide_test_setup(None, DriveType::Hard);
2225
2226        // select device [0,0] = primary channel, primary drive
2227        device_select(&mut ide_device, &dev_path).await;
2228        prep_ide_channel(&mut ide_device, DriveType::Hard, &dev_path);
2229
2230        // read the first 4 sectors
2231        write_command_params(
2232            &mut ide_device,
2233            &dev_path,
2234            START_SECTOR,
2235            SECTOR_COUNT,
2236            Addressing::Lba28Bit,
2237            &geometry,
2238        );
2239
2240        // PIO - writes sectors to track cache buffer
2241        execute_command(&mut ide_device, &dev_path, IdeCommand::READ_SECTORS.0);
2242
2243        let status = check_command_ready(&mut ide_device, &dev_path).await;
2244        assert!(status.drq());
2245        assert!(!status.err());
2246
2247        // PIO - reads data from track cache buffer
2248        let content_bytes = file_contents.as_bytes();
2249        for sector in 0..SECTOR_COUNT {
2250            let status = check_command_ready(&mut ide_device, &dev_path).await;
2251            assert!(status.drq());
2252            assert!(!status.err());
2253            for word in 0..protocol::HARD_DRIVE_SECTOR_BYTES / 2 {
2254                let data = &mut [0, 0][..];
2255                ide_device.io_read(IdeIoPort::PRI_DATA.0, data).unwrap();
2256
2257                let i = sector as usize * protocol::HARD_DRIVE_SECTOR_BYTES as usize / 2
2258                    + word as usize;
2259                assert_eq!(data[0], content_bytes[i * 2]);
2260                assert_eq!(data[1], content_bytes[i * 2 + 1]);
2261            }
2262        }
2263    }
2264
2265    // Command: READ SECTOR(S) - enlightened
2266    async fn enlightened_cmd_test(drive_type: DriveType) {
2267        const SECTOR_COUNT: u16 = 4;
2268        const BYTE_COUNT: u16 = SECTOR_COUNT * protocol::HARD_DRIVE_SECTOR_BYTES as u16;
2269
2270        let test_guest_mem = GuestMemory::allocate(16384);
2271
2272        let table_gpa = 0x1000;
2273        let data_gpa = 0x2000;
2274        test_guest_mem
2275            .write_plain(
2276                table_gpa,
2277                &BusMasterDmaDesc {
2278                    mem_physical_base: data_gpa,
2279                    byte_count: BYTE_COUNT,
2280                    unused: 0,
2281                    end_of_table: 0x80,
2282                },
2283            )
2284            .unwrap();
2285
2286        let (data_buffer, byte_count) = match drive_type {
2287            DriveType::Hard => (table_gpa as u32, 0),
2288            DriveType::Optical => (data_gpa, BYTE_COUNT.into()),
2289        };
2290
2291        let eint13_command = protocol::EnlightenedInt13Command {
2292            command: IdeCommand::READ_DMA_EXT,
2293            device_head: DeviceHeadReg::new().with_lba(true),
2294            flags: 0,
2295            result_status: 0,
2296            lba_low: 0,
2297            lba_high: 0,
2298            block_count: SECTOR_COUNT,
2299            byte_count,
2300            data_buffer,
2301            skip_bytes_head: 0,
2302            skip_bytes_tail: 0,
2303        };
2304        test_guest_mem.write_plain(0, &eint13_command).unwrap();
2305
2306        let dev_path = IdePath::default();
2307        let (mut ide_device, _disk, file_contents, _geometry) =
2308            ide_test_setup(Some(test_guest_mem.clone()), drive_type);
2309
2310        // select device [0,0] = primary channel, primary drive
2311        device_select(&mut ide_device, &dev_path).await;
2312        prep_ide_channel(&mut ide_device, drive_type, &dev_path);
2313
2314        // READ SECTORS - enlightened
2315        let r = ide_device.io_write(IdeIoPort::PRI_ENLIGHTENED.0, 0_u32.as_bytes()); // read from gpa 0
2316
2317        match r {
2318            IoResult::Defer(mut deferred) => {
2319                poll_fn(|cx| {
2320                    ide_device.poll_device(cx);
2321                    deferred.poll_write(cx)
2322                })
2323                .await
2324                .unwrap();
2325            }
2326            _ => panic!("{:?}", r),
2327        }
2328
2329        let mut buffer = vec![0u8; BYTE_COUNT as usize];
2330        test_guest_mem
2331            .read_at(data_gpa.into(), &mut buffer)
2332            .unwrap();
2333        assert_eq!(buffer, file_contents.as_bytes()[..buffer.len()]);
2334    }
2335
2336    // Command: READ SECTOR(S) - enlightened
2337    #[async_test]
2338    async fn enlightened_cd_cmd_test() {
2339        enlightened_cmd_test(DriveType::Optical).await
2340    }
2341
2342    #[async_test]
2343    async fn enlightened_hdd_cmd_test() {
2344        enlightened_cmd_test(DriveType::Hard).await
2345    }
2346
2347    // Command: READ SECTOR(S) - enlightened
2348    // However, provide incomplete PRD table
2349    #[async_test]
2350    async fn enlightened_cmd_test_incomplete_prd() {
2351        const SECTOR_COUNT: u16 = 8;
2352        const BYTE_COUNT: u16 = SECTOR_COUNT * protocol::HARD_DRIVE_SECTOR_BYTES as u16;
2353
2354        let test_guest_mem = GuestMemory::allocate(16384);
2355
2356        let table_gpa = 0x1000;
2357        let data_gpa = 0x2000;
2358        test_guest_mem
2359            .write_plain(
2360                table_gpa,
2361                &BusMasterDmaDesc {
2362                    mem_physical_base: data_gpa,
2363                    byte_count: BYTE_COUNT / 2,
2364                    unused: 0,
2365                    end_of_table: 0x80, // Mark end before second PRD
2366                },
2367            )
2368            .unwrap();
2369        test_guest_mem
2370            .write_plain(
2371                table_gpa + size_of::<BusMasterDmaDesc>() as u64,
2372                &BusMasterDmaDesc {
2373                    mem_physical_base: data_gpa,
2374                    byte_count: BYTE_COUNT / 2,
2375                    unused: 0,
2376                    end_of_table: 0x80,
2377                },
2378            )
2379            .unwrap();
2380
2381        let data_buffer = table_gpa as u32;
2382        let byte_count = 0;
2383
2384        let eint13_command = protocol::EnlightenedInt13Command {
2385            command: IdeCommand::READ_DMA_EXT,
2386            device_head: DeviceHeadReg::new().with_lba(true),
2387            flags: 0,
2388            result_status: 0,
2389            lba_low: 0,
2390            lba_high: 0,
2391            block_count: SECTOR_COUNT,
2392            byte_count,
2393            data_buffer,
2394            skip_bytes_head: 0,
2395            skip_bytes_tail: 0,
2396        };
2397        test_guest_mem.write_plain(0, &eint13_command).unwrap();
2398
2399        let dev_path = IdePath::default();
2400        let (mut ide_device, _disk, file_contents, _geometry) =
2401            ide_test_setup(Some(test_guest_mem.clone()), DriveType::Hard);
2402
2403        // select device [0,0] = primary channel, primary drive
2404        device_select(&mut ide_device, &dev_path).await;
2405        prep_ide_channel(&mut ide_device, DriveType::Hard, &dev_path);
2406
2407        // READ SECTORS - enlightened
2408        let r = ide_device.io_write(IdeIoPort::PRI_ENLIGHTENED.0, 0_u32.as_bytes()); // read from gpa 0
2409
2410        match r {
2411            IoResult::Defer(mut deferred) => {
2412                poll_fn(|cx| {
2413                    ide_device.poll_device(cx);
2414                    deferred.poll_write(cx)
2415                })
2416                .await
2417                .unwrap();
2418            }
2419            _ => panic!("{:?}", r),
2420        }
2421
2422        let mut buffer = vec![0u8; BYTE_COUNT as usize / 2];
2423        test_guest_mem
2424            .read_at(data_gpa.into(), &mut buffer)
2425            .unwrap();
2426        assert_eq!(buffer, file_contents.as_bytes()[..buffer.len()]);
2427    }
2428
2429    #[async_test]
2430    async fn enlightened_cmd_test_dma_boundary_overflow() {
2431        // Tests a DMA descriptor that starts at a valid address but overflows into invalid memory
2432        // Guest memory: 0x0000-0x3FFF (16KB)
2433        // Descriptor: starts at 0x3000, requests 8KB -> overflows to 0x5000 (invalid)
2434
2435        const SECTOR_COUNT: u16 = 16; // 16 sectors = 8KB
2436        const BYTE_COUNT: u16 = SECTOR_COUNT * protocol::HARD_DRIVE_SECTOR_BYTES as u16;
2437
2438        let test_guest_mem = GuestMemory::allocate(16384);
2439
2440        let table_gpa = 0x1000;
2441        let data_gpa = 0x3000; // Valid start, but will overflow
2442        test_guest_mem
2443            .write_plain(
2444                table_gpa,
2445                &BusMasterDmaDesc {
2446                    mem_physical_base: data_gpa,
2447                    byte_count: BYTE_COUNT, // 8KB - overflows beyond 0x3FFF
2448                    unused: 0,
2449                    end_of_table: 0x80,
2450                },
2451            )
2452            .unwrap();
2453
2454        let data_buffer = table_gpa as u32;
2455        let byte_count = 0;
2456
2457        let eint13_command = protocol::EnlightenedInt13Command {
2458            command: IdeCommand::READ_DMA_ALT,
2459            device_head: DeviceHeadReg::new().with_lba(true),
2460            flags: 0,
2461            result_status: 0,
2462            lba_low: 0,
2463            lba_high: 0,
2464            block_count: SECTOR_COUNT,
2465            byte_count,
2466            data_buffer,
2467            skip_bytes_head: 0,
2468            skip_bytes_tail: 0,
2469        };
2470        test_guest_mem.write_plain(0, &eint13_command).unwrap();
2471
2472        let dev_path = IdePath::default();
2473        let (mut ide_device, _disk, _file_contents, _geometry) =
2474            ide_test_setup(Some(test_guest_mem.clone()), DriveType::Hard);
2475
2476        device_select(&mut ide_device, &dev_path).await;
2477        prep_ide_channel(&mut ide_device, DriveType::Hard, &dev_path);
2478
2479        let r = ide_device.io_write(IdeIoPort::PRI_ENLIGHTENED.0, 0_u32.as_bytes());
2480
2481        match r {
2482            IoResult::Defer(mut deferred) => {
2483                poll_fn(|cx| {
2484                    ide_device.poll_device(cx);
2485                    deferred.poll_write(cx)
2486                })
2487                .await
2488                .unwrap();
2489            }
2490            _ => panic!("{:?}", r),
2491        }
2492
2493        let dma_state = get_dma_state(&mut ide_device, &dev_path);
2494        assert!(
2495            !dma_state,
2496            "Expected DMA state cleared - transfer from 0x{:x} with {} bytes overflows valid range 0x0-0x3FFF",
2497            data_gpa, BYTE_COUNT
2498        );
2499    }
2500
2501    #[async_test]
2502    async fn enlightened_cmd_test_dma_exact_boundary() {
2503        // Tests a DMA descriptor that ends exactly at the boundary of valid memory
2504        // Guest memory: 0x0000-0x3FFF (16KB)
2505        // Descriptor: starts at 0x3E00, requests 512 bytes -> ends at 0x4000 (just past boundary)
2506
2507        const BYTE_COUNT: u16 = 512;
2508
2509        let test_guest_mem = GuestMemory::allocate(16384);
2510
2511        let table_gpa = 0x1000;
2512        let data_gpa = 0x3E00; // 16KB - 512 bytes
2513        test_guest_mem
2514            .write_plain(
2515                table_gpa,
2516                &BusMasterDmaDesc {
2517                    mem_physical_base: data_gpa,
2518                    byte_count: BYTE_COUNT, // Ends exactly at boundary + 1
2519                    unused: 0,
2520                    end_of_table: 0x80,
2521                },
2522            )
2523            .unwrap();
2524
2525        let data_buffer = table_gpa as u32;
2526        let byte_count = 0;
2527
2528        let eint13_command = protocol::EnlightenedInt13Command {
2529            command: IdeCommand::READ_DMA_ALT,
2530            device_head: DeviceHeadReg::new().with_lba(true),
2531            flags: 0,
2532            result_status: 0,
2533            lba_low: 0,
2534            lba_high: 0,
2535            block_count: 1,
2536            byte_count,
2537            data_buffer,
2538            skip_bytes_head: 0,
2539            skip_bytes_tail: 0,
2540        };
2541        test_guest_mem.write_plain(0, &eint13_command).unwrap();
2542
2543        let dev_path = IdePath::default();
2544        let (mut ide_device, _disk, _file_contents, _geometry) =
2545            ide_test_setup(Some(test_guest_mem.clone()), DriveType::Hard);
2546
2547        device_select(&mut ide_device, &dev_path).await;
2548        prep_ide_channel(&mut ide_device, DriveType::Hard, &dev_path);
2549
2550        let r = ide_device.io_write(IdeIoPort::PRI_ENLIGHTENED.0, 0_u32.as_bytes());
2551
2552        match r {
2553            IoResult::Defer(mut deferred) => {
2554                poll_fn(|cx| {
2555                    ide_device.poll_device(cx);
2556                    deferred.poll_write(cx)
2557                })
2558                .await
2559                .unwrap();
2560            }
2561            _ => panic!("{:?}", r),
2562        }
2563
2564        let dma_state = get_dma_state(&mut ide_device, &dev_path);
2565        assert!(
2566            !dma_state,
2567            "Expected DMA state cleared - transfer ending at 0x{:x} exceeds valid range",
2568            data_gpa + BYTE_COUNT as u32
2569        );
2570    }
2571
2572    #[async_test]
2573    async fn enlightened_cmd_test_dma_integer_overflow() {
2574        // Tests a DMA descriptor with byte_count that could cause integer overflow
2575        // Guest memory: 0x0000-0x3FFF (16KB)
2576        // Descriptor: mem_physical_base = 0x2000, byte_count = 0xFFFF (64KB)
2577        // The checked_add should catch this overflow
2578
2579        let test_guest_mem = GuestMemory::allocate(16384);
2580
2581        let table_gpa = 0x1000;
2582        let data_gpa = 0x2000;
2583        test_guest_mem
2584            .write_plain(
2585                table_gpa,
2586                &BusMasterDmaDesc {
2587                    mem_physical_base: data_gpa,
2588                    byte_count: 0xFFFF, // Maximum 16-bit value - would overflow
2589                    unused: 0,
2590                    end_of_table: 0x80,
2591                },
2592            )
2593            .unwrap();
2594
2595        let data_buffer = table_gpa as u32;
2596        let byte_count = 0;
2597
2598        let eint13_command = protocol::EnlightenedInt13Command {
2599            command: IdeCommand::READ_DMA_ALT,
2600            device_head: DeviceHeadReg::new().with_lba(true),
2601            flags: 0,
2602            result_status: 0,
2603            lba_low: 0,
2604            lba_high: 0,
2605            block_count: 128, // Arbitrary
2606            byte_count,
2607            data_buffer,
2608            skip_bytes_head: 0,
2609            skip_bytes_tail: 0,
2610        };
2611        test_guest_mem.write_plain(0, &eint13_command).unwrap();
2612
2613        let dev_path = IdePath::default();
2614        let (mut ide_device, _disk, _file_contents, _geometry) =
2615            ide_test_setup(Some(test_guest_mem.clone()), DriveType::Hard);
2616
2617        device_select(&mut ide_device, &dev_path).await;
2618        prep_ide_channel(&mut ide_device, DriveType::Hard, &dev_path);
2619
2620        let r = ide_device.io_write(IdeIoPort::PRI_ENLIGHTENED.0, 0_u32.as_bytes());
2621
2622        match r {
2623            IoResult::Defer(mut deferred) => {
2624                poll_fn(|cx| {
2625                    ide_device.poll_device(cx);
2626                    deferred.poll_write(cx)
2627                })
2628                .await
2629                .unwrap();
2630            }
2631            _ => panic!("{:?}", r),
2632        }
2633
2634        let dma_state = get_dma_state(&mut ide_device, &dev_path);
2635        assert!(
2636            !dma_state,
2637            "Expected DMA state cleared - large byte_count 0xFFFF should be rejected"
2638        );
2639    }
2640
2641    #[async_test]
2642    async fn enlightened_cmd_test_dma_u32_max_overflow() {
2643        // Tests a DMA descriptor where mem_physical_base + transfer_bytes_left overflows u32
2644        // This tests the checked_add protection against u32 overflow
2645
2646        let test_guest_mem = GuestMemory::allocate(16384);
2647
2648        let table_gpa = 0x1000;
2649        let data_gpa = 0xFFFF_F000_u32; // Near u32::MAX
2650        test_guest_mem
2651            .write_plain(
2652                table_gpa,
2653                &BusMasterDmaDesc {
2654                    mem_physical_base: data_gpa,
2655                    byte_count: 0x2000, // Would overflow past u32::MAX
2656                    unused: 0,
2657                    end_of_table: 0x80,
2658                },
2659            )
2660            .unwrap();
2661
2662        let data_buffer = table_gpa as u32;
2663        let byte_count = 0;
2664
2665        let eint13_command = protocol::EnlightenedInt13Command {
2666            command: IdeCommand::READ_DMA_ALT,
2667            device_head: DeviceHeadReg::new().with_lba(true),
2668            flags: 0,
2669            result_status: 0,
2670            lba_low: 0,
2671            lba_high: 0,
2672            block_count: 16,
2673            byte_count,
2674            data_buffer,
2675            skip_bytes_head: 0,
2676            skip_bytes_tail: 0,
2677        };
2678        test_guest_mem.write_plain(0, &eint13_command).unwrap();
2679
2680        let dev_path = IdePath::default();
2681        let (mut ide_device, _disk, _file_contents, _geometry) =
2682            ide_test_setup(Some(test_guest_mem.clone()), DriveType::Hard);
2683
2684        device_select(&mut ide_device, &dev_path).await;
2685        prep_ide_channel(&mut ide_device, DriveType::Hard, &dev_path);
2686
2687        let r = ide_device.io_write(IdeIoPort::PRI_ENLIGHTENED.0, 0_u32.as_bytes());
2688
2689        match r {
2690            IoResult::Defer(mut deferred) => {
2691                poll_fn(|cx| {
2692                    ide_device.poll_device(cx);
2693                    deferred.poll_write(cx)
2694                })
2695                .await
2696                .unwrap();
2697            }
2698            _ => panic!("{:?}", r),
2699        }
2700
2701        let dma_state = get_dma_state(&mut ide_device, &dev_path);
2702        assert!(
2703            !dma_state,
2704            "Expected DMA state cleared - checked_add should catch u32 overflow from 0x{:x} + 0x2000",
2705            data_gpa
2706        );
2707    }
2708
2709    #[async_test]
2710    async fn enlightened_cmd_test_dma_zero_byte_count() {
2711        // Tests a DMA descriptor with byte_count = 0, which should be treated as 64KB
2712        // This could overflow if the base address is high enough
2713
2714        let test_guest_mem = GuestMemory::allocate(16384);
2715
2716        let table_gpa = 0x1000;
2717        let data_gpa = 0x1000;
2718        test_guest_mem
2719            .write_plain(
2720                table_gpa,
2721                &BusMasterDmaDesc {
2722                    mem_physical_base: data_gpa,
2723                    byte_count: 0, // Treated as 64KB (0x10000)
2724                    unused: 0,
2725                    end_of_table: 0x80,
2726                },
2727            )
2728            .unwrap();
2729
2730        let data_buffer = table_gpa as u32;
2731        let byte_count = 0;
2732
2733        let eint13_command = protocol::EnlightenedInt13Command {
2734            command: IdeCommand::READ_DMA_ALT,
2735            device_head: DeviceHeadReg::new().with_lba(true),
2736            flags: 0,
2737            result_status: 0,
2738            lba_low: 0,
2739            lba_high: 0,
2740            block_count: 128, // 64KB
2741            byte_count,
2742            data_buffer,
2743            skip_bytes_head: 0,
2744            skip_bytes_tail: 0,
2745        };
2746        test_guest_mem.write_plain(0, &eint13_command).unwrap();
2747
2748        let dev_path = IdePath::default();
2749        let (mut ide_device, _disk, _file_contents, _geometry) =
2750            ide_test_setup(Some(test_guest_mem.clone()), DriveType::Hard);
2751
2752        device_select(&mut ide_device, &dev_path).await;
2753        prep_ide_channel(&mut ide_device, DriveType::Hard, &dev_path);
2754
2755        let r = ide_device.io_write(IdeIoPort::PRI_ENLIGHTENED.0, 0_u32.as_bytes());
2756
2757        match r {
2758            IoResult::Defer(mut deferred) => {
2759                poll_fn(|cx| {
2760                    ide_device.poll_device(cx);
2761                    deferred.poll_write(cx)
2762                })
2763                .await
2764                .unwrap();
2765            }
2766            _ => panic!("{:?}", r),
2767        }
2768
2769        let dma_state = get_dma_state(&mut ide_device, &dev_path);
2770        assert!(
2771            !dma_state,
2772            "Expected DMA state cleared - byte_count=0 implies 64KB which exceeds guest memory"
2773        );
2774    }
2775
2776    #[async_test]
2777    async fn identify_test_cd() {
2778        let dev_path = IdePath::default();
2779        let (mut ide_device, _disk, _file_contents, _geometry) =
2780            ide_test_setup(None, DriveType::Optical);
2781
2782        // select device [0,0] = primary channel, primary drive
2783        device_select(&mut ide_device, &dev_path).await;
2784        prep_ide_channel(&mut ide_device, DriveType::Optical, &dev_path);
2785
2786        // PIO - writes sectors to track cache buffer
2787        execute_command(
2788            &mut ide_device,
2789            &dev_path,
2790            IdeCommand::IDENTIFY_PACKET_DEVICE.0,
2791        );
2792
2793        let status = check_command_ready(&mut ide_device, &dev_path).await;
2794        assert!(status.drq());
2795        assert!(!status.err());
2796
2797        // PIO - reads data from track cache buffer
2798        let data = &mut [0_u8; protocol::IDENTIFY_DEVICE_BYTES];
2799        ide_device.io_read(IdeIoPort::PRI_DATA.0, data).unwrap();
2800        let features = protocol::IdeFeatures::read_from_prefix(&data[..])
2801            .unwrap()
2802            .0; // TODO: zerocopy: use-rest-of-range (https://github.com/microsoft/openvmm/issues/759)
2803        let ex_features = protocol::IdeFeatures {
2804            config_bits: 0x85C0,
2805            serial_no: *b"                    ",
2806            buffer_size: 0x0080,
2807            firmware_revision: *b"        ",
2808            model_number: "iVtrau lDC                              ".as_bytes()[..]
2809                .try_into()
2810                .unwrap(),
2811            capabilities: 0x0300,
2812            pio_cycle_times: 0x0200,       // indicate fast I/O
2813            dma_cycle_times: 0x0200,       // indicate fast I/O
2814            new_words_valid_flags: 0x0003, // indicate next words are valid
2815            multi_sector_capabilities: 0x0100_u16 | protocol::MAX_SECTORS_MULT_TRANSFER_DEFAULT,
2816            single_word_dma_mode: 0x0007, // support up to mode 3, no mode active
2817            multi_word_dma_mode: 0x0407,  // support up to mode 3, mode 3 active
2818            enhanced_pio_mode: 0x0003,    // PIO mode 3 and 4 supported
2819            min_multi_dma_time: 0x0078,
2820            recommended_multi_dma_time: 0x0078,
2821            min_pio_cycle_time_no_flow: 0x01FC, // Taken from a real CD device
2822            min_pio_cycle_time_flow: 0x00B4,    // Taken from a real CD device
2823            ..FromZeros::new_zeroed()
2824        };
2825        assert_eq!(features.as_bytes(), ex_features.as_bytes());
2826    }
2827
2828    #[async_test]
2829    async fn identify_test_hdd() {
2830        let dev_path = IdePath::default();
2831        let (mut ide_device, _disk, _file_contents, geometry) =
2832            ide_test_setup(None, DriveType::Hard);
2833        // select device [0,0] = primary channel, primary drive
2834        device_select(&mut ide_device, &dev_path).await;
2835        prep_ide_channel(&mut ide_device, DriveType::Hard, &dev_path);
2836        // PIO - writes sectors to track cache buffer
2837        execute_command(&mut ide_device, &dev_path, IdeCommand::IDENTIFY_DEVICE.0);
2838
2839        let status = check_command_ready(&mut ide_device, &dev_path).await;
2840        assert!(status.drq());
2841        assert!(!status.err());
2842
2843        // PIO - reads data from track cache buffer
2844        let data = &mut [0_u8; protocol::IDENTIFY_DEVICE_BYTES];
2845        ide_device.io_read(IdeIoPort::PRI_DATA.0, data).unwrap();
2846        let features = protocol::IdeFeatures::read_from_prefix(&data[..])
2847            .unwrap()
2848            .0; // TODO: zerocopy: use-rest-of-range (https://github.com/microsoft/openvmm/issues/759)
2849
2850        let total_chs_sectors: u32 =
2851            geometry.sectors_per_track * geometry.cylinder_count * geometry.head_count;
2852        let (cylinders, heads, sectors_per_track) = if total_chs_sectors < protocol::MAX_CHS_SECTORS
2853        {
2854            (
2855                geometry.cylinder_count as u16,
2856                geometry.head_count as u16,
2857                geometry.sectors_per_track as u16,
2858            )
2859        } else {
2860            (0x3FFF, 16, 63)
2861        };
2862
2863        let firmware_revision = if dev_path.channel == 0 {
2864            ".1.1 0  "
2865        } else {
2866            ".1.1 1  "
2867        }
2868        .as_bytes()[..]
2869            .try_into()
2870            .unwrap();
2871
2872        let user_addressable_sectors =
2873            if geometry.total_sectors > (protocol::LBA_28BIT_MAX_SECTORS as u64) {
2874                protocol::LBA_28BIT_MAX_SECTORS
2875            } else {
2876                geometry.total_sectors as u32
2877            };
2878
2879        let ex_features = protocol::IdeFeatures {
2880            config_bits: 0x045A,
2881            cylinders,
2882            heads,
2883            unformatted_sectors_per_track: (protocol::HARD_DRIVE_SECTOR_BYTES
2884                * geometry.sectors_per_track) as u16,
2885            unformatted_bytes_per_sector: protocol::HARD_DRIVE_SECTOR_BYTES as u16,
2886            sectors_per_track,
2887            compact_flash: [0xABCD, 0xDCBA],
2888            vendor0: 0x0123,
2889            serial_no: *b"                    ",
2890            buffer_type: 3,
2891            buffer_size: 0x0080,
2892            firmware_revision,
2893            model_number: "iVtrau lDH                              ".as_bytes()[..]
2894                .try_into()
2895                .unwrap(),
2896            max_sectors_mult_transfer: (0x8000 | protocol::MAX_SECTORS_MULT_TRANSFER_DEFAULT),
2897            capabilities: 0x0F00,          // supports Dma, IORDY, LBA
2898            pio_cycle_times: 0x0200,       // indicate fast I/O
2899            dma_cycle_times: 0x0200,       // indicate fast I/O
2900            new_words_valid_flags: 0x0003, // indicate next words are valid
2901            log_cylinders: geometry.cylinder_count as u16,
2902            log_heads: geometry.head_count as u16,
2903            log_sectors_per_track: geometry.sectors_per_track as u16,
2904            log_total_sectors: total_chs_sectors.into(),
2905            multi_sector_capabilities: 0x0100_u16 | protocol::MAX_SECTORS_MULT_TRANSFER_DEFAULT,
2906            user_addressable_sectors: user_addressable_sectors.into(),
2907            single_word_dma_mode: 0x0007, // support up to mode 3, no mode active
2908            multi_word_dma_mode: 0x0407,  // support up to mode 3, mode 3 active
2909            enhanced_pio_mode: 0x0003,    // PIO mode 3 and 4 supported
2910            min_multi_dma_time: 0x0078,
2911            recommended_multi_dma_time: 0x0078,
2912            min_pio_cycle_time_no_flow: 0x014D,
2913            min_pio_cycle_time_flow: 0x0078,
2914            major_version_number: 0x01F0, // claim support for ATA4-ATA8
2915            minor_version_number: 0,
2916            command_set_supported: 0x0028, // support caching and power management
2917            command_sets_supported: 0x7400, // support flushing
2918            command_set_supported_ext: 0x4040, // write fua support for default write hardening
2919            command_set_enabled1: 0x0028,  // support caching and power management
2920            command_set_enabled2: 0x3400,  // support flushing
2921            command_set_default: 0x4040,   // write fua support for default write hardening
2922            total_sectors_48_bit: geometry.total_sectors.into(),
2923            default_sector_size_config: 0x4000, // describes the sector size related info. Reflect the underlying device sector size and logical:physical ratio
2924            logical_block_alignment: 0x4000, // describes alignment of logical blocks within physical block
2925            ..FromZeros::new_zeroed()
2926        };
2927        assert_eq!(features.as_bytes(), ex_features.as_bytes());
2928    }
2929
2930    /// Enlightened INT13 with a non-DMA command (READ_SECTORS) should not
2931    /// hang. Before the fix, this would start async disk IO that produces
2932    /// a PIO buffer on completion. The DMA engine can't drain a PIO buffer,
2933    /// so the deferred write completion check (!(bsy || drq)) never passes.
2934    #[async_test]
2935    async fn enlightened_hdd_non_dma_cmd_completes() {
2936        let test_guest_mem = GuestMemory::allocate(16384);
2937
2938        // Set up a PRD table (the enlightened path always writes it,
2939        // even though READ_SECTORS won't use it)
2940        let table_gpa: u64 = 0x1000;
2941        let data_gpa: u32 = 0x2000;
2942        test_guest_mem
2943            .write_plain(
2944                table_gpa,
2945                &BusMasterDmaDesc {
2946                    mem_physical_base: data_gpa,
2947                    byte_count: 512,
2948                    unused: 0,
2949                    end_of_table: 0x80,
2950                },
2951            )
2952            .unwrap();
2953
2954        // READ_SECTORS (0x20) is a PIO read command. The enlightened path
2955        // is designed for DMA commands only (READ_DMA_EXT, WRITE_DMA_EXT).
2956        // Sending a PIO command through it starts async disk IO, but the
2957        // resulting PIO buffer can't be drained by DMA -- hang forever.
2958        let eint13_command = protocol::EnlightenedInt13Command {
2959            command: IdeCommand::READ_SECTORS,
2960            device_head: DeviceHeadReg::new().with_lba(true),
2961            flags: 0,
2962            result_status: 0,
2963            lba_low: 0,
2964            lba_high: 0,
2965            block_count: 1,
2966            byte_count: 0,
2967            data_buffer: table_gpa as u32,
2968            skip_bytes_head: 0,
2969            skip_bytes_tail: 0,
2970        };
2971        test_guest_mem.write_plain(0, &eint13_command).unwrap();
2972
2973        let dev_path = IdePath::default();
2974        let (mut ide_device, _disk, _, _) =
2975            ide_test_setup(Some(test_guest_mem.clone()), DriveType::Hard);
2976
2977        device_select(&mut ide_device, &dev_path).await;
2978        prep_ide_channel(&mut ide_device, DriveType::Hard, &dev_path);
2979
2980        // After fix: non-DMA commands through the enlightened path are
2981        // rejected early and return Ok (not Defer). Before the fix,
2982        // this would return Defer and hang forever.
2983        assert!(
2984            matches!(
2985                ide_device.io_write(IdeIoPort::PRI_ENLIGHTENED.0, 0_u32.as_bytes()),
2986                IoResult::Ok
2987            ),
2988            "non-DMA command (READ_SECTORS) via enlightened path should return Ok, not Defer"
2989        );
2990    }
2991}