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 !Command::from(self.bus_master_state.cmd_status_reg as u16).pio_enabled() {
300                    return None;
301                }
302
303                // If the port does not match any of the statically registered IO ports then
304                // the port is part of the dynamically registered bus master range. The IDE
305                // bus master range spans 16 ports with the first 8 corresponding to the primary
306                // IDE channel.
307                Some((
308                    Port::BusMaster(BusMasterReg(io_port & 0x7)),
309                    (io_port as usize & 0x8) >> 3,
310                ))
311            }
312        }
313    }
314}
315
316impl Channel {
317    fn enlightened_port_write(
318        &mut self,
319        data: &[u8],
320        bus_master_state: &BusMasterState,
321    ) -> IoResult {
322        if data.len() != 4 {
323            return IoResult::Err(IoError::InvalidAccessSize);
324        }
325
326        if self.enlightened_write.is_some() {
327            tracelimit::error_ratelimited!("enlightened write while one is in progress, ignoring");
328            return IoResult::Ok;
329        }
330
331        // Read the EnlightenedInt13Command packet directly from guest ram
332        let addr = u32::from_ne_bytes(data.try_into().unwrap());
333
334        let eint13_cmd = match self
335            .guest_memory
336            .read_plain::<protocol::EnlightenedInt13Command>(addr as u64)
337        {
338            Ok(cmd) => cmd,
339            Err(err) => {
340                tracelimit::error_ratelimited!(
341                    error = &err as &dyn std::error::Error,
342                    "failed to read enlightened IO command"
343                );
344                return IoResult::Ok;
345            }
346        };
347
348        // Write out the drive-head register FIRST because that is used to
349        // select the current drive.
350        self.write_drive_register(
351            DriveRegister::DeviceHead,
352            eint13_cmd.device_head.into(),
353            bus_master_state,
354        );
355
356        if let Some(status) = self.current_drive_status() {
357            if status.err() {
358                tracelimit::warn_ratelimited!(
359                    "drive is in error state, ignoring enlightened command",
360                );
361                return IoResult::Ok;
362            } else if status.bsy() || status.drq() {
363                tracelimit::warn_ratelimited!(
364                    "command is already pending on this drive, ignoring enlightened command"
365                );
366                return IoResult::Ok;
367            }
368        }
369
370        let result = if let Some(drive_type) = self.current_drive_type() {
371            match drive_type {
372                DriveType::Optical => {
373                    self.enlightened_cd_command(addr.into(), eint13_cmd, bus_master_state)
374                }
375                DriveType::Hard => {
376                    self.enlightened_hdd_command(addr.into(), eint13_cmd, bus_master_state)
377                }
378            }
379        } else {
380            tracelimit::warn_ratelimited!(
381                eint13_cmd = ?eint13_cmd,
382                drive_idx = self.state.current_drive_idx,
383                "Enlightened IO command: No attached drive"
384            );
385            IoResult::Ok
386        };
387
388        self.post_drive_access(bus_master_state);
389        result
390    }
391
392    fn enlightened_hdd_command(
393        &mut self,
394        guest_address: u64,
395        eint13_cmd: protocol::EnlightenedInt13Command,
396        bus_master_state: &BusMasterState,
397    ) -> IoResult {
398        let mut lba48 = eint13_cmd.lba_high as u64;
399        lba48 <<= 32;
400        lba48 |= eint13_cmd.lba_low as u64;
401
402        tracing::trace!(
403            command = ?eint13_cmd.command,
404            lba = lba48,
405            block_count = eint13_cmd.block_count,
406            buffer = eint13_cmd.data_buffer,
407            guest_address,
408            "enlightened hdd command"
409        );
410
411        // The enlightened INT13 path is a DMA-only fast path used by
412        // the Hyper-V BIOS. Non-DMA commands (PIO reads/writes,
413        // IDENTIFY_DEVICE, etc.) would leave the drive with a PIO
414        // buffer that DMA can't drain, causing the deferred write to
415        // never complete.
416        let cmd = eint13_cmd.command;
417        if !matches!(
418            cmd,
419            IdeCommand::READ_DMA
420                | IdeCommand::READ_DMA_ALT
421                | IdeCommand::WRITE_DMA
422                | IdeCommand::WRITE_DMA_ALT
423                | IdeCommand::READ_DMA_EXT
424                | IdeCommand::WRITE_DMA_EXT
425                | IdeCommand::WRITE_DMA_FUA_EXT
426        ) {
427            tracelimit::warn_ratelimited!(?cmd, "ignoring non-DMA command in enlightened path");
428            return IoResult::Ok;
429        }
430
431        // Write out the PRD register for the bus master
432        self.write_bus_master_reg(
433            BusMasterReg::TABLE_PTR,
434            eint13_cmd.data_buffer.as_bytes(),
435            bus_master_state,
436        )
437        .unwrap();
438
439        // Now that we know what the IDE command is, disambiguate between
440        // 28-bit LBA and 48-bit LBA
441        if cmd == IdeCommand::READ_DMA_EXT || cmd == IdeCommand::WRITE_DMA_EXT {
442            // 48-bit LBA, high 24 bits of logical block address
443            self.write_drive_register(
444                DriveRegister::LbaLow,
445                (eint13_cmd.lba_low >> 24) as u8,
446                bus_master_state,
447            );
448
449            self.write_drive_register(
450                DriveRegister::LbaMid,
451                eint13_cmd.lba_high as u8,
452                bus_master_state,
453            );
454
455            self.write_drive_register(
456                DriveRegister::LbaHigh,
457                (eint13_cmd.lba_high >> 8) as u8,
458                bus_master_state,
459            );
460
461            // 48-bit LBA, high 8 bits of sector count
462            // Write the low-byte of the sector count
463            self.write_drive_register(
464                DriveRegister::SectorCount,
465                (eint13_cmd.block_count >> 8) as u8,
466                bus_master_state,
467            );
468        }
469
470        // Write the low-byte of the sector count
471        self.write_drive_register(
472            DriveRegister::SectorCount,
473            eint13_cmd.block_count as u8,
474            bus_master_state,
475        );
476
477        // Finish writing the LBA low bytes to the FIFOs
478        self.write_drive_register(
479            DriveRegister::LbaLow,
480            eint13_cmd.lba_low as u8,
481            bus_master_state,
482        );
483        self.write_drive_register(
484            DriveRegister::LbaMid,
485            (eint13_cmd.lba_low >> 8) as u8,
486            bus_master_state,
487        );
488        self.write_drive_register(
489            DriveRegister::LbaHigh,
490            (eint13_cmd.lba_low >> 16) as u8,
491            bus_master_state,
492        );
493
494        // Make sure that the IDE channel will not cause an interrupt since this
495        // enlightened operation is intended to be 100% synchronous.
496        let old_adapter_control_reg = self.state.shadow_adapter_control_reg;
497        self.write_drive_register(
498            DriveRegister::AlternateStatusDeviceControl,
499            DeviceControlReg::new()
500                .with_interrupt_mask(true)
501                .into_bits(),
502            bus_master_state,
503        );
504
505        // Start the dma engine.
506        let mut bus_master_flags = BusMasterCommandReg::new().with_start(true);
507        if cmd == IdeCommand::READ_DMA_EXT
508            || cmd == IdeCommand::READ_DMA
509            || cmd == IdeCommand::READ_DMA_ALT
510        {
511            // set rw flag to 1 to inticate that bus master is performing a read
512            bus_master_flags.set_write(true);
513        }
514
515        self.write_bus_master_reg(
516            BusMasterReg::COMMAND,
517            &[bus_master_flags.into_bits() as u8],
518            bus_master_state,
519        )
520        .unwrap();
521
522        // Start the IDE command
523        self.write_drive_register(DriveRegister::StatusCmd, cmd.0, bus_master_state);
524
525        // Defer the write.
526        let (write, token) = defer_write();
527        self.enlightened_write = Some(EnlightenedWrite::Hard(EnlightenedHddWrite {
528            deferred: write,
529            old_adapter_control_reg,
530            guest_address,
531            drive_index: self.state.current_drive_idx,
532        }));
533
534        tracing::trace!(enlightened_write = ?self.enlightened_write, "enlightened_hdd_command");
535        if let Some(status) = self.current_drive_status() {
536            if status.drq() {
537                tracelimit::warn_ratelimited!(
538                    "command is waiting for data read from guest or data write to guest"
539                );
540                return IoResult::Ok;
541            }
542        }
543        IoResult::Defer(token)
544    }
545
546    fn enlightened_cd_command(
547        &mut self,
548        guest_address: u64,
549        eint13_cmd: protocol::EnlightenedInt13Command,
550        bus_master_state: &BusMasterState,
551    ) -> IoResult {
552        tracing::trace!(
553            guest_address,
554            command = ?eint13_cmd,
555            "enlightened cd command"
556        );
557
558        // Save the old Precompensation byte because we must NOT use traditional DMA
559        // with this command. Just read the bytes into the track cache so we can use
560        // WriteRamBytes to move them to the guest.
561        let old_features_reg = self.state.shadow_features_reg;
562        self.write_drive_register(DriveRegister::ErrorFeatures, 0, bus_master_state);
563
564        // Make sure that any code path through the IDE completion and error code does NOT
565        // generate an interrupt. This enlightenment is intended to operate completely
566        // synchronously.
567        let old_adapter_control_reg = self.state.shadow_adapter_control_reg;
568        self.write_drive_register(
569            DriveRegister::AlternateStatusDeviceControl,
570            DeviceControlReg::new()
571                .with_interrupt_mask(true)
572                .into_bits(),
573            bus_master_state,
574        );
575
576        // Start the Atapi packet command
577        self.write_drive_register(
578            DriveRegister::StatusCmd,
579            IdeCommand::PACKET_COMMAND.0,
580            bus_master_state,
581        );
582
583        // Construct the SCSI command packet in the single sector buffer that
584        // we're about to dispatch.
585        let cdb = scsi::Cdb10 {
586            operation_code: ScsiOp::READ,
587            flags: CdbFlags::new(),
588            logical_block: eint13_cmd.lba_low.into(),
589            reserved2: 0,
590            transfer_blocks: eint13_cmd.block_count.into(),
591            control: 0,
592        };
593
594        // Assume the device is configured for 12-byte commands.
595        let mut command = [0; 12];
596        command[..cdb.as_bytes().len()].copy_from_slice(cdb.as_bytes());
597
598        // Spawn the IO read which eventually puts the data into the track cache
599        // Wait synchronously for the command to complete reading the data into the track cache.
600        self.write_drive_data(command.as_bytes(), bus_master_state);
601
602        // Defer the write.
603        let (write, token) = defer_write();
604        self.enlightened_write = Some(EnlightenedWrite::Optical(EnlightenedCdWrite {
605            deferred: write,
606            old_adapter_control_reg,
607            guest_address,
608            old_features_reg,
609            data_buffer: eint13_cmd.data_buffer,
610            skip_bytes_head: eint13_cmd.skip_bytes_head,
611            byte_count: eint13_cmd.byte_count,
612            block_count: eint13_cmd.block_count,
613            drive_index: self.state.current_drive_idx,
614        }));
615
616        tracing::trace!(enlightened_write = ?self.enlightened_write, "enlightened_cd_command");
617        if let Some(status) = self.current_drive_status() {
618            if status.drq() {
619                tracelimit::warn_ratelimited!(
620                    "command is waiting for data read from guest or data write to guest"
621                );
622                return IoResult::Ok;
623            }
624        }
625        IoResult::Defer(token)
626    }
627
628    fn complete_enlightened_hdd_write(
629        &mut self,
630        write: EnlightenedHddWrite,
631        bus_master_state: &BusMasterState,
632    ) {
633        // Stop the dma engine (probably stopped already, but this mimics the BIOS
634        // code which this enlightenment replaces).
635        self.write_bus_master_reg(BusMasterReg::COMMAND, &[0], bus_master_state)
636            .unwrap();
637
638        // Clear the pending interrupt and read status.
639        let status = self.read_drive_register(DriveRegister::StatusCmd, bus_master_state);
640        let status = Status::from_bits(status);
641
642        if status.err() {
643            // If there was an error, copy back the status into the enlightened INT13 command in
644            // the guest so that the guest can check it.
645            if let Err(err) = self.guest_memory.write_at(
646                write.guest_address
647                    + offset_of!(protocol::EnlightenedInt13Command, result_status) as u64,
648                &[status.into_bits()],
649            ) {
650                tracelimit::error_ratelimited!(
651                    ?status,
652                    error = &err as &dyn std::error::Error,
653                    "failed to write eint13 status back"
654                );
655            }
656        }
657
658        // Possibly re-enable IDE channel interrupts for the next operation
659        self.write_drive_register(
660            DriveRegister::AlternateStatusDeviceControl,
661            write.old_adapter_control_reg,
662            bus_master_state,
663        );
664
665        write.deferred.complete();
666    }
667
668    fn complete_enlightened_cd_write(
669        &mut self,
670        write: EnlightenedCdWrite,
671        bus_master_state: &BusMasterState,
672    ) {
673        // Clear the pending interrupt and read status.
674        let status = self.read_drive_register(DriveRegister::StatusCmd, bus_master_state);
675        let status = Status::from_bits(status);
676
677        if status.err() {
678            // If there was an error, copy back the status into the enlightened INT13 command in
679            // the guest so that the guest can check it.
680            if let Err(err) = self.guest_memory.write_at(
681                write.guest_address
682                    + offset_of!(protocol::EnlightenedInt13Command, result_status) as u64,
683                &[status.into_bits()],
684            ) {
685                tracelimit::error_ratelimited!(
686                    ?status,
687                    error = &err as &dyn std::error::Error,
688                    "failed to write eint13 status back"
689                );
690            }
691        } else {
692            let mut remaining =
693                (write.block_count as u32 * protocol::CD_DRIVE_SECTOR_BYTES) as usize;
694
695            // Skip over the unused portion of the result.
696            let skip = (write.skip_bytes_head as usize).min(remaining);
697            remaining -= skip;
698            self.skip_drive_data(skip, bus_master_state);
699
700            // Read the requested part of the result.
701            let byte_count = (write.byte_count as usize).min(remaining);
702            remaining -= byte_count;
703
704            let mut copied = 0;
705            while copied < byte_count {
706                let mut buf = [0; 512];
707                let len = (byte_count - copied).min(buf.len());
708                let buf = &mut buf[..len];
709                self.read_drive_data(buf, bus_master_state);
710                if let Err(err) = self
711                    .guest_memory
712                    .write_at((write.data_buffer as u64).wrapping_add(copied as u64), buf)
713                {
714                    tracelimit::warn_ratelimited!(
715                        error = &err as &dyn std::error::Error,
716                        "failed to write enlightened result to guest memory"
717                    );
718                }
719                copied += buf.len();
720            }
721
722            // Read any remaining data to prepare the device for the next command.
723            self.skip_drive_data(remaining, bus_master_state);
724        }
725
726        // Restore the precompensation setting which existed prior to this read
727        self.write_drive_register(
728            DriveRegister::ErrorFeatures,
729            write.old_features_reg,
730            bus_master_state,
731        );
732
733        // Possibly re-enable IDE channel interrupts for the next operation
734        self.write_drive_register(
735            DriveRegister::AlternateStatusDeviceControl,
736            write.old_adapter_control_reg,
737            bus_master_state,
738        );
739
740        tracing::trace!("enlightened cd write completed");
741        write.deferred.complete();
742    }
743
744    fn perform_dma_memory_phase(&mut self) {
745        let Some(drive) = &mut self.drives[self.state.current_drive_idx] else {
746            return;
747        };
748
749        if self.bus_master_state.dma_error {
750            if drive.handle_read_dma_descriptor_error() {
751                self.bus_master_state.dma_error = false;
752            }
753            return;
754        }
755
756        let mut dma_avail = match drive.dma_request() {
757            Some((dma_type, avail)) if *dma_type == self.bus_master_state.dma_io_type() => {
758                avail as u32
759            }
760            _ => {
761                // No active, appropriate DMA buffer.
762                return;
763            }
764        };
765
766        let Some(dma) = &mut self.bus_master_state.dma_state else {
767            return;
768        };
769
770        while dma_avail > 0 {
771            // If the number of bytes left in the transfer is zero, we need to read the next Dma descriptor
772            if dma.transfer_bytes_left == 0 {
773                assert!(!dma.transfer_complete);
774
775                // The descriptor table pointer points to a table of Dma
776                // scatter/gather descriptors built by the operating system.
777                // This table tells us where the place the incoming data for
778                // reads or where to get the outgoing data for writes. The
779                // last valid table entry will have the high bit of the
780                // EndOfTable field set.
781                let descriptor_addr: u64 = self
782                    .bus_master_state
783                    .desc_table_ptr
784                    .wrapping_add(8 * (dma.descriptor_idx as u32))
785                    .into();
786
787                let cur_desc_table_entry = match self
788                    .guest_memory
789                    .read_plain::<protocol::BusMasterDmaDesc>(descriptor_addr)
790                {
791                    Ok(cur_desc_table_entry) => cur_desc_table_entry,
792                    Err(err) => {
793                        self.bus_master_state.dma_state = None;
794                        if !drive.handle_read_dma_descriptor_error() {
795                            self.bus_master_state.dma_error = true;
796                        }
797                        tracelimit::error_ratelimited!(
798                            error = &err as &dyn std::error::Error,
799                            "dma descriptor read error"
800                        );
801                        return;
802                    }
803                };
804
805                tracing::trace!(entry = ?cur_desc_table_entry, "read dma desc");
806
807                dma.transfer_bytes_left = cur_desc_table_entry.byte_count.into();
808                // A zero byte length implies 64Kb
809                if cur_desc_table_entry.byte_count == 0 {
810                    dma.transfer_bytes_left = 0x10000;
811                }
812
813                dma.transfer_base_addr = cur_desc_table_entry.mem_physical_base.into();
814                dma.transfer_complete = (cur_desc_table_entry.end_of_table & 0x80) != 0;
815
816                // Increment to the next descriptor.
817                dma.descriptor_idx += 1;
818                if dma.transfer_complete {
819                    dma.descriptor_idx = 0;
820                }
821            }
822
823            // Transfer byte count is limited by the transfer size and the number of bytes in our IDE buffer.
824            let bytes_to_transfer = dma_avail.min(dma.transfer_bytes_left);
825
826            assert!(bytes_to_transfer != 0);
827
828            if let Err(err) = drive.dma_transfer(
829                &self.guest_memory,
830                dma.transfer_base_addr,
831                bytes_to_transfer as usize,
832            ) {
833                // The guest pointed the DMA engine at memory it can't access.
834                // Stop the transfer and raise the bus master DMA error, just as
835                // real hardware would on a failed bus access.
836                self.bus_master_state.dma_state = None;
837                if !drive.handle_read_dma_descriptor_error() {
838                    self.bus_master_state.dma_error = true;
839                }
840                tracelimit::error_ratelimited!(
841                    error = &err as &dyn std::error::Error,
842                    "dma transfer memory access error"
843                );
844                return;
845            }
846
847            dma_avail -= bytes_to_transfer;
848            dma.transfer_base_addr += bytes_to_transfer as u64;
849            dma.transfer_bytes_left -= bytes_to_transfer;
850            if dma.transfer_bytes_left == 0 && dma.transfer_complete {
851                if dma_avail > 0 {
852                    // If descriptor table ended before buffer was exhausted, advance buffer to end to indicate completion of operation
853                    drive.set_prd_exhausted();
854                    drive.dma_advance_buffer(dma_avail as usize);
855                }
856                tracing::trace!("dma transfer is complete");
857                self.bus_master_state.dma_state = None;
858                break;
859            }
860        }
861    }
862}
863
864impl ChangeDeviceState for IdeDevice {
865    fn start(&mut self) {}
866
867    async fn stop(&mut self) {}
868
869    async fn reset(&mut self) {
870        self.bus_master_pio_dynamic.unmap();
871        self.bus_master_state = BusMasterState::new();
872        for channel in &mut self.channels {
873            channel.reset();
874        }
875    }
876}
877
878impl ChipsetDevice for IdeDevice {
879    fn supports_pio(&mut self) -> Option<&mut dyn PortIoIntercept> {
880        Some(self)
881    }
882
883    fn supports_pci(&mut self) -> Option<&mut dyn PciConfigSpace> {
884        Some(self)
885    }
886
887    fn supports_poll_device(&mut self) -> Option<&mut dyn PollDevice> {
888        Some(self)
889    }
890}
891
892impl PollDevice for IdeDevice {
893    fn poll_device(&mut self, cx: &mut Context<'_>) {
894        for channel in &mut self.channels {
895            channel.poll_device(cx, &self.bus_master_state);
896        }
897    }
898}
899
900impl PortIoIntercept for IdeDevice {
901    fn io_read(&mut self, io_port: u16, data: &mut [u8]) -> IoResult {
902        match self.parse_port(io_port) {
903            Some((port, index)) => match port {
904                Port::Data => {
905                    self.channels[index].read_drive_data(data, &self.bus_master_state);
906                    IoResult::Ok
907                }
908                Port::Drive(register) => {
909                    data[0] =
910                        self.channels[index].read_drive_register(register, &self.bus_master_state);
911                    IoResult::Ok
912                }
913                Port::Enlightened => IoResult::Err(IoError::InvalidRegister),
914                Port::BusMaster(offset) => self.channels[index].read_bus_master_reg(offset, data),
915            },
916            None => IoResult::Err(IoError::InvalidRegister),
917        }
918    }
919
920    fn io_write(&mut self, io_port: u16, data: &[u8]) -> IoResult {
921        match self.parse_port(io_port) {
922            Some((port, index)) => match port {
923                Port::Data => {
924                    self.channels[index].write_drive_data(data, &self.bus_master_state);
925                    IoResult::Ok
926                }
927                Port::Drive(register) => {
928                    self.channels[index].write_drive_register(
929                        register,
930                        data[0],
931                        &self.bus_master_state,
932                    );
933                    IoResult::Ok
934                }
935                Port::Enlightened => {
936                    self.channels[index].enlightened_port_write(data, &self.bus_master_state)
937                }
938                Port::BusMaster(offset) => {
939                    self.channels[index].write_bus_master_reg(offset, data, &self.bus_master_state)
940                }
941            },
942            None => IoResult::Err(IoError::InvalidRegister),
943        }
944    }
945
946    fn get_static_regions(&mut self) -> &[(&str, RangeInclusive<u16>)] {
947        &[
948            (
949                "ide primary channel",
950                IdeIoPort::PRI_ENLIGHTENED.0..=IdeIoPort::PRI_STATUS_CMD.0,
951            ),
952            (
953                "ide primary channel control",
954                IdeIoPort::PRI_ALT_STATUS_DEVICE_CTL.0..=IdeIoPort::PRI_ALT_STATUS_DEVICE_CTL.0,
955            ),
956            (
957                "ide secondary channel",
958                IdeIoPort::SEC_ENLIGHTENED.0..=IdeIoPort::SEC_STATUS_CMD.0,
959            ),
960            (
961                "ide secondary channel control",
962                IdeIoPort::SEC_ALT_STATUS_DEVICE_CTL.0..=IdeIoPort::SEC_ALT_STATUS_DEVICE_CTL.0,
963            ),
964        ]
965    }
966}
967
968impl PciConfigSpace for IdeDevice {
969    fn pci_cfg_read(&mut self, offset: u16, mut value: ByteEnabledDwordRead<'_>) -> IoResult {
970        value.set(if offset < HEADER_TYPE_00_SIZE {
971            match HeaderType00(offset) {
972                HeaderType00::DEVICE_VENDOR => protocol::BX_PCI_ISA_BRIDGE_IDE_IDREG_VALUE,
973                HeaderType00::STATUS_COMMAND => self.bus_master_state.cmd_status_reg,
974                HeaderType00::CLASS_REVISION => protocol::BX_PCI_IDE_CLASS_WORD,
975                HeaderType00::BAR4 => self.bus_master_state.port_addr_reg,
976                offset => {
977                    tracing::debug!(?offset, "undefined type00 header read");
978                    0
979                }
980            }
981        } else {
982            match IdeConfigSpace(offset) {
983                IdeConfigSpace::PRIMARY_TIMING_REG_ADDR => self.bus_master_state.timing_reg,
984                IdeConfigSpace::SECONDARY_TIMING_REG_ADDR => {
985                    self.bus_master_state.secondary_timing_reg
986                }
987                IdeConfigSpace::UDMA_CTL_REG_ADDR => self.bus_master_state.dma_ctl_reg,
988                IdeConfigSpace::MANUFACTURE_ID_REG_ADDR => {
989                    // This is a private versioning register, and no one is supposed to use it.
990                    // But a real Triton chipset returns this value...
991                    0x00000F30
992                }
993                offset => {
994                    // Allow reads from undefined areas.
995                    tracing::trace!(?offset, "undefined ide pci config space read");
996                    return IoResult::Err(IoError::InvalidRegister);
997                }
998            }
999        });
1000
1001        tracing::trace!(?offset, ?value, "ide pci config space read");
1002        IoResult::Ok
1003    }
1004
1005    fn pci_cfg_write(&mut self, offset: u16, value: ByteEnabledDwordWrite) -> IoResult {
1006        if offset < HEADER_TYPE_00_SIZE {
1007            let offset = HeaderType00(offset);
1008            tracing::trace!(?offset, ?value, "ide pci config space write");
1009
1010            const BUS_MASTER_IO_ENABLE_MASK: u32 = Command::new()
1011                .with_pio_enabled(true)
1012                .with_bus_master(true)
1013                .into_bits() as u32;
1014
1015            match offset {
1016                HeaderType00::STATUS_COMMAND => {
1017                    // Several bits are used to reset status bits when written as 1s.
1018                    let value = value.merge(self.bus_master_state.cmd_status_reg);
1019                    self.bus_master_state.cmd_status_reg &= !(0x38000000 & value);
1020                    // Only allow writes to two bits (0 and 2). All other bits are read-only.
1021                    self.bus_master_state.cmd_status_reg &= !BUS_MASTER_IO_ENABLE_MASK;
1022
1023                    self.bus_master_state.cmd_status_reg |= value & BUS_MASTER_IO_ENABLE_MASK;
1024
1025                    // Is the io address space enabled for bus mastering and is bus mastering enabled?
1026                    let command = Command::from(self.bus_master_state.cmd_status_reg as u16);
1027                    if !(command.pio_enabled() && command.bus_master()) {
1028                        self.bus_master_pio_dynamic.unmap();
1029                        tracing::trace!("disabling bus master io range");
1030                    } else {
1031                        // Install the callbacks for the current bus primary I/O port range (which
1032                        // is dynamically configurable through PCI config registers)
1033                        let first_port = (self.bus_master_state.port_addr_reg as u16) & 0xFFF0;
1034                        tracing::trace!(?first_port, "enabling bus master range");
1035
1036                        // Change the io range for the bus master registers. Some of the bus master
1037                        // registers can be cached on writes.
1038                        self.bus_master_pio_dynamic.map(first_port);
1039                    }
1040                }
1041                HeaderType00::BAR4 => {
1042                    // Only allow writes to bits 4 to 15
1043                    let value = value.merge(self.bus_master_state.port_addr_reg);
1044                    self.bus_master_state.port_addr_reg =
1045                        (value & 0x0000FFF0) | DEFAULT_BUS_MASTER_PORT_ADDR_REG;
1046                }
1047                _ => tracing::debug!(?offset, "undefined type00 header write"),
1048            }
1049        } else {
1050            let offset = IdeConfigSpace(offset);
1051            tracing::trace!(?offset, ?value, "ide pci config space write");
1052
1053            match offset {
1054                IdeConfigSpace::PRIMARY_TIMING_REG_ADDR => {
1055                    value.merge_into(&mut self.bus_master_state.timing_reg)
1056                }
1057                IdeConfigSpace::SECONDARY_TIMING_REG_ADDR => {
1058                    value.merge_into(&mut self.bus_master_state.secondary_timing_reg)
1059                }
1060                IdeConfigSpace::UDMA_CTL_REG_ADDR => {
1061                    value.merge_into(&mut self.bus_master_state.dma_ctl_reg)
1062                }
1063                _ => tracing::trace!(?offset, "undefined ide pci config space write"),
1064            }
1065        }
1066
1067        IoResult::Ok
1068    }
1069
1070    fn suggested_bdf(&mut self) -> Option<(u8, u8, u8)> {
1071        Some((0, 7, 1)) // as per PIIX4 spec
1072    }
1073}
1074
1075/// IDE Channel
1076enum ChannelType {
1077    Primary,
1078    Secondary,
1079}
1080
1081#[derive(Inspect)]
1082#[inspect(tag = "drive_type")]
1083pub enum DriveMedia {
1084    HardDrive(#[inspect(rename = "backend")] Disk),
1085    OpticalDrive(#[inspect(rename = "backend")] Arc<dyn AsyncScsiDisk>),
1086}
1087
1088impl DriveMedia {
1089    pub fn hard_disk(disk: Disk) -> Self {
1090        DriveMedia::HardDrive(disk)
1091    }
1092
1093    pub fn optical_disk(scsi_disk: Arc<dyn AsyncScsiDisk>) -> Self {
1094        DriveMedia::OpticalDrive(scsi_disk)
1095    }
1096}
1097
1098#[derive(Debug, Default, Inspect)]
1099struct ChannelState {
1100    current_drive_idx: usize,
1101    shadow_adapter_control_reg: u8,
1102    shadow_features_reg: u8,
1103}
1104
1105#[derive(InspectMut)]
1106struct Channel {
1107    #[inspect(mut, with = "inspect_drives")]
1108    drives: [Option<DiskDrive>; 2],
1109    interrupt: LineInterrupt,
1110    state: ChannelState,
1111    bus_master_state: ChannelBusMasterState,
1112    enlightened_write: Option<EnlightenedWrite>,
1113    guest_memory: GuestMemory,
1114    #[inspect(skip)]
1115    channel: u8,
1116}
1117
1118fn inspect_drives(drives: &mut [Option<DiskDrive>]) -> impl '_ + InspectMut {
1119    inspect::adhoc_mut(|req| {
1120        let mut resp = req.respond();
1121        for (i, drive) in drives.iter_mut().enumerate() {
1122            resp.field_mut(&i.to_string(), drive);
1123        }
1124    })
1125}
1126
1127impl Channel {
1128    fn new(
1129        channel_drives: [Option<DriveMedia>; 2],
1130        channel_type: ChannelType,
1131        interrupt: LineInterrupt,
1132        guest_memory: GuestMemory,
1133    ) -> Result<Self, NewDeviceError> {
1134        let [primary_media, secondary_media] = channel_drives;
1135
1136        let channel_number = match channel_type {
1137            ChannelType::Primary => 0,
1138            ChannelType::Secondary => 1,
1139        };
1140
1141        Ok(Self {
1142            drives: [
1143                primary_media
1144                    .map(|media| {
1145                        DiskDrive::new(
1146                            media,
1147                            IdePath {
1148                                channel: channel_number,
1149                                drive: 0,
1150                            },
1151                        )
1152                    })
1153                    .transpose()?,
1154                secondary_media
1155                    .map(|media| {
1156                        DiskDrive::new(
1157                            media,
1158                            IdePath {
1159                                channel: channel_number,
1160                                drive: 1,
1161                            },
1162                        )
1163                    })
1164                    .transpose()?,
1165            ],
1166            interrupt,
1167            state: ChannelState::default(),
1168            bus_master_state: ChannelBusMasterState::default(),
1169            enlightened_write: None,
1170            guest_memory,
1171            channel: channel_number,
1172        })
1173    }
1174
1175    fn reset(&mut self) {
1176        tracelimit::info_ratelimited!(channel = self.channel, "channel reset");
1177        self.interrupt.set_level(false);
1178        self.state = ChannelState::default();
1179        self.bus_master_state = ChannelBusMasterState::default();
1180        for drive in self.drives.iter_mut().flatten() {
1181            drive.reset();
1182        }
1183    }
1184
1185    fn poll_device(&mut self, cx: &mut Context<'_>, bus_master_state: &BusMasterState) {
1186        for drive in self.drives.iter_mut().flatten() {
1187            drive.poll_device(cx);
1188        }
1189        self.post_drive_access(bus_master_state);
1190    }
1191
1192    fn current_drive_status(&mut self) -> Option<Status> {
1193        if let Some(drive) = &mut self.drives[self.state.current_drive_idx] {
1194            let status = drive.read_register(DriveRegister::AlternateStatusDeviceControl);
1195            Some(Status::from_bits(status))
1196        } else {
1197            None
1198        }
1199    }
1200
1201    fn drive_status(&mut self, drive_index: usize) -> Status {
1202        // Reading the values from Status register without clearing any bits
1203        assert!(self.drives[drive_index].is_some());
1204        let status = self.drives[drive_index]
1205            .as_mut()
1206            .unwrap()
1207            .read_register(DriveRegister::AlternateStatusDeviceControl);
1208        Status::from_bits(status)
1209    }
1210
1211    fn current_drive_type(&self) -> Option<DriveType> {
1212        self.drives[self.state.current_drive_idx]
1213            .as_ref()
1214            .map(|drive| drive.drive_type())
1215    }
1216
1217    fn drive_type(&mut self, drive_index: usize) -> DriveType {
1218        assert!(self.drives[drive_index].is_some());
1219        self.drives[drive_index]
1220            .as_ref()
1221            .map(|drive| drive.drive_type())
1222            .unwrap()
1223    }
1224
1225    fn interrupt_pending(&self) -> bool {
1226        self.drives
1227            .iter()
1228            .flatten()
1229            .any(|drive| drive.interrupt_pending())
1230    }
1231
1232    fn post_drive_access(&mut self, bus_master_state: &BusMasterState) {
1233        // DMA first, since this may affect the other operations.
1234        self.perform_dma_memory_phase();
1235
1236        // Enlightened writes.
1237        if let Some(enlightened_write) = &self.enlightened_write {
1238            let drive_index = match enlightened_write {
1239                EnlightenedWrite::Hard(enlightened_hdd_write) => enlightened_hdd_write.drive_index,
1240                EnlightenedWrite::Optical(enlightened_cd_write) => enlightened_cd_write.drive_index,
1241            };
1242
1243            let status = self.drive_status(drive_index);
1244            let completed = match self.drive_type(drive_index) {
1245                DriveType::Hard => !(status.bsy() || status.drq()),
1246                DriveType::Optical => status.drdy(),
1247            };
1248            if completed {
1249                // The command is done.
1250                let write = self.enlightened_write.take().unwrap();
1251                match write {
1252                    EnlightenedWrite::Hard(write) => {
1253                        self.complete_enlightened_hdd_write(write, bus_master_state)
1254                    }
1255                    EnlightenedWrite::Optical(write) => {
1256                        self.complete_enlightened_cd_write(write, bus_master_state)
1257                    }
1258                }
1259            }
1260        }
1261
1262        // Update interrupt state.
1263        let interrupt = self.interrupt_pending();
1264        if interrupt {
1265            tracing::trace!(channel = self.channel, interrupt, "post_drive_access");
1266            self.bus_master_state.status_reg.set_interrupt(true);
1267        }
1268        self.interrupt.set_level(interrupt);
1269    }
1270
1271    /// Returns Ok(true) if an interrupt should be delivered. The whole result
1272    /// of this should be passed to `io_port_completion`
1273    fn read_drive_register(
1274        &mut self,
1275        port: DriveRegister,
1276        bus_master_state: &BusMasterState,
1277    ) -> u8 {
1278        // Call the selected drive, but fall back to drive 0 if drive 1 is not present.
1279        let mut drive = self.drives[self.state.current_drive_idx].as_mut();
1280        if drive.is_none() {
1281            drive = self.drives[0].as_mut();
1282        }
1283
1284        let data = if let Some(drive) = drive {
1285            // Fill with zeroes if the drive doesn't write it (which can happen for some registers if
1286            // the device is not selected).
1287            drive.read_register(port)
1288        } else {
1289            // Returns 0x7f if neither device is present. This is align with ATA-5 "Devices shall not have a pull-up resistor on DD7"
1290            // Note: Legacy implementation returns 0xff in this case.
1291            0x7f
1292        };
1293
1294        tracing::trace!(?port, ?data, channel = self.channel, "io port read");
1295        self.post_drive_access(bus_master_state);
1296        data
1297    }
1298
1299    /// Returns Ok(true) if an interrupt should be delivered. The whole result
1300    /// of this should be passed to `io_port_completion` except in the case of
1301    /// the enlightened port path.
1302    fn write_drive_register(
1303        &mut self,
1304        port: DriveRegister,
1305        data: u8,
1306        bus_master_state: &BusMasterState,
1307    ) {
1308        tracing::trace!(?port, ?data, channel = self.channel, "io port write");
1309
1310        match port {
1311            DriveRegister::DeviceHead => {
1312                // Shadow the device bit for use in the DMA engine.
1313                self.state.current_drive_idx = ((data >> 4) & 1) as usize;
1314            }
1315            DriveRegister::AlternateStatusDeviceControl => {
1316                // Save this for restoring in the enlightened path.
1317                self.state.shadow_adapter_control_reg = data;
1318                let v = DeviceControlReg::from_bits_truncate(data);
1319                if v.reset() && (self.drives[0].is_some() || self.drives[1].is_some()) {
1320                    self.state = ChannelState::default();
1321                }
1322            }
1323            DriveRegister::ErrorFeatures => {
1324                // Save this for restoring in the enlightened path.
1325                self.state.shadow_features_reg = data;
1326            }
1327            _ => {}
1328        }
1329
1330        // Call both drives.
1331        if let Some(drive) = &mut self.drives[1] {
1332            drive.write_register(port, data);
1333        }
1334        if let Some(drive) = &mut self.drives[0] {
1335            drive.write_register(port, data);
1336        }
1337
1338        self.post_drive_access(bus_master_state);
1339    }
1340
1341    fn read_drive_data(&mut self, data: &mut [u8], bus_master_state: &BusMasterState) {
1342        // Call the selected drive, but fall back to drive 0 if drive 1 is not present.
1343        let mut drive = self.drives[self.state.current_drive_idx].as_mut();
1344        if drive.is_none() {
1345            drive = self.drives[0].as_mut();
1346        }
1347
1348        data.fill(0xff);
1349        // DD7 must be low to conform to the ATA spec.
1350        data[0] = 0x7f;
1351
1352        if let Some(drive) = drive {
1353            drive.pio_read(data);
1354        };
1355
1356        self.post_drive_access(bus_master_state);
1357    }
1358
1359    fn skip_drive_data(&mut self, mut len: usize, bus_master_state: &BusMasterState) {
1360        let mut buf = [0; 512];
1361        while len > 0 {
1362            let this_len = len.min(buf.len());
1363            let buf = &mut buf[..this_len];
1364            self.read_drive_data(buf, bus_master_state);
1365            len -= buf.len();
1366        }
1367    }
1368
1369    fn write_drive_data(&mut self, data: &[u8], bus_master_state: &BusMasterState) {
1370        if let Some(drive) = &mut self.drives[0] {
1371            drive.pio_write(data);
1372        }
1373        if let Some(drive) = &mut self.drives[1] {
1374            drive.pio_write(data);
1375        }
1376        self.post_drive_access(bus_master_state);
1377    }
1378
1379    fn read_bus_master_reg(&mut self, bus_master_reg: BusMasterReg, data: &mut [u8]) -> IoResult {
1380        let data_len = data.len();
1381        match bus_master_reg {
1382            BusMasterReg::COMMAND => match data_len {
1383                1 | 2 => data.copy_from_slice(
1384                    &self.bus_master_state.command_reg.into_bits().to_ne_bytes()[..data_len],
1385                ),
1386                _ => return IoResult::Err(IoError::InvalidAccessSize),
1387            },
1388            BusMasterReg::STATUS => {
1389                let mut status = self.bus_master_state.status_reg;
1390
1391                if self.bus_master_state.dma_state.is_some() {
1392                    status.set_active(true);
1393                }
1394
1395                match data_len {
1396                    1 | 2 => data.copy_from_slice(&status.into_bits().to_ne_bytes()[..data_len]),
1397                    _ => return IoResult::Err(IoError::InvalidAccessSize),
1398                }
1399            }
1400            BusMasterReg::TABLE_PTR => match data_len {
1401                2 | 4 => data.copy_from_slice(
1402                    &self.bus_master_state.desc_table_ptr.to_ne_bytes()[..data_len],
1403                ),
1404                _ => return IoResult::Err(IoError::InvalidAccessSize),
1405            },
1406            BusMasterReg::TABLE_PTR2 => {
1407                if data_len == 2 {
1408                    data.copy_from_slice(&self.bus_master_state.desc_table_ptr.to_ne_bytes()[2..4]);
1409                } else {
1410                    return IoResult::Err(IoError::InvalidAccessSize);
1411                }
1412            }
1413            _ => return IoResult::Err(IoError::InvalidRegister),
1414        }
1415
1416        tracing::trace!(?bus_master_reg, ?data, "bus master register read");
1417        IoResult::Ok
1418    }
1419
1420    fn write_bus_master_reg(
1421        &mut self,
1422        bus_master_reg: BusMasterReg,
1423        data: &[u8],
1424        bus_master_state: &BusMasterState,
1425    ) -> IoResult {
1426        let value: u64 = match data.len() {
1427            1 => u8::from_ne_bytes(data.as_bytes().try_into().unwrap()).into(),
1428            2 => u16::from_ne_bytes(data.as_bytes().try_into().unwrap()).into(),
1429            4 => u32::from_ne_bytes(data.as_bytes().try_into().unwrap()).into(),
1430            _ => return IoResult::Err(IoError::InvalidAccessSize),
1431        };
1432
1433        tracing::trace!(?bus_master_reg, value, "bus master register write");
1434
1435        match bus_master_reg {
1436            BusMasterReg::COMMAND => {
1437                // A write to this register will begin/end a dma transfer
1438                // and control its direction (write vs. read).
1439                if data.len() > 2 {
1440                    return IoResult::Err(IoError::InvalidAccessSize);
1441                }
1442
1443                let old_value = self.bus_master_state.command_reg;
1444                // TODO: make sure all bits that should be preserved are defined.
1445                let mut new_value = BusMasterCommandReg::from_bits_truncate(value as u32);
1446
1447                // The read/write bit is marked as read-only when dma is active.
1448                if old_value.start() {
1449                    // Set the new value of the read/write flag to match the
1450                    // existing value, regardless of the new value of the flag.
1451                    new_value.set_write(old_value.write());
1452                    if !new_value.start() {
1453                        self.bus_master_state.dma_state = None
1454                    }
1455                } else if new_value.start() {
1456                    self.bus_master_state.dma_state = Some(Default::default());
1457                };
1458
1459                self.bus_master_state.command_reg = new_value;
1460            }
1461            BusMasterReg::STATUS => {
1462                if data.len() > 2 {
1463                    return IoResult::Err(IoError::InvalidAccessSize);
1464                }
1465
1466                let value = BusMasterStatusReg::from_bits_truncate(value as u32);
1467                let old_value = self.bus_master_state.status_reg;
1468                let mut new_value = old_value.with_settable(value.settable());
1469
1470                // These bits are reset if a one is written
1471                if value.interrupt() {
1472                    new_value.set_interrupt(false);
1473                }
1474                if value.dma_error() {
1475                    new_value.set_dma_error(false);
1476                }
1477
1478                tracing::trace!(?old_value, ?new_value, "set bus master status");
1479                self.bus_master_state.status_reg = new_value;
1480            }
1481            BusMasterReg::TABLE_PTR => {
1482                if data.len() < 2 {
1483                    return IoResult::Err(IoError::InvalidAccessSize);
1484                }
1485
1486                if data.len() == 4 {
1487                    // Writing the whole 32-bits pointer with the lowest 2 bits zeroed-out.
1488                    self.bus_master_state.desc_table_ptr = value as u32 & 0xffff_fffc;
1489                } else {
1490                    // Writing the low 16-bits of the 32-bits pointer, with the
1491                    // lowest 2 bits zeroed-out
1492                    self.bus_master_state.desc_table_ptr = (self.bus_master_state.desc_table_ptr
1493                        & 0xffff_0000)
1494                        | (value as u32 & 0x0000_fffc);
1495                }
1496            }
1497            BusMasterReg::TABLE_PTR2 => {
1498                // Documentation doesn't mention this offset. Apparently OS/2 writes to this port.
1499                // Port not written to in recent Windows boot.
1500                self.bus_master_state.desc_table_ptr = (self.bus_master_state.desc_table_ptr
1501                    & 0xffff)
1502                    | ((value as u32 & 0xffff) << 16);
1503            }
1504            _ => return IoResult::Err(IoError::InvalidRegister),
1505        }
1506
1507        self.post_drive_access(bus_master_state);
1508        IoResult::Ok
1509    }
1510}
1511
1512#[derive(Debug, Copy, Clone, PartialEq)]
1513enum DriveType {
1514    Hard,
1515    Optical,
1516}
1517
1518#[derive(Debug, Default, Inspect)]
1519struct DmaState {
1520    descriptor_idx: u8,
1521    transfer_complete: bool,
1522    transfer_bytes_left: u32,
1523    transfer_base_addr: u64,
1524}
1525
1526mod save_restore {
1527    use super::*;
1528    use vmcore::save_restore::RestoreError;
1529    use vmcore::save_restore::SaveError;
1530    use vmcore::save_restore::SaveRestore;
1531
1532    mod state {
1533        use crate::drive::save_restore::state::SavedDriveState;
1534        use mesh::payload::Protobuf;
1535        use vmcore::save_restore::SavedStateRoot;
1536
1537        #[derive(Protobuf)]
1538        #[mesh(package = "storage.ide.controller")]
1539        pub struct SavedBusMasterState {
1540            #[mesh(1)]
1541            pub cmd_status_reg: u32,
1542            #[mesh(2)]
1543            pub port_addr_reg: u32,
1544            #[mesh(3)]
1545            pub timing_reg: u32,
1546            #[mesh(4)]
1547            pub secondary_timing_reg: u32,
1548            #[mesh(5)]
1549            pub dma_ctl_reg: u32,
1550        }
1551
1552        #[derive(Protobuf, SavedStateRoot)]
1553        #[mesh(package = "storage.ide.controller")]
1554        pub struct SavedState {
1555            #[mesh(1)]
1556            pub bus_master: SavedBusMasterState,
1557            #[mesh(2)]
1558            pub channel0: SavedChannelState,
1559            #[mesh(3)]
1560            pub channel1: SavedChannelState,
1561        }
1562
1563        #[derive(Protobuf)]
1564        #[mesh(package = "storage.ide.controller")]
1565        pub struct SavedDmaState {
1566            #[mesh(1)]
1567            pub descriptor_idx: u8,
1568            #[mesh(2)]
1569            pub transfer_complete: bool,
1570            #[mesh(3)]
1571            pub transfer_bytes_left: u32,
1572            #[mesh(4)]
1573            pub transfer_base_addr: u64,
1574        }
1575
1576        #[derive(Protobuf)]
1577        #[mesh(package = "storage.ide.controller")]
1578        pub struct SavedChannelBusMasterState {
1579            #[mesh(1)]
1580            pub command_reg: u32,
1581            #[mesh(2)]
1582            pub status_reg: u32,
1583            #[mesh(3)]
1584            pub desc_table_ptr: u32,
1585            #[mesh(4)]
1586            pub dma_state: Option<SavedDmaState>,
1587            #[mesh(5)]
1588            pub dma_error: bool,
1589        }
1590
1591        #[derive(Protobuf)]
1592        #[mesh(package = "storage.ide.controller")]
1593        pub struct SavedChannelState {
1594            #[mesh(1)]
1595            pub current_drive_idx: u8,
1596            #[mesh(2)]
1597            pub shadow_adapter_control_reg: u8,
1598            #[mesh(3)]
1599            pub shadow_features_reg: u8,
1600            #[mesh(4)]
1601            pub bus_master: SavedChannelBusMasterState,
1602            #[mesh(5)]
1603            pub drive0: Option<SavedDriveState>,
1604            #[mesh(6)]
1605            pub drive1: Option<SavedDriveState>,
1606        }
1607    }
1608
1609    impl SaveRestore for IdeDevice {
1610        type SavedState = state::SavedState;
1611
1612        fn save(&mut self) -> Result<Self::SavedState, SaveError> {
1613            let BusMasterState {
1614                cmd_status_reg,
1615                port_addr_reg,
1616                timing_reg,
1617                secondary_timing_reg,
1618                dma_ctl_reg,
1619            } = self.bus_master_state;
1620
1621            let bus_master = state::SavedBusMasterState {
1622                cmd_status_reg,
1623                port_addr_reg,
1624                timing_reg,
1625                secondary_timing_reg,
1626                dma_ctl_reg,
1627            };
1628
1629            let saved_state = state::SavedState {
1630                bus_master,
1631                channel0: self.channels[0].save()?,
1632                channel1: self.channels[1].save()?,
1633            };
1634
1635            Ok(saved_state)
1636        }
1637
1638        fn restore(&mut self, state: Self::SavedState) -> Result<(), RestoreError> {
1639            let state::SavedState {
1640                bus_master:
1641                    state::SavedBusMasterState {
1642                        cmd_status_reg,
1643                        port_addr_reg,
1644                        timing_reg,
1645                        secondary_timing_reg,
1646                        dma_ctl_reg,
1647                    },
1648                channel0,
1649                channel1,
1650            } = state;
1651
1652            self.bus_master_state = BusMasterState {
1653                cmd_status_reg,
1654                port_addr_reg,
1655                timing_reg,
1656                secondary_timing_reg,
1657                dma_ctl_reg,
1658            };
1659
1660            self.channels[0].restore(channel0)?;
1661            self.channels[1].restore(channel1)?;
1662
1663            Ok(())
1664        }
1665    }
1666
1667    #[derive(Debug, Error)]
1668    enum ChannelRestoreError {
1669        #[error("missing drive for state")]
1670        MissingDriveForState,
1671        #[error("missing state for drive")]
1672        MissingStateForDrive,
1673    }
1674
1675    impl Channel {
1676        fn save(&mut self) -> Result<state::SavedChannelState, SaveError> {
1677            // We wait for the completion of deferred IOs as part of pause.
1678            assert!(self.enlightened_write.is_none());
1679
1680            let ChannelState {
1681                current_drive_idx,
1682                shadow_adapter_control_reg,
1683                shadow_features_reg,
1684            } = self.state;
1685
1686            let ChannelBusMasterState {
1687                command_reg,
1688                status_reg,
1689                desc_table_ptr,
1690                dma_state,
1691                dma_error,
1692            } = &self.bus_master_state;
1693
1694            let saved_state = state::SavedChannelState {
1695                current_drive_idx: current_drive_idx as u8,
1696                shadow_adapter_control_reg,
1697                shadow_features_reg,
1698                bus_master: state::SavedChannelBusMasterState {
1699                    command_reg: command_reg.into_bits(),
1700                    status_reg: status_reg.into_bits(),
1701                    desc_table_ptr: *desc_table_ptr,
1702                    dma_state: dma_state.as_ref().map(|dma| {
1703                        let DmaState {
1704                            descriptor_idx,
1705                            transfer_complete,
1706                            transfer_bytes_left,
1707                            transfer_base_addr,
1708                        } = dma;
1709
1710                        state::SavedDmaState {
1711                            descriptor_idx: *descriptor_idx,
1712                            transfer_complete: *transfer_complete,
1713                            transfer_bytes_left: *transfer_bytes_left,
1714                            transfer_base_addr: *transfer_base_addr,
1715                        }
1716                    }),
1717                    dma_error: *dma_error,
1718                },
1719                drive0: self.drives[0]
1720                    .as_mut()
1721                    .map(|drive| drive.save())
1722                    .transpose()?,
1723                drive1: self.drives[1]
1724                    .as_mut()
1725                    .map(|drive| drive.save())
1726                    .transpose()?,
1727            };
1728
1729            Ok(saved_state)
1730        }
1731
1732        fn restore(&mut self, state: state::SavedChannelState) -> Result<(), RestoreError> {
1733            let state::SavedChannelState {
1734                current_drive_idx,
1735                shadow_adapter_control_reg,
1736                shadow_features_reg,
1737                bus_master:
1738                    state::SavedChannelBusMasterState {
1739                        command_reg,
1740                        status_reg,
1741                        desc_table_ptr,
1742                        dma_state,
1743                        dma_error,
1744                    },
1745                drive0,
1746                drive1,
1747            } = state;
1748
1749            self.state = ChannelState {
1750                current_drive_idx: current_drive_idx as usize,
1751                shadow_adapter_control_reg,
1752                shadow_features_reg,
1753            };
1754
1755            self.bus_master_state = ChannelBusMasterState {
1756                command_reg: BusMasterCommandReg::from_bits(command_reg),
1757                status_reg: BusMasterStatusReg::from_bits(status_reg),
1758                desc_table_ptr,
1759                dma_state: dma_state.map(|dma| {
1760                    let state::SavedDmaState {
1761                        descriptor_idx,
1762                        transfer_complete,
1763                        transfer_bytes_left,
1764                        transfer_base_addr,
1765                    } = dma;
1766
1767                    DmaState {
1768                        descriptor_idx,
1769                        transfer_complete,
1770                        transfer_bytes_left,
1771                        transfer_base_addr,
1772                    }
1773                }),
1774                dma_error,
1775            };
1776
1777            for (drive, state) in self.drives.iter_mut().zip([drive0, drive1]) {
1778                match (drive, state) {
1779                    (Some(drive), Some(state)) => drive.restore(state)?,
1780                    (None, None) => {}
1781                    (Some(_), None) => {
1782                        return Err(RestoreError::InvalidSavedState(
1783                            ChannelRestoreError::MissingStateForDrive.into(),
1784                        ));
1785                    }
1786                    (None, Some(_)) => {
1787                        return Err(RestoreError::InvalidSavedState(
1788                            ChannelRestoreError::MissingDriveForState.into(),
1789                        ));
1790                    }
1791                }
1792            }
1793
1794            self.interrupt.set_level(self.interrupt_pending());
1795            Ok(())
1796        }
1797    }
1798}
1799
1800#[cfg(test)]
1801mod tests {
1802    use super::*;
1803    use crate::IdeIoPort;
1804    use crate::protocol::BusMasterDmaDesc;
1805    use crate::protocol::DeviceHeadReg;
1806    use crate::protocol::IdeCommand;
1807    use chipset_device::pio::ExternallyManagedPortIoIntercepts;
1808    use disk_file::FileDisk;
1809    use pal_async::async_test;
1810    use scsidisk::atapi_scsi::AtapiScsiDisk;
1811    use scsidisk::scsidvd::SimpleScsiDvd;
1812    use std::fs::File;
1813    use std::future::poll_fn;
1814    use std::io::Read;
1815    use std::io::Write;
1816    use std::task::Poll;
1817    use tempfile::NamedTempFile;
1818    use test_with_tracing::test;
1819    use zerocopy::FromBytes;
1820    use zerocopy::FromZeros;
1821    use zerocopy::IntoBytes;
1822
1823    #[async_test]
1824    async fn restore_updates_interrupt_without_processing_drive_work() {
1825        use vmcore::line_interrupt::test_helpers::TestLineInterruptTarget;
1826        use vmcore::save_restore::SaveRestore;
1827        use vmcore::save_restore::SavedStateBlob;
1828
1829        fn controller(file: &NamedTempFile, drive: u8, interrupt: LineInterrupt) -> IdeDevice {
1830            let disk = Disk::new(FileDisk::open(file.reopen().unwrap(), false).unwrap()).unwrap();
1831            let mut drives = [None, None];
1832            drives[usize::from(drive)] = Some(DriveMedia::hard_disk(disk));
1833            IdeDevice::new(
1834                GuestMemory::allocate(16 * 1024),
1835                &mut ExternallyManagedPortIoIntercepts,
1836                drives,
1837                [None, None],
1838                interrupt,
1839                LineInterrupt::detached(),
1840            )
1841            .unwrap()
1842        }
1843
1844        for drive in [0, 1] {
1845            for pending in [false, true] {
1846                let file = NamedTempFile::new().unwrap();
1847                file.as_file().set_len(1024 * 1024).unwrap();
1848                let mut source = controller(&file, drive, LineInterrupt::detached());
1849                if pending {
1850                    source
1851                        .io_write(
1852                            IdeIoPort::PRI_DEVICE_HEAD.0,
1853                            &[DeviceHeadReg::new().with_dev(drive != 0).into_bits()],
1854                        )
1855                        .unwrap();
1856                    execute_command(
1857                        &mut source,
1858                        &IdePath { channel: 0, drive },
1859                        IdeCommand::IDENTIFY_DEVICE.0,
1860                    );
1861                }
1862                // The bus-master interrupt bit can be acknowledged separately
1863                // from the drive interrupt. Restore must not relatch it.
1864                source.channels[0]
1865                    .bus_master_state
1866                    .status_reg
1867                    .set_interrupt(false);
1868                let saved = SavedStateBlob::new(source.save().unwrap());
1869                let target = TestLineInterruptTarget::new_arc();
1870                let mut destination = controller(
1871                    &file,
1872                    drive,
1873                    LineInterrupt::new_with_target("IDE", target.clone(), 0),
1874                );
1875                destination.channels[0].interrupt.set_level(!pending);
1876                destination.restore(saved.parse().unwrap()).unwrap();
1877                assert_eq!(target.is_high(0), pending);
1878                assert!(
1879                    !destination.channels[0]
1880                        .bus_master_state
1881                        .status_reg
1882                        .interrupt()
1883                );
1884            }
1885        }
1886    }
1887
1888    #[derive(Debug, Inspect)]
1889    struct MediaGeometry {
1890        sectors_per_track: u32,
1891        cylinder_count: u32,
1892        head_count: u32,
1893        total_sectors: u64,
1894    }
1895
1896    impl MediaGeometry {
1897        fn new(total_sectors: u64, sector_size: u32) -> Result<Self, NewDeviceError> {
1898            if total_sectors > protocol::MAX_BYTES_48BIT_LBA / sector_size as u64 {
1899                return Err(NewDeviceError::DiskTooLarge(
1900                    total_sectors * sector_size as u64,
1901                ));
1902            }
1903            let hard_drive_sectors = total_sectors.min(protocol::MAX_CHS_SECTORS as u64);
1904            let mut sectors_per_track;
1905            let mut cylinders_times_heads;
1906            let mut head_count;
1907
1908            if hard_drive_sectors > (16 * 63 * 0xFFFF) {
1909                sectors_per_track = 255;
1910                head_count = 16;
1911                cylinders_times_heads = hard_drive_sectors / (sectors_per_track as u64);
1912            } else {
1913                sectors_per_track = 17;
1914                cylinders_times_heads = hard_drive_sectors / (sectors_per_track as u64);
1915
1916                head_count = std::cmp::max((cylinders_times_heads as u32).div_ceil(1024), 4);
1917
1918                if (cylinders_times_heads >= (head_count as u64) * 1024) || head_count > 16 {
1919                    // Always use 16 heads
1920                    head_count = 16;
1921                    sectors_per_track = 31;
1922                    cylinders_times_heads = hard_drive_sectors / (sectors_per_track as u64);
1923                }
1924
1925                if cylinders_times_heads >= (head_count as u64) * 1024 {
1926                    // Always use 16 heads
1927                    head_count = 16;
1928                    sectors_per_track = 63;
1929                    cylinders_times_heads = hard_drive_sectors / (sectors_per_track as u64);
1930                }
1931            }
1932            Ok(MediaGeometry {
1933                sectors_per_track,
1934                cylinder_count: (cylinders_times_heads / (head_count as u64)) as u32,
1935                head_count,
1936                total_sectors,
1937            })
1938        }
1939    }
1940
1941    struct CommandParams {
1942        sector_count: u8,
1943        sector_num: u8,
1944        cylinder_lsb: u8,
1945        cylinder_msb: u8,
1946        device_head: u8,
1947    }
1948
1949    #[expect(dead_code)]
1950    enum Addressing {
1951        Chs,
1952        Lba28Bit,
1953        Lba48Bit,
1954    }
1955
1956    fn ide_test_setup(
1957        guest_memory: Option<GuestMemory>,
1958        drive_type: DriveType,
1959    ) -> (IdeDevice, File, Vec<u32>, MediaGeometry) {
1960        let test_guest_mem = match guest_memory {
1961            Some(test_gm) => test_gm,
1962            None => GuestMemory::allocate(16 * 1024),
1963        };
1964
1965        // prep file (write 4GB, numbers 1-1048576 (1GB))
1966        let temp_file = NamedTempFile::new().unwrap();
1967        let mut handle1 = temp_file.reopen().unwrap();
1968        let handle2 = temp_file.reopen().unwrap();
1969        let data = (0..0x100000_u32).collect::<Vec<_>>();
1970        handle1.write_all(data.as_bytes()).unwrap();
1971
1972        let disk = Disk::new(FileDisk::open(handle1, false).unwrap()).unwrap();
1973        let geometry = MediaGeometry::new(disk.sector_count(), disk.sector_size()).unwrap();
1974
1975        let media = match drive_type {
1976            DriveType::Hard => DriveMedia::hard_disk(disk),
1977            DriveType::Optical => DriveMedia::optical_disk(Arc::new(AtapiScsiDisk::new(Arc::new(
1978                SimpleScsiDvd::new(Some(disk)),
1979            )))),
1980        };
1981
1982        let ide_device = IdeDevice::new(
1983            test_guest_mem,
1984            &mut ExternallyManagedPortIoIntercepts,
1985            [Some(media), None],
1986            [None, None],
1987            LineInterrupt::detached(),
1988            LineInterrupt::detached(),
1989        )
1990        .unwrap();
1991
1992        (ide_device, handle2, data, geometry)
1993    }
1994
1995    // IDE Test Host protocol functions
1996    fn get_status(ide_controller: &mut IdeDevice, dev_path: &IdePath) -> Status {
1997        let mut data = [0_u8; 1];
1998        ide_controller
1999            .io_read(
2000                io_port(IdeIoPort::PRI_STATUS_CMD, dev_path.channel.into()),
2001                &mut data,
2002            )
2003            .unwrap();
2004
2005        Status::from_bits(data[0])
2006    }
2007
2008    async fn check_status_loop(ide_device: &mut IdeDevice, dev_path: &IdePath) -> Status {
2009        // loop until device is not busy and is ready to transfer data.
2010        wait_for(ide_device, |ide_device| {
2011            let status: Status = get_status(ide_device, dev_path);
2012            (!status.bsy() && !status.drq()).then_some(status)
2013        })
2014        .await
2015    }
2016
2017    async fn check_command_ready(ide_device: &mut IdeDevice, dev_path: &IdePath) -> Status {
2018        // loop until device is not busy and is ready to transfer data.
2019        wait_for(ide_device, |ide_device| {
2020            let status: Status = get_status(ide_device, dev_path);
2021            (!status.bsy() && status.drdy()).then_some(status)
2022        })
2023        .await
2024    }
2025
2026    fn io_port(io_port: IdeIoPort, channel_idx: usize) -> u16 {
2027        if channel_idx == 0 {
2028            io_port.0
2029        } else {
2030            io_port.0 - IdeIoPort::PRI_DATA.0 + IdeIoPort::SEC_DATA.0
2031        }
2032    }
2033
2034    // Host: setup command parameters by writing to features, sector count/number,
2035    // cylinder low/high, dev/head registers
2036    fn write_command_params(
2037        controller: &mut IdeDevice,
2038        dev_path: &IdePath,
2039        sector: u32,
2040        sector_count: u8,
2041        addr: Addressing,
2042        geometry: &MediaGeometry,
2043    ) {
2044        let channel_idx: usize = dev_path.channel as usize;
2045
2046        let io_params = match addr {
2047            Addressing::Chs => {
2048                let sectors_per_track = geometry.sectors_per_track;
2049                let head_count = geometry.head_count;
2050
2051                let sector_num: u8 = ((sector % sectors_per_track) as u8) + 1;
2052                let cylinders: u16 = (sector / (head_count * sectors_per_track)) as u16;
2053                let cylinder_lsb: u8 = cylinders as u8;
2054                let cylinder_msb: u8 = (cylinders >> 8) as u8;
2055                let device_head: u8 = (sector / sectors_per_track % head_count) as u8;
2056
2057                CommandParams {
2058                    sector_count,
2059                    sector_num,
2060                    cylinder_lsb,
2061                    cylinder_msb,
2062                    device_head,
2063                }
2064            }
2065            Addressing::Lba28Bit => {
2066                let sector_num = sector as u8;
2067                let cylinder = (sector & 0x00FF_FF00) >> 8;
2068                let cylinder_lsb: u8 = cylinder as u8;
2069                let cylinder_msb: u8 = (cylinder >> 8) as u8;
2070                let device_head = DeviceHeadReg::new()
2071                    .with_head((sector >> 24) as u8)
2072                    .with_lba(true)
2073                    .into();
2074
2075                CommandParams {
2076                    sector_count,
2077                    sector_num,
2078                    cylinder_lsb,
2079                    cylinder_msb,
2080                    device_head,
2081                }
2082            }
2083            Addressing::Lba48Bit => todo!(),
2084        };
2085
2086        controller
2087            .io_write(
2088                io_port(IdeIoPort::PRI_SECTOR_COUNT, channel_idx),
2089                &[io_params.sector_count],
2090            )
2091            .unwrap();
2092        controller
2093            .io_write(
2094                io_port(IdeIoPort::PRI_SECTOR_NUM, channel_idx),
2095                &[io_params.sector_num],
2096            )
2097            .unwrap();
2098        controller
2099            .io_write(
2100                io_port(IdeIoPort::PRI_CYLINDER_LSB, channel_idx),
2101                &[io_params.cylinder_lsb],
2102            )
2103            .unwrap();
2104        controller
2105            .io_write(
2106                io_port(IdeIoPort::PRI_CYLINDER_MSB, channel_idx),
2107                &[io_params.cylinder_msb],
2108            )
2109            .unwrap();
2110        controller
2111            .io_write(
2112                io_port(IdeIoPort::PRI_DEVICE_HEAD, channel_idx),
2113                &[io_params.device_head],
2114            )
2115            .unwrap();
2116    }
2117
2118    // Host: Execute device selection protocol
2119    async fn device_select(ide_controller: &mut IdeDevice, dev_path: &IdePath) {
2120        check_status_loop(ide_controller, dev_path).await;
2121
2122        let dev_idx: u8 = dev_path.drive;
2123        ide_controller
2124            .io_write(
2125                io_port(IdeIoPort::PRI_DEVICE_HEAD, dev_path.channel.into()),
2126                &[dev_idx],
2127            )
2128            .unwrap();
2129
2130        check_status_loop(ide_controller, dev_path).await;
2131    }
2132
2133    // Host: Write command code to command register, wait 400ns before reading status register
2134    fn execute_command(ide_controller: &mut IdeDevice, dev_path: &IdePath, command: u8) {
2135        ide_controller
2136            .io_write(
2137                io_port(IdeIoPort::PRI_STATUS_CMD, dev_path.channel.into()),
2138                &[command],
2139            )
2140            .unwrap();
2141    }
2142
2143    fn execute_soft_reset_command(ide_controller: &mut IdeDevice, dev_path: &IdePath, command: u8) {
2144        ide_controller
2145            .io_write(
2146                io_port(
2147                    IdeIoPort::PRI_ALT_STATUS_DEVICE_CTL,
2148                    dev_path.channel.into(),
2149                ),
2150                &[command],
2151            )
2152            .unwrap();
2153    }
2154
2155    fn get_dma_state(ide_controller: &mut IdeDevice, dev_path: &IdePath) -> bool {
2156        // Returns true if DMA state exists, false if None
2157        ide_controller.channels[dev_path.channel as usize]
2158            .bus_master_state
2159            .dma_state
2160            .is_some()
2161    }
2162
2163    fn prep_ide_channel(ide_controller: &mut IdeDevice, drive_type: DriveType, dev_path: &IdePath) {
2164        match drive_type {
2165            DriveType::Hard => {
2166                // SET MULTIPLE MODE - sets number of sectors per block to 128
2167                // this is needed when computing IO sector count for a read/write
2168                execute_command(ide_controller, dev_path, IdeCommand::SET_MULTI_BLOCK_MODE.0);
2169            }
2170            DriveType::Optical => {
2171                // Optical is a ATAPI (PACKET) drive and does not support the SET_MULTI_BLOCK_MODE command
2172            }
2173        }
2174    }
2175
2176    // Waits for a condition on the IDE device, polling the device until then.
2177    async fn wait_for<T>(
2178        ide_device: &mut IdeDevice,
2179        mut f: impl FnMut(&mut IdeDevice) -> Option<T>,
2180    ) -> T {
2181        poll_fn(|cx| {
2182            ide_device.poll_device(cx);
2183            let r = f(ide_device);
2184            if let Some(r) = r {
2185                Poll::Ready(r)
2186            } else {
2187                Poll::Pending
2188            }
2189        })
2190        .await
2191    }
2192
2193    // IDE Command Tests
2194    // Command: WRITE SECTOR(S)
2195    #[async_test]
2196    async fn write_sectors_test() {
2197        const START_SECTOR: u32 = 0;
2198        const SECTOR_COUNT: u8 = 4;
2199
2200        let dev_path = IdePath::default();
2201        let (mut ide_device, mut disk, _file_contents, geometry) =
2202            ide_test_setup(None, DriveType::Hard);
2203
2204        // select device [0,0] = primary channel, primary drive
2205        device_select(&mut ide_device, &dev_path).await;
2206        prep_ide_channel(&mut ide_device, DriveType::Hard, &dev_path);
2207
2208        // write to first 4 sectors
2209        write_command_params(
2210            &mut ide_device,
2211            &dev_path,
2212            START_SECTOR,
2213            SECTOR_COUNT,
2214            Addressing::Lba28Bit,
2215            &geometry,
2216        );
2217
2218        execute_command(&mut ide_device, &dev_path, IdeCommand::WRITE_SECTORS.0);
2219
2220        // drive status should contain DRQ as data is ready to be exchanged with host
2221        let status = get_status(&mut ide_device, &dev_path);
2222        assert!(status.drq() && !status.bsy());
2223
2224        // PIO - writes to data port
2225        let data = &[0xFF_u8; 2][..];
2226        for _ in 0..SECTOR_COUNT {
2227            let status = check_command_ready(&mut ide_device, &dev_path).await;
2228            assert!(status.drq());
2229            assert!(!status.err());
2230            for _ in 0..protocol::HARD_DRIVE_SECTOR_BYTES / 2 {
2231                ide_device.io_write(IdeIoPort::PRI_DATA.0, data).unwrap();
2232            }
2233        }
2234
2235        let status = check_command_ready(&mut ide_device, &dev_path).await;
2236        assert!(!status.err());
2237        assert!(!status.drq());
2238
2239        let buffer =
2240            &mut [0_u8; (protocol::HARD_DRIVE_SECTOR_BYTES * SECTOR_COUNT as u32) as usize][..];
2241        disk.read_exact(buffer).unwrap();
2242        for byte in buffer {
2243            assert_eq!(*byte, 0xFF);
2244        }
2245    }
2246
2247    #[async_test]
2248    async fn software_reset_test() {
2249        const START_SECTOR: u32 = 0;
2250        const SECTOR_COUNT: u8 = 4;
2251
2252        let dev_path = IdePath::default();
2253        let (mut ide_device, _disk, _file_contents, geometry) =
2254            ide_test_setup(None, DriveType::Hard);
2255
2256        // select device [0,0] = primary channel, primary drive
2257        device_select(&mut ide_device, &dev_path).await;
2258        prep_ide_channel(&mut ide_device, DriveType::Hard, &dev_path);
2259
2260        // write to first 4 sectors
2261        write_command_params(
2262            &mut ide_device,
2263            &dev_path,
2264            START_SECTOR,
2265            SECTOR_COUNT,
2266            Addressing::Lba28Bit,
2267            &geometry,
2268        );
2269
2270        execute_command(&mut ide_device, &dev_path, IdeCommand::WRITE_SECTORS.0);
2271        // drive status should contain DRQ as data is ready to be exchanged with host
2272        let status = get_status(&mut ide_device, &dev_path);
2273        assert!(status.drq() && !status.bsy());
2274
2275        execute_soft_reset_command(&mut ide_device, &dev_path, IdeCommand::SOFT_RESET.0);
2276        let status = get_status(&mut ide_device, &dev_path);
2277        assert!(status.bsy());
2278    }
2279
2280    // Command: READ SECTOR(S)
2281    #[async_test]
2282    async fn read_sectors_test() {
2283        const START_SECTOR: u32 = 0;
2284        const SECTOR_COUNT: u8 = 4;
2285
2286        let dev_path = IdePath::default();
2287        let (mut ide_device, _disk, file_contents, geometry) =
2288            ide_test_setup(None, DriveType::Hard);
2289
2290        // select device [0,0] = primary channel, primary drive
2291        device_select(&mut ide_device, &dev_path).await;
2292        prep_ide_channel(&mut ide_device, DriveType::Hard, &dev_path);
2293
2294        // read the first 4 sectors
2295        write_command_params(
2296            &mut ide_device,
2297            &dev_path,
2298            START_SECTOR,
2299            SECTOR_COUNT,
2300            Addressing::Lba28Bit,
2301            &geometry,
2302        );
2303
2304        // PIO - writes sectors to track cache buffer
2305        execute_command(&mut ide_device, &dev_path, IdeCommand::READ_SECTORS.0);
2306
2307        let status = check_command_ready(&mut ide_device, &dev_path).await;
2308        assert!(status.drq());
2309        assert!(!status.err());
2310
2311        // PIO - reads data from track cache buffer
2312        let content_bytes = file_contents.as_bytes();
2313        for sector in 0..SECTOR_COUNT {
2314            let status = check_command_ready(&mut ide_device, &dev_path).await;
2315            assert!(status.drq());
2316            assert!(!status.err());
2317            for word in 0..protocol::HARD_DRIVE_SECTOR_BYTES / 2 {
2318                let data = &mut [0, 0][..];
2319                ide_device.io_read(IdeIoPort::PRI_DATA.0, data).unwrap();
2320
2321                let i = sector as usize * protocol::HARD_DRIVE_SECTOR_BYTES as usize / 2
2322                    + word as usize;
2323                assert_eq!(data[0], content_bytes[i * 2]);
2324                assert_eq!(data[1], content_bytes[i * 2 + 1]);
2325            }
2326        }
2327    }
2328
2329    // Command: READ SECTOR(S) - enlightened
2330    async fn enlightened_cmd_test(drive_type: DriveType) {
2331        const SECTOR_COUNT: u16 = 4;
2332        const BYTE_COUNT: u16 = SECTOR_COUNT * protocol::HARD_DRIVE_SECTOR_BYTES as u16;
2333
2334        let test_guest_mem = GuestMemory::allocate(16384);
2335
2336        let table_gpa = 0x1000;
2337        let data_gpa = 0x2000;
2338        test_guest_mem
2339            .write_plain(
2340                table_gpa,
2341                &BusMasterDmaDesc {
2342                    mem_physical_base: data_gpa,
2343                    byte_count: BYTE_COUNT,
2344                    unused: 0,
2345                    end_of_table: 0x80,
2346                },
2347            )
2348            .unwrap();
2349
2350        let (data_buffer, byte_count) = match drive_type {
2351            DriveType::Hard => (table_gpa as u32, 0),
2352            DriveType::Optical => (data_gpa, BYTE_COUNT.into()),
2353        };
2354
2355        let eint13_command = protocol::EnlightenedInt13Command {
2356            command: IdeCommand::READ_DMA_EXT,
2357            device_head: DeviceHeadReg::new().with_lba(true),
2358            flags: 0,
2359            result_status: 0,
2360            lba_low: 0,
2361            lba_high: 0,
2362            block_count: SECTOR_COUNT,
2363            byte_count,
2364            data_buffer,
2365            skip_bytes_head: 0,
2366            skip_bytes_tail: 0,
2367        };
2368        test_guest_mem.write_plain(0, &eint13_command).unwrap();
2369
2370        let dev_path = IdePath::default();
2371        let (mut ide_device, _disk, file_contents, _geometry) =
2372            ide_test_setup(Some(test_guest_mem.clone()), drive_type);
2373
2374        // select device [0,0] = primary channel, primary drive
2375        device_select(&mut ide_device, &dev_path).await;
2376        prep_ide_channel(&mut ide_device, drive_type, &dev_path);
2377
2378        // READ SECTORS - enlightened
2379        let r = ide_device.io_write(IdeIoPort::PRI_ENLIGHTENED.0, 0_u32.as_bytes()); // read from gpa 0
2380
2381        match r {
2382            IoResult::Defer(mut deferred) => {
2383                poll_fn(|cx| {
2384                    ide_device.poll_device(cx);
2385                    deferred.poll_write(cx)
2386                })
2387                .await
2388                .unwrap();
2389            }
2390            _ => panic!("{:?}", r),
2391        }
2392
2393        let mut buffer = vec![0u8; BYTE_COUNT as usize];
2394        test_guest_mem
2395            .read_at(data_gpa.into(), &mut buffer)
2396            .unwrap();
2397        assert_eq!(buffer, file_contents.as_bytes()[..buffer.len()]);
2398    }
2399
2400    // Command: READ SECTOR(S) - enlightened
2401    #[async_test]
2402    async fn enlightened_cd_cmd_test() {
2403        enlightened_cmd_test(DriveType::Optical).await
2404    }
2405
2406    #[async_test]
2407    async fn enlightened_hdd_cmd_test() {
2408        enlightened_cmd_test(DriveType::Hard).await
2409    }
2410
2411    // Command: READ SECTOR(S) - enlightened
2412    // However, provide incomplete PRD table
2413    #[async_test]
2414    async fn enlightened_cmd_test_incomplete_prd() {
2415        const SECTOR_COUNT: u16 = 8;
2416        const BYTE_COUNT: u16 = SECTOR_COUNT * protocol::HARD_DRIVE_SECTOR_BYTES as u16;
2417
2418        let test_guest_mem = GuestMemory::allocate(16384);
2419
2420        let table_gpa = 0x1000;
2421        let data_gpa = 0x2000;
2422        test_guest_mem
2423            .write_plain(
2424                table_gpa,
2425                &BusMasterDmaDesc {
2426                    mem_physical_base: data_gpa,
2427                    byte_count: BYTE_COUNT / 2,
2428                    unused: 0,
2429                    end_of_table: 0x80, // Mark end before second PRD
2430                },
2431            )
2432            .unwrap();
2433        test_guest_mem
2434            .write_plain(
2435                table_gpa + size_of::<BusMasterDmaDesc>() as u64,
2436                &BusMasterDmaDesc {
2437                    mem_physical_base: data_gpa,
2438                    byte_count: BYTE_COUNT / 2,
2439                    unused: 0,
2440                    end_of_table: 0x80,
2441                },
2442            )
2443            .unwrap();
2444
2445        let data_buffer = table_gpa as u32;
2446        let byte_count = 0;
2447
2448        let eint13_command = protocol::EnlightenedInt13Command {
2449            command: IdeCommand::READ_DMA_EXT,
2450            device_head: DeviceHeadReg::new().with_lba(true),
2451            flags: 0,
2452            result_status: 0,
2453            lba_low: 0,
2454            lba_high: 0,
2455            block_count: SECTOR_COUNT,
2456            byte_count,
2457            data_buffer,
2458            skip_bytes_head: 0,
2459            skip_bytes_tail: 0,
2460        };
2461        test_guest_mem.write_plain(0, &eint13_command).unwrap();
2462
2463        let dev_path = IdePath::default();
2464        let (mut ide_device, _disk, file_contents, _geometry) =
2465            ide_test_setup(Some(test_guest_mem.clone()), DriveType::Hard);
2466
2467        // select device [0,0] = primary channel, primary drive
2468        device_select(&mut ide_device, &dev_path).await;
2469        prep_ide_channel(&mut ide_device, DriveType::Hard, &dev_path);
2470
2471        // READ SECTORS - enlightened
2472        let r = ide_device.io_write(IdeIoPort::PRI_ENLIGHTENED.0, 0_u32.as_bytes()); // read from gpa 0
2473
2474        match r {
2475            IoResult::Defer(mut deferred) => {
2476                poll_fn(|cx| {
2477                    ide_device.poll_device(cx);
2478                    deferred.poll_write(cx)
2479                })
2480                .await
2481                .unwrap();
2482            }
2483            _ => panic!("{:?}", r),
2484        }
2485
2486        let mut buffer = vec![0u8; BYTE_COUNT as usize / 2];
2487        test_guest_mem
2488            .read_at(data_gpa.into(), &mut buffer)
2489            .unwrap();
2490        assert_eq!(buffer, file_contents.as_bytes()[..buffer.len()]);
2491    }
2492
2493    #[async_test]
2494    async fn enlightened_cmd_test_dma_boundary_overflow() {
2495        // Tests a DMA descriptor that starts at a valid address but overflows into invalid memory
2496        // Guest memory: 0x0000-0x3FFF (16KB)
2497        // Descriptor: starts at 0x3000, requests 8KB -> overflows to 0x5000 (invalid)
2498
2499        const SECTOR_COUNT: u16 = 16; // 16 sectors = 8KB
2500        const BYTE_COUNT: u16 = SECTOR_COUNT * protocol::HARD_DRIVE_SECTOR_BYTES as u16;
2501
2502        let test_guest_mem = GuestMemory::allocate(16384);
2503
2504        let table_gpa = 0x1000;
2505        let data_gpa = 0x3000; // Valid start, but will overflow
2506        test_guest_mem
2507            .write_plain(
2508                table_gpa,
2509                &BusMasterDmaDesc {
2510                    mem_physical_base: data_gpa,
2511                    byte_count: BYTE_COUNT, // 8KB - overflows beyond 0x3FFF
2512                    unused: 0,
2513                    end_of_table: 0x80,
2514                },
2515            )
2516            .unwrap();
2517
2518        let data_buffer = table_gpa as u32;
2519        let byte_count = 0;
2520
2521        let eint13_command = protocol::EnlightenedInt13Command {
2522            command: IdeCommand::READ_DMA_ALT,
2523            device_head: DeviceHeadReg::new().with_lba(true),
2524            flags: 0,
2525            result_status: 0,
2526            lba_low: 0,
2527            lba_high: 0,
2528            block_count: SECTOR_COUNT,
2529            byte_count,
2530            data_buffer,
2531            skip_bytes_head: 0,
2532            skip_bytes_tail: 0,
2533        };
2534        test_guest_mem.write_plain(0, &eint13_command).unwrap();
2535
2536        let dev_path = IdePath::default();
2537        let (mut ide_device, _disk, _file_contents, _geometry) =
2538            ide_test_setup(Some(test_guest_mem.clone()), DriveType::Hard);
2539
2540        device_select(&mut ide_device, &dev_path).await;
2541        prep_ide_channel(&mut ide_device, DriveType::Hard, &dev_path);
2542
2543        let r = ide_device.io_write(IdeIoPort::PRI_ENLIGHTENED.0, 0_u32.as_bytes());
2544
2545        match r {
2546            IoResult::Defer(mut deferred) => {
2547                poll_fn(|cx| {
2548                    ide_device.poll_device(cx);
2549                    deferred.poll_write(cx)
2550                })
2551                .await
2552                .unwrap();
2553            }
2554            _ => panic!("{:?}", r),
2555        }
2556
2557        let dma_state = get_dma_state(&mut ide_device, &dev_path);
2558        assert!(
2559            !dma_state,
2560            "Expected DMA state cleared - transfer from 0x{:x} with {} bytes overflows valid range 0x0-0x3FFF",
2561            data_gpa, BYTE_COUNT
2562        );
2563    }
2564
2565    #[async_test]
2566    async fn enlightened_cmd_test_dma_exact_boundary() {
2567        // Tests a DMA descriptor that ends exactly at the boundary of valid memory
2568        // Guest memory: 0x0000-0x3FFF (16KB)
2569        // Descriptor: starts at 0x3E00, requests 512 bytes -> ends at 0x4000 (just past boundary)
2570
2571        const BYTE_COUNT: u16 = 512;
2572
2573        let test_guest_mem = GuestMemory::allocate(16384);
2574
2575        let table_gpa = 0x1000;
2576        let data_gpa = 0x3E00; // 16KB - 512 bytes
2577        test_guest_mem
2578            .write_plain(
2579                table_gpa,
2580                &BusMasterDmaDesc {
2581                    mem_physical_base: data_gpa,
2582                    byte_count: BYTE_COUNT, // Ends exactly at boundary + 1
2583                    unused: 0,
2584                    end_of_table: 0x80,
2585                },
2586            )
2587            .unwrap();
2588
2589        let data_buffer = table_gpa as u32;
2590        let byte_count = 0;
2591
2592        let eint13_command = protocol::EnlightenedInt13Command {
2593            command: IdeCommand::READ_DMA_ALT,
2594            device_head: DeviceHeadReg::new().with_lba(true),
2595            flags: 0,
2596            result_status: 0,
2597            lba_low: 0,
2598            lba_high: 0,
2599            block_count: 1,
2600            byte_count,
2601            data_buffer,
2602            skip_bytes_head: 0,
2603            skip_bytes_tail: 0,
2604        };
2605        test_guest_mem.write_plain(0, &eint13_command).unwrap();
2606
2607        let dev_path = IdePath::default();
2608        let (mut ide_device, _disk, _file_contents, _geometry) =
2609            ide_test_setup(Some(test_guest_mem.clone()), DriveType::Hard);
2610
2611        device_select(&mut ide_device, &dev_path).await;
2612        prep_ide_channel(&mut ide_device, DriveType::Hard, &dev_path);
2613
2614        let r = ide_device.io_write(IdeIoPort::PRI_ENLIGHTENED.0, 0_u32.as_bytes());
2615
2616        match r {
2617            IoResult::Defer(mut deferred) => {
2618                poll_fn(|cx| {
2619                    ide_device.poll_device(cx);
2620                    deferred.poll_write(cx)
2621                })
2622                .await
2623                .unwrap();
2624            }
2625            _ => panic!("{:?}", r),
2626        }
2627
2628        let dma_state = get_dma_state(&mut ide_device, &dev_path);
2629        assert!(
2630            !dma_state,
2631            "Expected DMA state cleared - transfer ending at 0x{:x} exceeds valid range",
2632            data_gpa + BYTE_COUNT as u32
2633        );
2634    }
2635
2636    #[async_test]
2637    async fn enlightened_cmd_test_dma_integer_overflow() {
2638        // Tests a DMA descriptor with byte_count that could cause integer overflow
2639        // Guest memory: 0x0000-0x3FFF (16KB)
2640        // Descriptor: mem_physical_base = 0x2000, byte_count = 0xFFFF (64KB)
2641        // The checked_add should catch this overflow
2642
2643        let test_guest_mem = GuestMemory::allocate(16384);
2644
2645        let table_gpa = 0x1000;
2646        let data_gpa = 0x2000;
2647        test_guest_mem
2648            .write_plain(
2649                table_gpa,
2650                &BusMasterDmaDesc {
2651                    mem_physical_base: data_gpa,
2652                    byte_count: 0xFFFF, // Maximum 16-bit value - would overflow
2653                    unused: 0,
2654                    end_of_table: 0x80,
2655                },
2656            )
2657            .unwrap();
2658
2659        let data_buffer = table_gpa as u32;
2660        let byte_count = 0;
2661
2662        let eint13_command = protocol::EnlightenedInt13Command {
2663            command: IdeCommand::READ_DMA_ALT,
2664            device_head: DeviceHeadReg::new().with_lba(true),
2665            flags: 0,
2666            result_status: 0,
2667            lba_low: 0,
2668            lba_high: 0,
2669            block_count: 128, // Arbitrary
2670            byte_count,
2671            data_buffer,
2672            skip_bytes_head: 0,
2673            skip_bytes_tail: 0,
2674        };
2675        test_guest_mem.write_plain(0, &eint13_command).unwrap();
2676
2677        let dev_path = IdePath::default();
2678        let (mut ide_device, _disk, _file_contents, _geometry) =
2679            ide_test_setup(Some(test_guest_mem.clone()), DriveType::Hard);
2680
2681        device_select(&mut ide_device, &dev_path).await;
2682        prep_ide_channel(&mut ide_device, DriveType::Hard, &dev_path);
2683
2684        let r = ide_device.io_write(IdeIoPort::PRI_ENLIGHTENED.0, 0_u32.as_bytes());
2685
2686        match r {
2687            IoResult::Defer(mut deferred) => {
2688                poll_fn(|cx| {
2689                    ide_device.poll_device(cx);
2690                    deferred.poll_write(cx)
2691                })
2692                .await
2693                .unwrap();
2694            }
2695            _ => panic!("{:?}", r),
2696        }
2697
2698        let dma_state = get_dma_state(&mut ide_device, &dev_path);
2699        assert!(
2700            !dma_state,
2701            "Expected DMA state cleared - large byte_count 0xFFFF should be rejected"
2702        );
2703    }
2704
2705    #[async_test]
2706    async fn enlightened_cmd_test_dma_u32_max_overflow() {
2707        // Tests a DMA descriptor where mem_physical_base + transfer_bytes_left overflows u32
2708        // This tests the checked_add protection against u32 overflow
2709
2710        let test_guest_mem = GuestMemory::allocate(16384);
2711
2712        let table_gpa = 0x1000;
2713        let data_gpa = 0xFFFF_F000_u32; // Near u32::MAX
2714        test_guest_mem
2715            .write_plain(
2716                table_gpa,
2717                &BusMasterDmaDesc {
2718                    mem_physical_base: data_gpa,
2719                    byte_count: 0x2000, // Would overflow past u32::MAX
2720                    unused: 0,
2721                    end_of_table: 0x80,
2722                },
2723            )
2724            .unwrap();
2725
2726        let data_buffer = table_gpa as u32;
2727        let byte_count = 0;
2728
2729        let eint13_command = protocol::EnlightenedInt13Command {
2730            command: IdeCommand::READ_DMA_ALT,
2731            device_head: DeviceHeadReg::new().with_lba(true),
2732            flags: 0,
2733            result_status: 0,
2734            lba_low: 0,
2735            lba_high: 0,
2736            block_count: 16,
2737            byte_count,
2738            data_buffer,
2739            skip_bytes_head: 0,
2740            skip_bytes_tail: 0,
2741        };
2742        test_guest_mem.write_plain(0, &eint13_command).unwrap();
2743
2744        let dev_path = IdePath::default();
2745        let (mut ide_device, _disk, _file_contents, _geometry) =
2746            ide_test_setup(Some(test_guest_mem.clone()), DriveType::Hard);
2747
2748        device_select(&mut ide_device, &dev_path).await;
2749        prep_ide_channel(&mut ide_device, DriveType::Hard, &dev_path);
2750
2751        let r = ide_device.io_write(IdeIoPort::PRI_ENLIGHTENED.0, 0_u32.as_bytes());
2752
2753        match r {
2754            IoResult::Defer(mut deferred) => {
2755                poll_fn(|cx| {
2756                    ide_device.poll_device(cx);
2757                    deferred.poll_write(cx)
2758                })
2759                .await
2760                .unwrap();
2761            }
2762            _ => panic!("{:?}", r),
2763        }
2764
2765        let dma_state = get_dma_state(&mut ide_device, &dev_path);
2766        assert!(
2767            !dma_state,
2768            "Expected DMA state cleared - checked_add should catch u32 overflow from 0x{:x} + 0x2000",
2769            data_gpa
2770        );
2771    }
2772
2773    #[async_test]
2774    async fn enlightened_cmd_test_dma_zero_byte_count() {
2775        // Tests a DMA descriptor with byte_count = 0, which should be treated as 64KB
2776        // This could overflow if the base address is high enough
2777
2778        let test_guest_mem = GuestMemory::allocate(16384);
2779
2780        let table_gpa = 0x1000;
2781        let data_gpa = 0x1000;
2782        test_guest_mem
2783            .write_plain(
2784                table_gpa,
2785                &BusMasterDmaDesc {
2786                    mem_physical_base: data_gpa,
2787                    byte_count: 0, // Treated as 64KB (0x10000)
2788                    unused: 0,
2789                    end_of_table: 0x80,
2790                },
2791            )
2792            .unwrap();
2793
2794        let data_buffer = table_gpa as u32;
2795        let byte_count = 0;
2796
2797        let eint13_command = protocol::EnlightenedInt13Command {
2798            command: IdeCommand::READ_DMA_ALT,
2799            device_head: DeviceHeadReg::new().with_lba(true),
2800            flags: 0,
2801            result_status: 0,
2802            lba_low: 0,
2803            lba_high: 0,
2804            block_count: 128, // 64KB
2805            byte_count,
2806            data_buffer,
2807            skip_bytes_head: 0,
2808            skip_bytes_tail: 0,
2809        };
2810        test_guest_mem.write_plain(0, &eint13_command).unwrap();
2811
2812        let dev_path = IdePath::default();
2813        let (mut ide_device, _disk, _file_contents, _geometry) =
2814            ide_test_setup(Some(test_guest_mem.clone()), DriveType::Hard);
2815
2816        device_select(&mut ide_device, &dev_path).await;
2817        prep_ide_channel(&mut ide_device, DriveType::Hard, &dev_path);
2818
2819        let r = ide_device.io_write(IdeIoPort::PRI_ENLIGHTENED.0, 0_u32.as_bytes());
2820
2821        match r {
2822            IoResult::Defer(mut deferred) => {
2823                poll_fn(|cx| {
2824                    ide_device.poll_device(cx);
2825                    deferred.poll_write(cx)
2826                })
2827                .await
2828                .unwrap();
2829            }
2830            _ => panic!("{:?}", r),
2831        }
2832
2833        let dma_state = get_dma_state(&mut ide_device, &dev_path);
2834        assert!(
2835            !dma_state,
2836            "Expected DMA state cleared - byte_count=0 implies 64KB which exceeds guest memory"
2837        );
2838    }
2839
2840    /// Build the 12-byte ATAPI CDB for PREVENT ALLOW MEDIUM REMOVAL.
2841    fn medium_removal_cdb(prevent: bool) -> [u8; 12] {
2842        let cdb = scsi::CdbMediaRemoval {
2843            operation_code: ScsiOp::MEDIUM_REMOVAL,
2844            lun: 0,
2845            reserved: [0; 2],
2846            flags: scsi::MediaRemovalFlags::new()
2847                .with_prevent(prevent)
2848                .with_persistent(prevent),
2849        };
2850        let mut command = [0; 12];
2851        command[..cdb.as_bytes().len()].copy_from_slice(cdb.as_bytes());
2852        command
2853    }
2854
2855    /// Build a 12-byte ATAPI CDB the device does not implement, which is refused
2856    /// with ILLEGAL_COMMAND sense whatever else is going on.
2857    fn unsupported_cdb() -> [u8; 12] {
2858        let mut command = [0; 12];
2859        command[0] = ScsiOp::WRITE.0;
2860        command
2861    }
2862
2863    /// Build the 12-byte ATAPI CDB for START STOP UNIT with LOEJ set.
2864    fn eject_cdb() -> [u8; 12] {
2865        let cdb = scsi::StartStop {
2866            operation_code: ScsiOp::START_STOP_UNIT,
2867            immediate: 0,
2868            reserved2: [0; 2],
2869            flag: scsi::StartStopFlags::new()
2870                .with_start(false)
2871                .with_load_eject(true),
2872            control: 0,
2873        };
2874        let mut command = [0; 12];
2875        command[..cdb.as_bytes().len()].copy_from_slice(cdb.as_bytes());
2876        command
2877    }
2878
2879    /// Run one ATAPI packet command through the register interface, returning the
2880    /// status the drive settles on.
2881    async fn atapi_packet_command(
2882        ide_device: &mut IdeDevice,
2883        dev_path: &IdePath,
2884        cdb: &[u8; 12],
2885    ) -> Status {
2886        execute_command(ide_device, dev_path, IdeCommand::PACKET_COMMAND.0);
2887        let status = check_command_ready(ide_device, dev_path).await;
2888        assert!(status.drq(), "the drive should be waiting for the CDB");
2889        for chunk in cdb.chunks(2) {
2890            ide_device.io_write(IdeIoPort::PRI_DATA.0, chunk).unwrap();
2891        }
2892        check_command_ready(ide_device, dev_path).await
2893    }
2894
2895    /// A drive reset ends the nexus for an ATAPI drive too.
2896    ///
2897    /// The tray lock is scoped to the initiator that set it, so a reset has to drop
2898    /// it along with the sense slot and any queued medium event. Without that, the
2899    /// next initiator's first eject is refused with MEDIUM_REMOVAL_PREVENTED by a
2900    /// decision it never made.
2901    ///
2902    /// The first eject is the control: without it a pass would only show that
2903    /// ejecting works, not that the reset is what made it work.
2904    #[async_test]
2905    async fn atapi_reset_ends_the_nexus() {
2906        let dev_path = IdePath::default();
2907        let (mut ide_device, _disk, _file_contents, _geometry) =
2908            ide_test_setup(None, DriveType::Optical);
2909
2910        device_select(&mut ide_device, &dev_path).await;
2911
2912        let status =
2913            atapi_packet_command(&mut ide_device, &dev_path, &medium_removal_cdb(true)).await;
2914        assert!(!status.err(), "locking the tray should succeed");
2915
2916        // Locked, so this one must be refused.
2917        let status = atapi_packet_command(&mut ide_device, &dev_path, &eject_cdb()).await;
2918        assert!(status.err(), "a locked tray must refuse the eject");
2919
2920        ide_device.reset().await;
2921        device_select(&mut ide_device, &dev_path).await;
2922
2923        // Same command, same drive, same media: it succeeds now only because the
2924        // lock did not survive the reset.
2925        let status = atapi_packet_command(&mut ide_device, &dev_path, &eject_cdb()).await;
2926        assert!(!status.err(), "the tray lock outlived the drive reset");
2927    }
2928
2929    /// A reset must not leave an ATAPI command in flight.
2930    ///
2931    /// The nexus state is cleared on the drive, but the sense slot is written by
2932    /// `AtapiScsiDisk::execute_scsi` when its future COMPLETES, which is after the
2933    /// inner command is awaited. An I/O the reset leaves behind therefore finishes
2934    /// afterwards and writes the previous initiator's result into the slot the
2935    /// reset just emptied. `HardDrive::reset` already drops its I/O for the same
2936    /// reason.
2937    ///
2938    /// Writing the CDB spawns the I/O synchronously and nothing polls it until
2939    /// `poll_device` runs, which is what lets the test hold one across the reset.
2940    #[async_test]
2941    async fn atapi_reset_drops_the_command_left_in_flight() {
2942        let dev_path = IdePath::default();
2943        let (mut ide_device, _disk, _file_contents, _geometry) =
2944            ide_test_setup(None, DriveType::Optical);
2945
2946        device_select(&mut ide_device, &dev_path).await;
2947
2948        // Control: this command is refused whatever the nexus state holds, so the
2949        // assertion at the end cannot pass merely because the reset made it
2950        // succeed - which is what an eject would have done once the tray unlocked.
2951        let status = atapi_packet_command(&mut ide_device, &dev_path, &unsupported_cdb()).await;
2952        assert!(status.err(), "an unsupported command must be refused");
2953
2954        // Start the same command again and stop before it completes.
2955        execute_command(&mut ide_device, &dev_path, IdeCommand::PACKET_COMMAND.0);
2956        let status = check_command_ready(&mut ide_device, &dev_path).await;
2957        assert!(status.drq(), "the drive should be waiting for the CDB");
2958        for chunk in unsupported_cdb().chunks(2) {
2959            ide_device.io_write(IdeIoPort::PRI_DATA.0, chunk).unwrap();
2960        }
2961
2962        ide_device.reset().await;
2963
2964        // Give anything the reset left behind a chance to finish.
2965        poll_fn(|cx| {
2966            ide_device.poll_device(cx);
2967            Poll::Ready(())
2968        })
2969        .await;
2970
2971        let status = get_status(&mut ide_device, &dev_path);
2972        assert!(
2973            !status.err(),
2974            "a command left in flight by the reset completed afterwards"
2975        );
2976    }
2977
2978    /// The ATA DEVICE RESET command ends the nexus as well.
2979    ///
2980    /// It takes its own path (`handle_soft_reset`) and never reaches the drive
2981    /// reset above, so covering only that one would leave the command a guest
2982    /// actually issues after an error still carrying the previous lock.
2983    #[async_test]
2984    async fn atapi_device_reset_command_ends_the_nexus() {
2985        let dev_path = IdePath::default();
2986        let (mut ide_device, _disk, _file_contents, _geometry) =
2987            ide_test_setup(None, DriveType::Optical);
2988
2989        device_select(&mut ide_device, &dev_path).await;
2990
2991        let status =
2992            atapi_packet_command(&mut ide_device, &dev_path, &medium_removal_cdb(true)).await;
2993        assert!(!status.err(), "locking the tray should succeed");
2994
2995        let status = atapi_packet_command(&mut ide_device, &dev_path, &eject_cdb()).await;
2996        assert!(status.err(), "a locked tray must refuse the eject");
2997
2998        // DEVICE RESET leaves the status register at zero (ATA8-ACS3 "Normal
2999        // Outputs"), so there is no ready state to wait for here; the PACKET
3000        // command below sets DRDY again on its own.
3001        execute_command(&mut ide_device, &dev_path, IdeCommand::DEVICE_RESET.0);
3002
3003        let status = atapi_packet_command(&mut ide_device, &dev_path, &eject_cdb()).await;
3004        assert!(
3005            !status.err(),
3006            "the tray lock outlived the DEVICE RESET command"
3007        );
3008    }
3009
3010    /// A software reset (SRST through the device control register) is the path a
3011    /// guest driver takes, so it is pinned separately from the two above.
3012    #[async_test]
3013    async fn atapi_software_reset_ends_the_nexus() {
3014        let dev_path = IdePath::default();
3015        let (mut ide_device, _disk, _file_contents, _geometry) =
3016            ide_test_setup(None, DriveType::Optical);
3017
3018        device_select(&mut ide_device, &dev_path).await;
3019
3020        let status =
3021            atapi_packet_command(&mut ide_device, &dev_path, &medium_removal_cdb(true)).await;
3022        assert!(!status.err(), "locking the tray should succeed");
3023
3024        let status = atapi_packet_command(&mut ide_device, &dev_path, &eject_cdb()).await;
3025        assert!(status.err(), "a locked tray must refuse the eject");
3026
3027        execute_soft_reset_command(&mut ide_device, &dev_path, IdeCommand::SOFT_RESET.0);
3028
3029        let status = atapi_packet_command(&mut ide_device, &dev_path, &eject_cdb()).await;
3030        assert!(!status.err(), "the tray lock outlived the software reset");
3031    }
3032
3033    #[async_test]
3034    async fn identify_test_cd() {
3035        let dev_path = IdePath::default();
3036        let (mut ide_device, _disk, _file_contents, _geometry) =
3037            ide_test_setup(None, DriveType::Optical);
3038
3039        // select device [0,0] = primary channel, primary drive
3040        device_select(&mut ide_device, &dev_path).await;
3041        prep_ide_channel(&mut ide_device, DriveType::Optical, &dev_path);
3042
3043        // PIO - writes sectors to track cache buffer
3044        execute_command(
3045            &mut ide_device,
3046            &dev_path,
3047            IdeCommand::IDENTIFY_PACKET_DEVICE.0,
3048        );
3049
3050        let status = check_command_ready(&mut ide_device, &dev_path).await;
3051        assert!(status.drq());
3052        assert!(!status.err());
3053
3054        // PIO - reads data from track cache buffer
3055        let data = &mut [0_u8; protocol::IDENTIFY_DEVICE_BYTES];
3056        ide_device.io_read(IdeIoPort::PRI_DATA.0, data).unwrap();
3057        let features = protocol::IdeFeatures::read_from_prefix(&data[..])
3058            .unwrap()
3059            .0; // TODO: zerocopy: use-rest-of-range (https://github.com/microsoft/openvmm/issues/759)
3060        let ex_features = protocol::IdeFeatures {
3061            config_bits: 0x85C0,
3062            serial_no: *b"                    ",
3063            buffer_size: 0x0080,
3064            firmware_revision: *b"        ",
3065            model_number: "iVtrau lDC                              ".as_bytes()[..]
3066                .try_into()
3067                .unwrap(),
3068            capabilities: 0x0300,
3069            pio_cycle_times: 0x0200,       // indicate fast I/O
3070            dma_cycle_times: 0x0200,       // indicate fast I/O
3071            new_words_valid_flags: 0x0003, // indicate next words are valid
3072            multi_sector_capabilities: 0x0100_u16 | protocol::MAX_SECTORS_MULT_TRANSFER_DEFAULT,
3073            single_word_dma_mode: 0x0007, // support up to mode 3, no mode active
3074            multi_word_dma_mode: 0x0407,  // support up to mode 3, mode 3 active
3075            enhanced_pio_mode: 0x0003,    // PIO mode 3 and 4 supported
3076            min_multi_dma_time: 0x0078,
3077            recommended_multi_dma_time: 0x0078,
3078            min_pio_cycle_time_no_flow: 0x01FC, // Taken from a real CD device
3079            min_pio_cycle_time_flow: 0x00B4,    // Taken from a real CD device
3080            ..FromZeros::new_zeroed()
3081        };
3082        assert_eq!(features.as_bytes(), ex_features.as_bytes());
3083    }
3084
3085    #[async_test]
3086    async fn identify_test_hdd() {
3087        let dev_path = IdePath::default();
3088        let (mut ide_device, _disk, _file_contents, geometry) =
3089            ide_test_setup(None, DriveType::Hard);
3090        // select device [0,0] = primary channel, primary drive
3091        device_select(&mut ide_device, &dev_path).await;
3092        prep_ide_channel(&mut ide_device, DriveType::Hard, &dev_path);
3093        // PIO - writes sectors to track cache buffer
3094        execute_command(&mut ide_device, &dev_path, IdeCommand::IDENTIFY_DEVICE.0);
3095
3096        let status = check_command_ready(&mut ide_device, &dev_path).await;
3097        assert!(status.drq());
3098        assert!(!status.err());
3099
3100        // PIO - reads data from track cache buffer
3101        let data = &mut [0_u8; protocol::IDENTIFY_DEVICE_BYTES];
3102        ide_device.io_read(IdeIoPort::PRI_DATA.0, data).unwrap();
3103        let features = protocol::IdeFeatures::read_from_prefix(&data[..])
3104            .unwrap()
3105            .0; // TODO: zerocopy: use-rest-of-range (https://github.com/microsoft/openvmm/issues/759)
3106
3107        let total_chs_sectors: u32 =
3108            geometry.sectors_per_track * geometry.cylinder_count * geometry.head_count;
3109        let (cylinders, heads, sectors_per_track) = if total_chs_sectors < protocol::MAX_CHS_SECTORS
3110        {
3111            (
3112                geometry.cylinder_count as u16,
3113                geometry.head_count as u16,
3114                geometry.sectors_per_track as u16,
3115            )
3116        } else {
3117            (0x3FFF, 16, 63)
3118        };
3119
3120        let firmware_revision = if dev_path.channel == 0 {
3121            ".1.1 0  "
3122        } else {
3123            ".1.1 1  "
3124        }
3125        .as_bytes()[..]
3126            .try_into()
3127            .unwrap();
3128
3129        let user_addressable_sectors =
3130            if geometry.total_sectors > (protocol::LBA_28BIT_MAX_SECTORS as u64) {
3131                protocol::LBA_28BIT_MAX_SECTORS
3132            } else {
3133                geometry.total_sectors as u32
3134            };
3135
3136        let ex_features = protocol::IdeFeatures {
3137            config_bits: 0x045A,
3138            cylinders,
3139            heads,
3140            unformatted_sectors_per_track: (protocol::HARD_DRIVE_SECTOR_BYTES
3141                * geometry.sectors_per_track) as u16,
3142            unformatted_bytes_per_sector: protocol::HARD_DRIVE_SECTOR_BYTES as u16,
3143            sectors_per_track,
3144            compact_flash: [0xABCD, 0xDCBA],
3145            vendor0: 0x0123,
3146            serial_no: *b"                    ",
3147            buffer_type: 3,
3148            buffer_size: 0x0080,
3149            firmware_revision,
3150            model_number: "iVtrau lDH                              ".as_bytes()[..]
3151                .try_into()
3152                .unwrap(),
3153            max_sectors_mult_transfer: (0x8000 | protocol::MAX_SECTORS_MULT_TRANSFER_DEFAULT),
3154            capabilities: 0x0F00,          // supports Dma, IORDY, LBA
3155            pio_cycle_times: 0x0200,       // indicate fast I/O
3156            dma_cycle_times: 0x0200,       // indicate fast I/O
3157            new_words_valid_flags: 0x0003, // indicate next words are valid
3158            log_cylinders: geometry.cylinder_count as u16,
3159            log_heads: geometry.head_count as u16,
3160            log_sectors_per_track: geometry.sectors_per_track as u16,
3161            log_total_sectors: total_chs_sectors.into(),
3162            multi_sector_capabilities: 0x0100_u16 | protocol::MAX_SECTORS_MULT_TRANSFER_DEFAULT,
3163            user_addressable_sectors: user_addressable_sectors.into(),
3164            single_word_dma_mode: 0x0007, // support up to mode 3, no mode active
3165            multi_word_dma_mode: 0x0407,  // support up to mode 3, mode 3 active
3166            enhanced_pio_mode: 0x0003,    // PIO mode 3 and 4 supported
3167            min_multi_dma_time: 0x0078,
3168            recommended_multi_dma_time: 0x0078,
3169            min_pio_cycle_time_no_flow: 0x014D,
3170            min_pio_cycle_time_flow: 0x0078,
3171            major_version_number: 0x01F0, // claim support for ATA4-ATA8
3172            minor_version_number: 0,
3173            command_set_supported: 0x0028, // support caching and power management
3174            command_sets_supported: 0x7400, // support flushing
3175            command_set_supported_ext: 0x4040, // write fua support for default write hardening
3176            command_set_enabled1: 0x0028,  // support caching and power management
3177            command_set_enabled2: 0x3400,  // support flushing
3178            command_set_default: 0x4040,   // write fua support for default write hardening
3179            total_sectors_48_bit: geometry.total_sectors.into(),
3180            default_sector_size_config: 0x4000, // describes the sector size related info. Reflect the underlying device sector size and logical:physical ratio
3181            logical_block_alignment: 0x4000, // describes alignment of logical blocks within physical block
3182            ..FromZeros::new_zeroed()
3183        };
3184        assert_eq!(features.as_bytes(), ex_features.as_bytes());
3185    }
3186
3187    /// Enlightened INT13 with a non-DMA command (READ_SECTORS) should not
3188    /// hang. Before the fix, this would start async disk IO that produces
3189    /// a PIO buffer on completion. The DMA engine can't drain a PIO buffer,
3190    /// so the deferred write completion check (!(bsy || drq)) never passes.
3191    #[async_test]
3192    async fn enlightened_hdd_non_dma_cmd_completes() {
3193        let test_guest_mem = GuestMemory::allocate(16384);
3194
3195        // Set up a PRD table (the enlightened path always writes it,
3196        // even though READ_SECTORS won't use it)
3197        let table_gpa: u64 = 0x1000;
3198        let data_gpa: u32 = 0x2000;
3199        test_guest_mem
3200            .write_plain(
3201                table_gpa,
3202                &BusMasterDmaDesc {
3203                    mem_physical_base: data_gpa,
3204                    byte_count: 512,
3205                    unused: 0,
3206                    end_of_table: 0x80,
3207                },
3208            )
3209            .unwrap();
3210
3211        // READ_SECTORS (0x20) is a PIO read command. The enlightened path
3212        // is designed for DMA commands only (READ_DMA_EXT, WRITE_DMA_EXT).
3213        // Sending a PIO command through it starts async disk IO, but the
3214        // resulting PIO buffer can't be drained by DMA -- hang forever.
3215        let eint13_command = protocol::EnlightenedInt13Command {
3216            command: IdeCommand::READ_SECTORS,
3217            device_head: DeviceHeadReg::new().with_lba(true),
3218            flags: 0,
3219            result_status: 0,
3220            lba_low: 0,
3221            lba_high: 0,
3222            block_count: 1,
3223            byte_count: 0,
3224            data_buffer: table_gpa as u32,
3225            skip_bytes_head: 0,
3226            skip_bytes_tail: 0,
3227        };
3228        test_guest_mem.write_plain(0, &eint13_command).unwrap();
3229
3230        let dev_path = IdePath::default();
3231        let (mut ide_device, _disk, _, _) =
3232            ide_test_setup(Some(test_guest_mem.clone()), DriveType::Hard);
3233
3234        device_select(&mut ide_device, &dev_path).await;
3235        prep_ide_channel(&mut ide_device, DriveType::Hard, &dev_path);
3236
3237        // After fix: non-DMA commands through the enlightened path are
3238        // rejected early and return Ok (not Defer). Before the fix,
3239        // this would return Defer and hang forever.
3240        assert!(
3241            matches!(
3242                ide_device.io_write(IdeIoPort::PRI_ENLIGHTENED.0, 0_u32.as_bytes()),
3243                IoResult::Ok
3244            ),
3245            "non-DMA command (READ_SECTORS) via enlightened path should return Ok, not Defer"
3246        );
3247    }
3248
3249    /// Regression test for the drive-head TOCTOU bug on the enlightened path.
3250    ///
3251    /// The enlightened path must select the target drive (via the Device/Head
3252    /// register in the command packet) *before* checking whether the drive is
3253    /// busy/errored. Before the fix, that busy/error check ran against the
3254    /// *previously* selected drive.
3255    ///
3256    /// This mirrors the Azure ADE scenario: an optical drive sits on the
3257    /// channel master and is the currently-selected drive in a pending (DRQ)
3258    /// state, while a hard disk (the BEK disk) sits on the channel slave. An
3259    /// enlightened read targeting the slave must not be dropped just because
3260    /// the master is pending.
3261    ///
3262    /// Before the fix this drops the command (`io_write` returns `Ok` and logs
3263    /// "command is already pending on this drive, ignoring enlightened
3264    /// command"); after the fix the command is serviced (`Defer`) and the
3265    /// slave disk's data is read.
3266    #[async_test]
3267    async fn enlightened_wrong_drive_head_toctou() {
3268        const SECTOR_COUNT: u16 = 4;
3269        const BYTE_COUNT: u16 = SECTOR_COUNT * protocol::HARD_DRIVE_SECTOR_BYTES as u16;
3270
3271        let test_guest_mem = GuestMemory::allocate(16384);
3272
3273        // PRD table + enlightened command packet targeting the SLAVE (dev=1).
3274        let table_gpa = 0x1000;
3275        let data_gpa = 0x2000;
3276        test_guest_mem
3277            .write_plain(
3278                table_gpa,
3279                &BusMasterDmaDesc {
3280                    mem_physical_base: data_gpa,
3281                    byte_count: BYTE_COUNT,
3282                    unused: 0,
3283                    end_of_table: 0x80,
3284                },
3285            )
3286            .unwrap();
3287
3288        let eint13_command = protocol::EnlightenedInt13Command {
3289            command: IdeCommand::READ_DMA_EXT,
3290            // Target the slave drive (device bit set).
3291            device_head: DeviceHeadReg::new().with_lba(true).with_dev(true),
3292            flags: 0,
3293            result_status: 0,
3294            lba_low: 0,
3295            lba_high: 0,
3296            block_count: SECTOR_COUNT,
3297            byte_count: 0,
3298            data_buffer: table_gpa as u32,
3299            skip_bytes_head: 0,
3300            skip_bytes_tail: 0,
3301        };
3302        test_guest_mem.write_plain(0, &eint13_command).unwrap();
3303
3304        // Build the hard disk (slave) backing with known contents.
3305        let temp_file = NamedTempFile::new().unwrap();
3306        let mut handle = temp_file.reopen().unwrap();
3307        let file_contents = (0..0x100000_u32).collect::<Vec<_>>();
3308        handle.write_all(file_contents.as_bytes()).unwrap();
3309        let hard_disk = Disk::new(FileDisk::open(handle, false).unwrap()).unwrap();
3310
3311        // Master = empty optical drive (no media), Slave = the hard disk.
3312        let optical = DriveMedia::optical_disk(Arc::new(AtapiScsiDisk::new(Arc::new(
3313            SimpleScsiDvd::new(None),
3314        ))));
3315        let hard = DriveMedia::hard_disk(hard_disk);
3316
3317        let mut ide_device = IdeDevice::new(
3318            test_guest_mem.clone(),
3319            &mut ExternallyManagedPortIoIntercepts,
3320            [Some(optical), Some(hard)],
3321            [None, None],
3322            LineInterrupt::detached(),
3323            LineInterrupt::detached(),
3324        )
3325        .unwrap();
3326
3327        // Primary channel, master (the optical drive).
3328        let dev_path = IdePath::default();
3329
3330        // Select the master (optical) and put it into a pending (DRQ) state by
3331        // issuing a PACKET command, which waits for the CDB. This leaves the
3332        // master selected (current_drive_idx = 0) with DRQ set.
3333        device_select(&mut ide_device, &dev_path).await;
3334        execute_command(&mut ide_device, &dev_path, IdeCommand::PACKET_COMMAND.0);
3335
3336        let status = get_status(&mut ide_device, &dev_path);
3337        assert!(
3338            status.drq(),
3339            "expected optical master to be pending (DRQ) before the enlightened command"
3340        );
3341
3342        // Issue the enlightened read targeting the SLAVE hard disk. With the
3343        // bug, the busy/error guard reads the master's (DRQ) status and drops
3344        // the command (returns Ok). With the fix, the drive-head is written
3345        // first, so the guard reads the ready slave and the command proceeds
3346        // (Defer).
3347        let r = ide_device.io_write(IdeIoPort::PRI_ENLIGHTENED.0, 0_u32.as_bytes());
3348
3349        let mut deferred = match r {
3350            IoResult::Defer(deferred) => deferred,
3351            other => panic!(
3352                "enlightened command targeting the slave was dropped ({other:?}); \
3353                 the drive-head TOCTOU guard checked the previously-selected master"
3354            ),
3355        };
3356
3357        poll_fn(|cx| {
3358            ide_device.poll_device(cx);
3359            deferred.poll_write(cx)
3360        })
3361        .await
3362        .unwrap();
3363
3364        // Verify the slave disk's data was read into guest memory.
3365        let mut buffer = vec![0u8; BYTE_COUNT as usize];
3366        test_guest_mem
3367            .read_at(data_gpa.into(), &mut buffer)
3368            .unwrap();
3369        assert_eq!(buffer, file_contents.as_bytes()[..buffer.len()]);
3370    }
3371}