diff --git a/Cargo.lock b/Cargo.lock index 7926c93bbfa..077f8d3929c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11461,12 +11461,14 @@ dependencies = [ "ide", "inspect", "inspect_counters", + "memory_range", "mesh", "missing_dev", "pal_async", "parking_lot", "paste", "pci_bus", + "pci_core", "pcie", "range_map_vec", "state_unit", diff --git a/vmm_core/vmotherboard/Cargo.toml b/vmm_core/vmotherboard/Cargo.toml index b71f155d9e1..5b3a71565de 100644 --- a/vmm_core/vmotherboard/Cargo.toml +++ b/vmm_core/vmotherboard/Cargo.toml @@ -58,6 +58,9 @@ thiserror.workspace = true tracing.workspace = true [dev-dependencies] +inspect = { workspace = true, features = ["initiate"] } +memory_range.workspace = true +pci_core.workspace = true test_with_tracing.workspace = true [lints] diff --git a/vmm_core/vmotherboard/src/base_chipset.rs b/vmm_core/vmotherboard/src/base_chipset.rs index 5c454b52279..08da5fcc7ba 100644 --- a/vmm_core/vmotherboard/src/base_chipset.rs +++ b/vmm_core/vmotherboard/src/base_chipset.rs @@ -1241,3 +1241,629 @@ pub mod options { } } } + +#[cfg(test)] +mod tests { + use super::BaseChipsetBuilder; + use super::BaseChipsetBuilderError; + use super::BaseChipsetBuilderOutput; + use super::options::BaseChipsetDevices; + use super::options::BaseChipsetFoundation; + use super::options::BaseChipsetManifest; + use super::options::dev; + use crate::BusIdPci; + use crate::ChipsetDeviceHandle; + use crate::DebugEventHandler; + use crate::LegacyPciChipsetDeviceHandle; + use crate::PowerEvent; + use crate::PowerEventHandler; + use crate::chipset::Chipset; + use crate::chipset::tests::Fixture; + use crate::chipset::tests::Pci; + use crate::chipset::tests::Shared; + use crate::chipset::tests::TestDevice; + use crate::chipset::tests::access; + use chipset_device::ChipsetDevice; + use chipset_device_resources::BSP_LINT_LINE_SET; + use chipset_device_resources::IRQ_LINE_SET; + use closeable_mutex::CloseableMutex; + use guestmem::GuestMemory; + use pal_async::DefaultDriver; + use pal_async::async_test; + use parking_lot::Mutex; + use std::sync::Arc; + use test_with_tracing::test; + use vm_resource::IntoResource; + use vm_resource::ResourceResolver; + use vmcore::line_interrupt::LineSetTarget; + + struct PanicOnDebugBreak; + + impl DebugEventHandler for PanicOnDebugBreak { + fn on_debug_break(&self, _: Option) { + panic!("unexpected debug break"); + } + } + + #[derive(Default)] + struct RecordPower(Mutex>); + + impl PowerEventHandler for RecordPower { + fn on_power_event(&self, evt: PowerEvent) { + self.0.lock().push(match evt { + PowerEvent::PowerOff => "power-off", + PowerEvent::Reset => "reset", + PowerEvent::Hibernate => "hibernate", + }); + } + } + + #[derive(Default)] + struct RecordLines(Mutex>); + + impl LineSetTarget for RecordLines { + fn set_irq(&self, vector: u32, high: bool) { + self.0.lock().push((vector, high)); + } + } + + async fn base_chipset<'a>( + fixture: &'a Fixture, + power: &Arc, + devices: BaseChipsetDevices, + resolver: &ResourceResolver, + configure: impl FnOnce(BaseChipsetBuilder<'a>) -> BaseChipsetBuilder<'a>, + ) -> Result, BaseChipsetBuilderError> { + let foundation = BaseChipsetFoundation { + is_restoring: false, + untrusted_dma_memory: GuestMemory::empty(), + trusted_vtl0_dma_memory: GuestMemory::empty(), + power_event_handler: power.clone(), + debug_event_handler: Arc::new(PanicOnDebugBreak), + vmtime: &fixture.time, + vmtime_unit: fixture.time_unit.handle(), + doorbell_registration: None, + }; + configure(BaseChipsetBuilder::new(foundation, devices)) + .build(&fixture.source, &fixture.units, resolver) + .await + } + + fn generic_pci_bus() -> BaseChipsetDevices { + BaseChipsetDevices { + deps_generic_pci_bus: Some(dev::GenericPciBusDeps { + bus_id: BusIdPci::new("pci0"), + pio_addr: 0xcf8, + pio_data: 0xcfc, + }), + ..BaseChipsetDevices::empty() + } + } + + fn cfg_address(bdf: (u8, u8, u8), offset: u8) -> [u8; 4] { + let (bus, device, function) = bdf; + (0x8000_0000 + | (u32::from(bus) << 16) + | (u32::from(device) << 11) + | (u32::from(function) << 8) + | u32::from(offset)) + .to_le_bytes() + } + + async fn cfg_read(chipset: &Chipset, bdf: (u8, u8, u8), offset: u8) -> u32 { + chipset.io_write(0, 0xcf8, &cfg_address(bdf, offset)).await; + let mut data = [0; 4]; + chipset.io_read(0, 0xcfc, &mut data).await; + u32::from_le_bytes(data) + } + + async fn cfg_write(chipset: &Chipset, bdf: (u8, u8, u8), offset: u8, value: u32) { + chipset.io_write(0, 0xcf8, &cfg_address(bdf, offset)).await; + chipset.io_write(0, 0xcfc, &value.to_le_bytes()).await; + } + + async fn port_read(chipset: &Chipset, port: u16) -> u8 { + let mut data = [0]; + chipset.io_read(0, port, &mut data).await; + data[0] + } + + async fn port_write(chipset: &Chipset, port: u16, value: u8) { + chipset.io_write(0, port, &[value]).await; + } + + // Test: A base chipset with a generic PCI bus at 0xcf8/0xcfc, a PCI device + // at 00:03.0, and one that suggests 00:03.0 but is placed at 00:05.0, + // accessed through the config address/data ports; then two devices at + // the same address. + // Expected: Each address returns its device's data, an empty slot reads all + // ones, writes reach the device, the manifest check passes, and the + // duplicate address makes build fail naming both devices. + #[async_test] + async fn generic_pci_bus_routes_config_space(driver: DefaultDriver) { + let fixture = Fixture::new(&driver).await; + let power = Arc::new(RecordPower::default()); + let shared = Arc::new(Mutex::new(Shared::default())); + let resolver = ResourceResolver::new(); + let pci_device = |name, fill| TestDevice { + pci: Pci::SuggestedBdf(0, 3, 0), + read_fill: fill, + ..TestDevice::new(name, &shared) + }; + + { + let output = base_chipset(&fixture, &power, generic_pci_bus(), &resolver, |b| { + b.with_expected_manifest(BaseChipsetManifest { + with_generic_pci_bus: true, + ..BaseChipsetManifest::empty() + }) + }) + .await + .unwrap(); + let builder = output.chipset_builder; + builder + .arc_mutex_device("nic") + .on_pci_bus(BusIdPci::new("pci0")) + .add(|_| pci_device("nic", 0x5a)) + .unwrap(); + // Suggests 00:03.0 too, but the explicit address wins. + builder + .arc_mutex_device("moved") + .on_pci_bus(BusIdPci::new("pci0")) + .with_pci_addr(0, 5, 0) + .add(|_| pci_device("moved", 0x6b)) + .unwrap(); + let (chipset, _devices) = builder.build().unwrap(); + + assert_eq!(cfg_read(&chipset, (0, 3, 0), 0).await, 0x5a5a_5a5a); + assert_eq!(cfg_read(&chipset, (0, 5, 0), 0).await, 0x6b6b_6b6b); + assert_eq!(cfg_read(&chipset, (0, 4, 0), 0).await, !0); + cfg_write(&chipset, (0, 3, 0), 0x10, 0xfebf_0000).await; + assert_eq!( + shared.lock().accesses, + [access("nic", "pci", 0x10, &0xfebf_0000u32.to_le_bytes())] + ); + } + + let output = base_chipset(&fixture, &power, generic_pci_bus(), &resolver, |b| b) + .await + .unwrap(); + let builder = output.chipset_builder; + for name in ["first", "second"] { + builder + .arc_mutex_device(name) + .on_pci_bus(BusIdPci::new("pci0")) + .add(|_| pci_device(name, 0)) + .unwrap(); + } + let err = match builder.build() { + Ok(_) => panic!("build unexpectedly succeeded"), + Err(err) => format!("{:#}", anyhow::Error::from(err)), + }; + assert!( + err.contains("cannot attach second to 00:03:0, already occupied by first"), + "{err}" + ); + } + + // Test: A Gen1 base chipset with the PIIX4 PCI bus, the Hyper-V IDE + // controller, and the PIIX4 USB UHCI stub added as a legacy PCI + // device handle at 00:07.2; guest writes to the PIIX4 reset register + // at 0xcf9; then two handles at the same address. + // Expected: IDE answers at 00:07.1 with the PIIX4 IDE IDs, the stub answers + // at 00:07.2 with its documented register values, only writes with a + // reset bit set raise a reset power event, and the duplicate address + // fails the build. + #[async_test] + async fn gen1_piix4_pci_bus_resets_and_hosts_legacy_pci_devices(driver: DefaultDriver) { + let fixture = Fixture::new(&driver).await; + let power = Arc::new(RecordPower::default()); + let mut resolver = ResourceResolver::new(); + resolver.add_resolver(chipset_legacy::piix4_uhci::resolver::Piix4PciUsbUhciStubResolver); + let devices = || BaseChipsetDevices { + deps_piix4_pci_bus: Some(dev::Piix4PciBusDeps { + bus_id: BusIdPci::new("piix4"), + }), + deps_hyperv_ide: Some(dev::HyperVIdeDeps { + attached_to: BusIdPci::new("piix4"), + primary_channel_drives: [None, None], + secondary_channel_drives: [None, None], + }), + ..BaseChipsetDevices::empty() + }; + let uhci = |name: &str| LegacyPciChipsetDeviceHandle { + name: name.into(), + resource: chipset_resources::piix4_uhci::Piix4PciUsbUhciStubDeviceHandle + .into_resource(), + pci_bus_name: "piix4".into(), + bdf: (0, 7, 2), + }; + + { + let output = base_chipset(&fixture, &power, devices(), &resolver, |b| { + b.with_pci_device_handles(vec![uhci("uhci")]) + }) + .await + .unwrap(); + let (chipset, _devices) = output.chipset_builder.build().unwrap(); + + assert_eq!(cfg_read(&chipset, (0, 7, 1), 0).await, 0x7111_8086); + // Status/command, and interrupt pin D with no line assigned. + assert_eq!(cfg_read(&chipset, (0, 7, 2), 0x04).await, 0x0280_0000); + assert_eq!(cfg_read(&chipset, (0, 7, 2), 0x3c).await, 0x04ff); + assert_eq!(cfg_read(&chipset, (0, 7, 3), 0x04).await, !0); + + port_write(&chipset, 0xcf9, 0x01).await; + assert!(power.0.lock().is_empty()); + port_write(&chipset, 0xcf9, 0x06).await; + assert_eq!(*power.0.lock(), ["reset"]); + } + + let output = base_chipset(&fixture, &power, devices(), &resolver, |b| { + b.with_pci_device_handles(vec![uhci("uhci"), uhci("uhci2")]) + }) + .await + .unwrap(); + let err = match output.chipset_builder.build() { + Ok(_) => panic!("build unexpectedly succeeded"), + Err(err) => format!("{:#}", anyhow::Error::from(err)), + }; + assert!( + err.contains("cannot attach uhci2 to 00:07:2, already occupied by uhci"), + "{err}" + ); + } + + // Test: A base chipset configured with a fallback MMIO device and tracing + // options, accessed at an unclaimed MMIO address and an unclaimed + // port. + // Expected: The MMIO access reaches the fallback device, and the port + // access still reads all ones. + #[async_test] + async fn base_chipset_forwards_unclaimed_mmio_to_fallback(driver: DefaultDriver) { + let fixture = Fixture::new(&driver).await; + let power = Arc::new(RecordPower::default()); + let shared = Arc::new(Mutex::new(Shared::default())); + let fallback: Arc> = + Arc::new(CloseableMutex::new(TestDevice { + read_fill: 0xfb, + ..TestDevice::new("fallback", &shared) + })); + let output = base_chipset( + &fixture, + &power, + BaseChipsetDevices::empty(), + &ResourceResolver::new(), + |b| { + b.with_fallback_mmio_device(Some(fallback)) + .with_trace_unknown_mmio(false) + .with_trace_unknown_pio(true) + }, + ) + .await + .unwrap(); + let (chipset, _devices) = output.chipset_builder.build().unwrap(); + + let mut data = [0; 4]; + chipset.mmio_read(0, 0x8000, &mut data).await; + assert_eq!(data, [0xfb; 4]); + assert_eq!(port_read(&chipset, 0x80).await, !0); + assert_eq!( + shared.lock().accesses, + [access("fallback", "mmio", 0x8000, &[])] + ); + } + + fn rtc_time_source() -> vm_resource::Resource { + chipset_resources::cmos_rtc_time_source::SystemTimeClockHandle { + delta_milliseconds: 0, + } + .into_resource() + } + + fn rtc_resolver() -> ResourceResolver { + let mut resolver = ResourceResolver::new(); + resolver.add_resolver(chipset_resources::cmos_rtc_time_source::SystemTimeClockResolver); + resolver + } + + /// Initial CMOS contents with a marker byte in general-purpose RAM. + const CMOS_MARKER: u8 = 0xab; + + fn initial_cmos() -> [u8; 256] { + let mut cmos = [0; 256]; + cmos[0x40] = CMOS_MARKER; + cmos + } + + /// Checks that CMOS RAM starts with `initial_cmos()` and keeps a write, + /// using the index/data ports at 0x70/0x71. + async fn assert_cmos_ram_works(chipset: &Chipset) { + port_write(chipset, 0x70, 0x40).await; + assert_eq!(port_read(chipset, 0x71).await, CMOS_MARKER); + port_write(chipset, 0x70, 0x41).await; + port_write(chipset, 0x71, 0x5c).await; + port_write(chipset, 0x70, 0x41).await; + assert_eq!(port_read(chipset, 0x71).await, 0x5c); + } + + // Test: Build the generic CMOS RTC with initial CMOS contents, read and + // write CMOS RAM through ports 0x70/0x71, then build it without a + // time source resolver. + // Expected: CMOS RAM starts with the supplied contents and keeps guest + // writes; a missing time source fails the build. + #[async_test] + async fn generic_cmos_rtc_exposes_cmos_ram(driver: DefaultDriver) { + let fixture = Fixture::new(&driver).await; + let power = Arc::new(RecordPower::default()); + let devices = || BaseChipsetDevices { + deps_generic_cmos_rtc: Some(dev::GenericCmosRtcDeps { + irq: 8, + time_source: rtc_time_source(), + century_reg_idx: 0x32, + initial_cmos: Some(initial_cmos()), + }), + ..BaseChipsetDevices::empty() + }; + + { + let output = base_chipset(&fixture, &power, devices(), &rtc_resolver(), |b| b) + .await + .unwrap(); + let (chipset, _devices) = output.chipset_builder.build().unwrap(); + assert_cmos_ram_works(&chipset).await; + } + + let err = base_chipset(&fixture, &power, devices(), &ResourceResolver::new(), |b| b) + .await + .err() + .unwrap(); + assert!( + matches!(err, BaseChipsetBuilderError::ResolveResource(_)), + "{err}" + ); + } + + // Test: Build the Gen1 (PIIX4) CMOS RTC with initial CMOS contents, read + // and write CMOS RAM through ports 0x70/0x71, then build it without a + // time source resolver. + // Expected: CMOS RAM starts with the supplied contents and keeps guest + // writes; a missing time source fails the build. + #[async_test] + async fn gen1_piix4_cmos_rtc_exposes_cmos_ram(driver: DefaultDriver) { + let fixture = Fixture::new(&driver).await; + let power = Arc::new(RecordPower::default()); + let devices = || BaseChipsetDevices { + deps_piix4_cmos_rtc: Some(dev::Piix4CmosRtcDeps { + time_source: rtc_time_source(), + initial_cmos: Some(initial_cmos()), + enlightened_interrupts: false, + }), + ..BaseChipsetDevices::empty() + }; + + { + let output = base_chipset(&fixture, &power, devices(), &rtc_resolver(), |b| b) + .await + .unwrap(); + let (chipset, _devices) = output.chipset_builder.build().unwrap(); + assert_cmos_ram_works(&chipset).await; + } + + let err = base_chipset(&fixture, &power, devices(), &ResourceResolver::new(), |b| b) + .await + .err() + .unwrap(); + assert!( + matches!(err, BaseChipsetBuilderError::ResolveResource(_)), + "{err}" + ); + } + + // Test: Build a Gen1 base chipset with an ISA DMA controller handle, + // program channel 2's address and page registers through their ports, + // and build again without a DMA resolver. + // Expected: The registers read back what the guest wrote, and the missing + // resolver fails the build with the ISA DMA error. + #[async_test] + async fn gen1_isa_dma_controller_is_resolved_and_programmable(driver: DefaultDriver) { + let fixture = Fixture::new(&driver).await; + let power = Arc::new(RecordPower::default()); + let mut resolver = ResourceResolver::new(); + resolver.add_resolver(chipset::dma::resolver::GenericIsaDmaResolver); + let dma = || Some(chipset_resources::isa_dma::GenericIsaDmaDeviceHandle.into_resource()); + + { + let output = base_chipset( + &fixture, + &power, + BaseChipsetDevices::empty(), + &resolver, + |b| b.with_isa_dma_handle(dma()), + ) + .await + .unwrap(); + let (chipset, _devices) = output.chipset_builder.build().unwrap(); + + // Clear the byte flip-flop, write the 16-bit address low then high. + port_write(&chipset, 0x0c, 0).await; + port_write(&chipset, 0x04, 0x34).await; + port_write(&chipset, 0x04, 0x12).await; + port_write(&chipset, 0x0c, 0).await; + assert_eq!(port_read(&chipset, 0x04).await, 0x34); + assert_eq!(port_read(&chipset, 0x04).await, 0x12); + port_write(&chipset, 0x81, 0x05).await; + assert_eq!(port_read(&chipset, 0x81).await, 0x05); + } + + let err = base_chipset( + &fixture, + &power, + BaseChipsetDevices::empty(), + &ResourceResolver::new(), + |b| b.with_isa_dma_handle(dma()), + ) + .await + .err() + .unwrap(); + assert!( + matches!(err, BaseChipsetBuilderError::ResolveIsaDma(_)), + "{err}" + ); + } + + // Test: Build each Gen1 floppy controller variant (generic ISA, full + // Winbond super I/O, stub Winbond super I/O) with and without an ISA + // DMA controller. + // Expected: Each builds when DMA is available and fails with + // `NoDmaForFloppy` otherwise. + #[cfg(any( + feature = "dev_generic_isa_floppy", + feature = "dev_winbond_super_io_and_floppy_full", + feature = "dev_winbond_super_io_and_floppy_stub" + ))] + #[async_test] + async fn gen1_floppy_controllers_require_isa_dma(driver: DefaultDriver) { + let fixture = Fixture::new(&driver).await; + let power = Arc::new(RecordPower::default()); + let mut resolver = ResourceResolver::new(); + resolver.add_resolver(chipset::dma::resolver::GenericIsaDmaResolver); + let variants: &[fn() -> BaseChipsetDevices] = &[ + #[cfg(feature = "dev_generic_isa_floppy")] + || BaseChipsetDevices { + deps_generic_isa_floppy: Some(dev::GenericIsaFloppyDeps { + irq: 6, + dma_channel: 2, + pio_base: 0x3f0, + drives: floppy::DriveRibbon::None, + }), + ..BaseChipsetDevices::empty() + }, + #[cfg(feature = "dev_winbond_super_io_and_floppy_full")] + || BaseChipsetDevices { + deps_winbond_super_io_and_floppy_full: Some(dev::WinbondSuperIoAndFloppyFullDeps { + primary_disk_drive: floppy::DriveRibbon::None, + secondary_disk_drive: floppy::DriveRibbon::None, + }), + ..BaseChipsetDevices::empty() + }, + #[cfg(feature = "dev_winbond_super_io_and_floppy_stub")] + || BaseChipsetDevices { + deps_winbond_super_io_and_floppy_stub: Some(dev::WinbondSuperIoAndFloppyStubDeps), + ..BaseChipsetDevices::empty() + }, + ]; + + for devices in variants { + let err = base_chipset(&fixture, &power, devices(), &resolver, |b| b) + .await + .err() + .unwrap(); + assert!( + matches!(err, BaseChipsetBuilderError::NoDmaForFloppy), + "{err}" + ); + + let output = base_chipset(&fixture, &power, devices(), &resolver, |b| { + b.with_isa_dma_handle(Some( + chipset_resources::isa_dma::GenericIsaDmaDeviceHandle.into_resource(), + )) + }) + .await + .unwrap(); + output.chipset_builder.build().unwrap(); + } + } + + // Test: A base chipset with a PIC added from a device handle, an external + // target on the BSP LINT line set, and a device that raises IRQ 5 and + // IRQ 10 after the guest initializes both PICs; then a device handle + // that has no resolver. + // Expected: Each IRQ makes the PIC signal the processor through the + // external target and acknowledges as base vector plus IRQ (through + // the cascade for IRQ 10); the unresolvable handle fails the build. + #[async_test] + async fn irq_lines_reach_the_pic_and_external_targets(driver: DefaultDriver) { + let fixture = Fixture::new(&driver).await; + let power = Arc::new(RecordPower::default()); + let shared = Arc::new(Mutex::new(Shared::default())); + let mut resolver = ResourceResolver::new(); + resolver.add_resolver(chipset::pic::resolver::PicResolver); + let pic = || ChipsetDeviceHandle { + name: "pic".into(), + resource: chipset_resources::pic::PicDeviceHandle.into_resource(), + }; + + { + let output = base_chipset( + &fixture, + &power, + BaseChipsetDevices::empty(), + &resolver, + |b| b.with_device_handles(vec![pic()]), + ) + .await + .unwrap(); + let builder = output.chipset_builder; + let lint = Arc::new(RecordLines::default()); + builder.add_external_line_target(BSP_LINT_LINE_SET, 0..=0, 0, "test", lint.clone()); + let irq5 = builder + .arc_mutex_device("irq5") + .add(|services| TestDevice { + line: Some(services.new_line(IRQ_LINE_SET, "test", 5)), + ..TestDevice::new("irq5", &shared) + }) + .unwrap(); + let irq10 = builder + .arc_mutex_device("irq10") + .add(|services| TestDevice { + line: Some(services.new_line(IRQ_LINE_SET, "test", 10)), + ..TestDevice::new("irq10", &shared) + }) + .unwrap(); + let (chipset, _devices) = builder.build().unwrap(); + + // ICW1-ICW4 for the primary (vectors 0x20, secondary on IRQ 2) and + // secondary (vectors 0x28, cascade identity 2) PICs, then unmask. + for (port, value) in [ + (0x20, 0x11), + (0x21, 0x20), + (0x21, 0x04), + (0x21, 0x01), + (0x21, 0x00), + (0xa0, 0x11), + (0xa1, 0x28), + (0xa1, 0x02), + (0xa1, 0x01), + (0xa1, 0x00), + ] { + port_write(&chipset, port, value).await; + } + assert_eq!(chipset.acknowledge_pic_interrupt(), None); + + irq5.lock().line.as_ref().unwrap().set_level(true); + assert_eq!(lint.0.lock().last(), Some(&(0, true))); + assert_eq!(chipset.acknowledge_pic_interrupt(), Some(0x25)); + + irq10.lock().line.as_ref().unwrap().set_level(true); + assert_eq!(lint.0.lock().last(), Some(&(0, true))); + assert_eq!(chipset.acknowledge_pic_interrupt(), Some(0x2a)); + } + + let err = base_chipset( + &fixture, + &power, + BaseChipsetDevices::empty(), + &ResourceResolver::new(), + |b| b.with_device_handles(vec![pic()]), + ) + .await + .err() + .unwrap(); + assert!( + matches!(err, BaseChipsetBuilderError::AddDevice(_)), + "{err}" + ); + assert!(err.to_string().contains("pic"), "{err}"); + } +} diff --git a/vmm_core/vmotherboard/src/chipset/mod.rs b/vmm_core/vmotherboard/src/chipset/mod.rs index 439c49cbb99..bddf9e2f981 100644 --- a/vmm_core/vmotherboard/src/chipset/mod.rs +++ b/vmm_core/vmotherboard/src/chipset/mod.rs @@ -375,3 +375,1245 @@ impl std::fmt::Display for PcieConflict { } } } + +#[cfg(test)] +pub(crate) mod tests { + use super::Chipset; + use super::ChipsetBuilder; + use super::ChipsetDevices; + use crate::BusIdPci; + use crate::DebugEventHandler; + use crate::chipset::backing::arc_mutex::device::AddDeviceError; + use chipset_device::ChipsetDevice; + use chipset_device::interrupt::AcknowledgePicInterrupt; + use chipset_device::interrupt::HandleEoi; + use chipset_device::io::IoError; + use chipset_device::io::IoResult; + use chipset_device::io::deferred::DeferredRead; + use chipset_device::io::deferred::DeferredWrite; + use chipset_device::io::deferred::defer_read; + use chipset_device::io::deferred::defer_write; + use chipset_device::mmio::ControlMmioIntercept; + use chipset_device::mmio::MmioIntercept; + use chipset_device::mmio::RegisterMmioIntercept; + use chipset_device::pci::ByteEnabledDwordRead; + use chipset_device::pci::ByteEnabledDwordWrite; + use chipset_device::pci::PciConfigSpace; + use chipset_device::pio::PortIoIntercept; + use closeable_mutex::CloseableMutex; + use futures::FutureExt; + use inspect::InspectMut; + use pal_async::DefaultDriver; + use pal_async::async_test; + use parking_lot::Mutex; + use state_unit::StateUnits; + use std::ops::RangeInclusive; + use std::sync::Arc; + use test_with_tracing::test; + use vmcore::device_state::ChangeDeviceState; + use vmcore::line_interrupt::LineInterrupt; + use vmcore::save_restore::NoSavedState; + use vmcore::save_restore::RestoreError; + use vmcore::save_restore::SaveError; + use vmcore::save_restore::SaveRestore; + use vmcore::vm_task::SingleDriverBackend; + use vmcore::vm_task::VmTaskDriverSource; + use vmcore::vmtime::VmTime; + use vmcore::vmtime::VmTimeKeeper; + use vmcore::vmtime::VmTimeSource; + + struct PanicOnDebugBreak; + + impl DebugEventHandler for PanicOnDebugBreak { + fn on_debug_break(&self, _: Option) { + panic!("unexpected debug break"); + } + } + + pub(crate) struct Fixture { + pub(crate) source: VmTaskDriverSource, + pub(crate) units: StateUnits, + pub(crate) time_unit: state_unit::SpawnedUnit<()>, + pub(crate) time: VmTimeSource, + _keeper: VmTimeKeeper, + } + + impl Fixture { + pub(crate) async fn new(driver: &DefaultDriver) -> Self { + let units = StateUnits::new(); + let time_unit = units + .add("vmtime") + .spawn(driver.clone(), async |mut recv| { + while let Ok(req) = recv.recv().await { + req.apply(&mut NoopUnit).await; + } + }) + .unwrap(); + let keeper = VmTimeKeeper::new(driver, VmTime::from_100ns(0)); + let time = keeper.builder().build(driver).await.unwrap(); + Self { + source: VmTaskDriverSource::new(SingleDriverBackend::new(driver.clone())), + units, + time_unit, + time, + _keeper: keeper, + } + } + + pub(crate) fn builder( + &self, + fallback_mmio: Option>>, + ) -> ChipsetBuilder<'_> { + self.builder_with_debug(fallback_mmio, Arc::new(PanicOnDebugBreak)) + } + + pub(crate) fn builder_with_debug( + &self, + fallback_mmio: Option>>, + debug: Arc, + ) -> ChipsetBuilder<'_> { + ChipsetBuilder::new( + &self.source, + &self.units, + debug, + &self.time, + self.time_unit.handle(), + false, + false, + fallback_mmio, + ) + } + } + + /// Stands in for the VM time unit so whole-VM state transitions complete. + #[derive(InspectMut)] + struct NoopUnit; + + impl state_unit::StateUnit for NoopUnit { + async fn start(&mut self) {} + + async fn stop(&mut self) {} + + async fn reset(&mut self) -> anyhow::Result<()> { + Ok(()) + } + + async fn save( + &mut self, + ) -> Result, SaveError> { + Ok(None) + } + + async fn restore( + &mut self, + _: vmcore::save_restore::SavedStateBlob, + ) -> Result<(), RestoreError> { + Ok(()) + } + } + + #[derive(Debug, PartialEq)] + pub(crate) struct Access { + pub(crate) device: &'static str, + pub(crate) kind: &'static str, + pub(crate) addr: u64, + pub(crate) data: Vec, + } + + #[derive(Default)] + pub(crate) struct Shared { + pub(crate) accesses: Vec, + pub(crate) events: Vec, + deferred_reads: Vec, + deferred_writes: Vec, + eois: Vec, + } + + #[derive(Clone, Copy, PartialEq)] + pub(crate) enum Pci { + None, + NoSuggestedBdf, + SuggestedBdf(u8, u8, u8), + } + + #[derive(Clone, Copy)] + pub(crate) enum Response { + Ok, + Fail, + Defer, + } + + pub(crate) struct TestDevice { + pub(crate) name: &'static str, + pub(crate) mmio: Vec<(&'static str, RangeInclusive)>, + pub(crate) pio: Vec<(&'static str, RangeInclusive)>, + pub(crate) response: Response, + pub(crate) read_fill: u8, + pub(crate) region: Option>, + pub(crate) pci: Pci, + pub(crate) pic_vector: Option, + pub(crate) eoi: bool, + pub(crate) line: Option, + pub(crate) shared: Arc>, + } + + impl TestDevice { + pub(crate) fn new(name: &'static str, shared: &Arc>) -> Self { + Self { + name, + mmio: Vec::new(), + pio: Vec::new(), + response: Response::Ok, + read_fill: 0, + region: None, + pci: Pci::None, + pic_vector: None, + eoi: false, + line: None, + shared: shared.clone(), + } + } + + fn read(&mut self, kind: &'static str, addr: u64, data: &mut [u8]) -> IoResult { + let mut shared = self.shared.lock(); + shared.accesses.push(Access { + device: self.name, + kind, + addr, + data: Vec::new(), + }); + match self.response { + Response::Ok => { + data.fill(self.read_fill); + IoResult::Ok + } + Response::Fail => { + data.fill(self.read_fill); + IoResult::Err(IoError::InvalidRegister) + } + Response::Defer => { + let (read, token) = defer_read(); + shared.deferred_reads.push(read); + IoResult::Defer(token) + } + } + } + + fn write(&mut self, kind: &'static str, addr: u64, data: &[u8]) -> IoResult { + let mut shared = self.shared.lock(); + shared.accesses.push(Access { + device: self.name, + kind, + addr, + data: data.to_vec(), + }); + match self.response { + Response::Ok => IoResult::Ok, + Response::Fail => IoResult::Err(IoError::InvalidRegister), + Response::Defer => { + let (write, token) = defer_write(); + shared.deferred_writes.push(write); + IoResult::Defer(token) + } + } + } + } + + impl InspectMut for TestDevice { + fn inspect_mut(&mut self, req: inspect::Request<'_>) { + req.ignore(); + } + } + + impl ChangeDeviceState for TestDevice { + fn start(&mut self) { + self.shared + .lock() + .events + .push(format!("{}:start", self.name)); + } + + async fn stop(&mut self) { + self.shared + .lock() + .events + .push(format!("{}:stop", self.name)); + } + + async fn reset(&mut self) { + self.shared + .lock() + .events + .push(format!("{}:reset", self.name)); + } + } + + impl SaveRestore for TestDevice { + type SavedState = NoSavedState; + + fn save(&mut self) -> Result { + Ok(NoSavedState) + } + + fn restore(&mut self, _: NoSavedState) -> Result<(), RestoreError> { + Ok(()) + } + } + + impl ChipsetDevice for TestDevice { + fn supports_mmio(&mut self) -> Option<&mut dyn MmioIntercept> { + Some(self) + } + + fn supports_pio(&mut self) -> Option<&mut dyn PortIoIntercept> { + Some(self) + } + + fn supports_pci(&mut self) -> Option<&mut dyn PciConfigSpace> { + (self.pci != Pci::None).then_some(self) + } + + fn supports_acknowledge_pic_interrupt( + &mut self, + ) -> Option<&mut dyn AcknowledgePicInterrupt> { + self.pic_vector.is_some().then_some(self) + } + + fn supports_handle_eoi(&mut self) -> Option<&mut dyn HandleEoi> { + self.eoi.then_some(self) + } + } + + impl MmioIntercept for TestDevice { + fn get_static_regions(&mut self) -> &[(&str, RangeInclusive)] { + &self.mmio + } + + fn mmio_read(&mut self, addr: u64, data: &mut [u8]) -> IoResult { + self.read("mmio", addr, data) + } + + fn mmio_write(&mut self, addr: u64, data: &[u8]) -> IoResult { + self.write("mmio", addr, data) + } + } + + impl PortIoIntercept for TestDevice { + fn get_static_regions(&mut self) -> &[(&str, RangeInclusive)] { + &self.pio + } + + fn io_read(&mut self, port: u16, data: &mut [u8]) -> IoResult { + self.read("pio", port.into(), data) + } + + fn io_write(&mut self, port: u16, data: &[u8]) -> IoResult { + self.write("pio", port.into(), data) + } + } + + impl PciConfigSpace for TestDevice { + fn pci_cfg_read(&mut self, _: u16, mut value: ByteEnabledDwordRead<'_>) -> IoResult { + value.set(u32::from_ne_bytes([self.read_fill; 4])); + IoResult::Ok + } + + fn pci_cfg_write(&mut self, offset: u16, value: ByteEnabledDwordWrite) -> IoResult { + self.shared.lock().accesses.push(Access { + device: self.name, + kind: "pci", + addr: offset.into(), + data: value.as_valid_byte_slice().to_vec(), + }); + IoResult::Ok + } + + fn suggested_bdf(&mut self) -> Option<(u8, u8, u8)> { + match self.pci { + Pci::SuggestedBdf(b, d, f) => Some((b, d, f)), + Pci::None | Pci::NoSuggestedBdf => None, + } + } + } + + impl AcknowledgePicInterrupt for TestDevice { + fn acknowledge_interrupt(&mut self) -> Option { + self.pic_vector + } + } + + impl HandleEoi for TestDevice { + fn handle_eoi(&mut self, irq: u32) { + self.shared.lock().eois.push(irq); + } + } + + pub(crate) fn access( + device: &'static str, + kind: &'static str, + addr: u64, + data: &[u8], + ) -> Access { + Access { + device, + kind, + addr, + data: data.to_vec(), + } + } + + pub(crate) fn build(builder: ChipsetBuilder<'_>) -> (Arc, ChipsetDevices) { + builder.build().unwrap() + } + + pub(crate) fn add_error(result: Result) -> String { + match result { + Ok(_) => panic!("add unexpectedly succeeded"), + Err(err) => format!("{:#}", anyhow::Error::from(err)), + } + } + + pub(crate) fn build_error(builder: ChipsetBuilder<'_>) -> String { + match builder.build() { + Ok(_) => panic!("build unexpectedly succeeded"), + Err(err) => format!("{:#}", anyhow::Error::from(err)), + } + } + + // Test: Two devices with static MMIO/PIO ranges, then reads and writes at + // range boundaries through the chipset. + // Expected: Each access reaches only the owning device with its address and + // data, and reads return that device's data. + #[async_test] + async fn accesses_reach_owning_device(driver: DefaultDriver) { + let fixture = Fixture::new(&driver).await; + let builder = fixture.builder(None); + let shared = Arc::new(Mutex::new(Shared::default())); + builder + .arc_mutex_device("a") + .add(|_| TestDevice { + mmio: vec![("a-mmio", 0x1000..=0x1fff)], + pio: vec![("a-pio", 0x60..=0x63)], + read_fill: 0xaa, + ..TestDevice::new("a", &shared) + }) + .unwrap(); + builder + .arc_mutex_device("b") + .add(|_| TestDevice { + mmio: vec![("b-mmio", 0x2000..=0x2fff)], + pio: vec![("b-pio", 0x64..=0x64)], + read_fill: 0xbb, + ..TestDevice::new("b", &shared) + }) + .unwrap(); + let (chipset, _devices) = build(builder); + + let mut data = [0; 4]; + chipset.mmio_read(0, 0x1ffc, &mut data).await; + assert_eq!(data, [0xaa; 4]); + chipset.mmio_read(0, 0x2000, &mut data).await; + assert_eq!(data, [0xbb; 4]); + chipset.mmio_write(0, 0x1000, &[1, 2, 3, 4]).await; + let mut byte = [0]; + chipset.io_read(0, 0x63, &mut byte).await; + assert_eq!(byte, [0xaa]); + chipset.io_read(0, 0x64, &mut byte).await; + assert_eq!(byte, [0xbb]); + chipset.io_write(0, 0x60, &[5]).await; + + assert_eq!( + std::mem::take(&mut shared.lock().accesses), + [ + access("a", "mmio", 0x1ffc, &[]), + access("b", "mmio", 0x2000, &[]), + access("a", "mmio", 0x1000, &[1, 2, 3, 4]), + access("a", "pio", 0x63, &[]), + access("b", "pio", 0x64, &[]), + access("a", "pio", 0x60, &[5]), + ] + ); + assert!(chipset.is_mmio(0x1fff)); + assert!(chipset.is_mmio(0x2000)); + } + + // Test: MMIO/PIO accesses just outside a device's static ranges. + // Expected: Reads return all ones, writes are dropped, the device sees + // nothing, and `is_mmio` reports the address as unclaimed. + #[async_test] + async fn unclaimed_accesses_read_all_ones(driver: DefaultDriver) { + let fixture = Fixture::new(&driver).await; + let builder = fixture.builder(None); + let shared = Arc::new(Mutex::new(Shared::default())); + builder + .arc_mutex_device("a") + .add(|_| TestDevice { + mmio: vec![("a-mmio", 0x1000..=0x1fff)], + pio: vec![("a-pio", 0x60..=0x63)], + ..TestDevice::new("a", &shared) + }) + .unwrap(); + let (chipset, _devices) = build(builder); + + let mut data = [0; 8]; + chipset.mmio_read(0, 0x2000, &mut data).await; + assert_eq!(data, [!0; 8]); + chipset.mmio_write(0, 0xfff, &[1; 4]).await; + let mut data = [0; 2]; + chipset.io_read(0, 0x64, &mut data).await; + assert_eq!(data, [!0; 2]); + chipset.io_write(0, 0x5f, &[1]).await; + + assert!(shared.lock().accesses.is_empty()); + assert!(!chipset.is_mmio(0xfff)); + assert!(!chipset.is_mmio(0x2000)); + } + + // Test: A device that partly fills the read buffer and then fails both + // reads and writes. + // Expected: The guest reads all ones rather than the partial data, and a + // failed write still reaches the device without disturbing later I/O. + #[async_test] + async fn device_errors_read_all_ones(driver: DefaultDriver) { + let fixture = Fixture::new(&driver).await; + let builder = fixture.builder(None); + let shared = Arc::new(Mutex::new(Shared::default())); + builder + .arc_mutex_device("a") + .add(|_| TestDevice { + mmio: vec![("a-mmio", 0x1000..=0x1fff)], + pio: vec![("a-pio", 0x60..=0x63)], + response: Response::Fail, + read_fill: 0x12, + ..TestDevice::new("a", &shared) + }) + .unwrap(); + let (chipset, _devices) = build(builder); + + let mut data = [0; 4]; + chipset.mmio_read(0, 0x1000, &mut data).await; + assert_eq!(data, [!0; 4]); + let mut data = [0; 2]; + chipset.io_read(0, 0x60, &mut data).await; + assert_eq!(data, [!0; 2]); + chipset.mmio_write(0, 0x1004, &[7]).await; + chipset.io_write(0, 0x61, &[8]).await; + + assert_eq!( + shared.lock().accesses, + [ + access("a", "mmio", 0x1000, &[]), + access("a", "pio", 0x60, &[]), + access("a", "mmio", 0x1004, &[7]), + access("a", "pio", 0x61, &[8]), + ] + ); + } + + // Test: A device that defers its reads and writes, then completes, fails, + // or abandons them. + // Expected: The chipset access stays pending until the device answers; + // completed reads return the device data, and failed or abandoned + // reads return all ones. + #[async_test] + async fn deferred_accesses_complete_with_device_result(driver: DefaultDriver) { + let fixture = Fixture::new(&driver).await; + let builder = fixture.builder(None); + let shared = Arc::new(Mutex::new(Shared::default())); + builder + .arc_mutex_device("a") + .add(|_| TestDevice { + mmio: vec![("a-mmio", 0x1000..=0x1fff)], + pio: vec![("a-pio", 0x60..=0x63)], + response: Response::Defer, + ..TestDevice::new("a", &shared) + }) + .unwrap(); + let (chipset, _devices) = build(builder); + + let mut data = [0; 4]; + { + let mut read = std::pin::pin!(chipset.mmio_read(0, 0x1000, &mut data)); + assert!((&mut read).now_or_never().is_none()); + let deferred = shared.lock().deferred_reads.pop().unwrap(); + deferred.complete(&[1, 2, 3, 4]); + read.await; + } + assert_eq!(data, [1, 2, 3, 4]); + + let mut data = [0; 2]; + { + let mut read = std::pin::pin!(chipset.io_read(0, 0x60, &mut data)); + assert!((&mut read).now_or_never().is_none()); + let deferred = shared.lock().deferred_reads.pop().unwrap(); + deferred.complete_error(IoError::InvalidAccessSize); + read.await; + } + assert_eq!(data, [!0; 2]); + + let mut data = [0; 4]; + { + let mut read = std::pin::pin!(chipset.mmio_read(0, 0x1000, &mut data)); + assert!((&mut read).now_or_never().is_none()); + drop(shared.lock().deferred_reads.pop().unwrap()); + read.await; + } + assert_eq!(data, [!0; 4]); + + let mut write = std::pin::pin!(chipset.mmio_write(0, 0x1008, &[9])); + assert!((&mut write).now_or_never().is_none()); + shared.lock().deferred_writes.pop().unwrap().complete(); + write.await; + + let mut write = std::pin::pin!(chipset.io_write(0, 0x62, &[10])); + assert!((&mut write).now_or_never().is_none()); + shared + .lock() + .deferred_writes + .pop() + .unwrap() + .complete_error(IoError::InvalidRegister); + write.await; + + assert_eq!(shared.lock().accesses.len(), 5); + } + + // Test: A chipset with a fallback MMIO device and one claimed range. + // Expected: Unclaimed MMIO goes to the fallback, claimed MMIO goes to its + // owner, unclaimed port I/O still reads all ones, and `is_mmio` stays + // false for fallback-only addresses. + #[async_test] + async fn fallback_device_receives_only_unclaimed_mmio(driver: DefaultDriver) { + let fixture = Fixture::new(&driver).await; + let shared = Arc::new(Mutex::new(Shared::default())); + let fallback: Arc> = + Arc::new(CloseableMutex::new(TestDevice { + read_fill: 0xfb, + ..TestDevice::new("fallback", &shared) + })); + let builder = fixture.builder(Some(fallback)); + builder + .arc_mutex_device("a") + .add(|_| TestDevice { + mmio: vec![("a-mmio", 0x1000..=0x1fff)], + read_fill: 0xaa, + ..TestDevice::new("a", &shared) + }) + .unwrap(); + let (chipset, _devices) = build(builder); + + let mut data = [0; 4]; + chipset.mmio_read(0, 0x8000, &mut data).await; + assert_eq!(data, [0xfb; 4]); + chipset.mmio_write(0, 0x8004, &[3]).await; + chipset.mmio_read(0, 0x1000, &mut data).await; + assert_eq!(data, [0xaa; 4]); + let mut byte = [0]; + chipset.io_read(0, 0x80, &mut byte).await; + assert_eq!(byte, [!0]); + + assert_eq!( + shared.lock().accesses, + [ + access("fallback", "mmio", 0x8000, &[]), + access("fallback", "mmio", 0x8004, &[3]), + access("a", "mmio", 0x1000, &[]), + ] + ); + assert!(!chipset.is_mmio(0x8000)); + } + + // Test: Static MMIO and PIO ranges that overlap by one address, and ranges + // that are exactly adjacent. + // Expected: Overlaps make build fail and name both devices; adjacent ranges + // build successfully. + #[async_test] + async fn overlapping_static_ranges_fail_build(driver: DefaultDriver) { + let fixture = Fixture::new(&driver).await; + let shared = Arc::new(Mutex::new(Shared::default())); + + let builder = fixture.builder(None); + builder + .arc_mutex_device("first") + .add(|_| TestDevice { + mmio: vec![("first-mmio", 0x1000..=0x1fff)], + pio: vec![("first-pio", 0x60..=0x63)], + ..TestDevice::new("first", &shared) + }) + .unwrap(); + builder + .arc_mutex_device("second") + .add(|_| TestDevice { + mmio: vec![("second-mmio", 0x1fff..=0x2fff)], + pio: vec![("second-pio", 0x63..=0x64)], + ..TestDevice::new("second", &shared) + }) + .unwrap(); + let err = build_error(builder); + assert!( + err.contains("static mmio intercept region conflict"), + "{err}" + ); + assert!( + err.contains("static pio intercept region conflict"), + "{err}" + ); + assert!(err.contains("second/second-mmio"), "{err}"); + assert!(err.contains("first/first-mmio"), "{err}"); + assert!(err.contains("second/second-pio"), "{err}"); + assert!(err.contains("first/first-pio"), "{err}"); + + let builder = fixture.builder(None); + builder + .arc_mutex_device("first") + .add(|_| TestDevice { + mmio: vec![("first-mmio", 0x1000..=0x1fff)], + pio: vec![("first-pio", 0x60..=0x63)], + ..TestDevice::new("first", &shared) + }) + .unwrap(); + builder + .arc_mutex_device("second") + .add(|_| TestDevice { + mmio: vec![("second-mmio", 0x2000..=0x2fff)], + pio: vec![("second-pio", 0x64..=0x64)], + ..TestDevice::new("second", &shared) + }) + .unwrap(); + build(builder); + } + + // Test: PCI devices added without a bus, without a BDF, and on a bus that + // was never registered. + // Expected: The first two are rejected when added and the third makes build + // fail with the device name and requested BDF. + #[async_test] + async fn pci_device_wiring_errors_are_reported(driver: DefaultDriver) { + let fixture = Fixture::new(&driver).await; + let shared = Arc::new(Mutex::new(Shared::default())); + let builder = fixture.builder(None); + + let err = add_error(builder.arc_mutex_device("no-bus").add(|_| TestDevice { + pci: Pci::SuggestedBdf(0, 1, 0), + ..TestDevice::new("no-bus", &shared) + })); + assert!(err.contains("no pci bus specified"), "{err}"); + + let err = add_error( + builder + .arc_mutex_device("no-bdf") + .on_pci_bus(BusIdPci::new("missing")) + .add(|_| TestDevice { + pci: Pci::NoSuggestedBdf, + ..TestDevice::new("no-bdf", &shared) + }), + ); + assert!(err.contains("no pci bus address provided"), "{err}"); + + builder + .arc_mutex_device("orphan") + .on_pci_bus(BusIdPci::new("missing")) + .with_pci_addr(0, 3, 1) + .add(|_| TestDevice { + pci: Pci::SuggestedBdf(0, 2, 0), + ..TestDevice::new("orphan", &shared) + }) + .unwrap(); + let err = build_error(builder); + assert!( + err.contains("cannot attach orphan to 00:03:1, no valid PCI bus"), + "{err}" + ); + } + + // Test: A device remaps a dynamic MMIO region after build, then tries to + // map it over another device's static range. + // Expected: Dispatch follows the current mapping with the old address + // released, and the conflicting map never takes over the static + // range. + #[async_test] + async fn runtime_region_mapping_moves_dispatch(driver: DefaultDriver) { + let fixture = Fixture::new(&driver).await; + let shared = Arc::new(Mutex::new(Shared::default())); + let builder = fixture.builder(None); + builder + .arc_mutex_device("static") + .add(|_| TestDevice { + mmio: vec![("static-mmio", 0x1000..=0x1fff)], + read_fill: 0x55, + ..TestDevice::new("static", &shared) + }) + .unwrap(); + let dynamic = builder + .arc_mutex_device("dynamic") + .add(|services| TestDevice { + region: Some(services.register_mmio().new_io_region("bar", 0x100)), + read_fill: 0xdd, + ..TestDevice::new("dynamic", &shared) + }) + .unwrap(); + let (chipset, _devices) = build(builder); + let mut data = [0; 4]; + + dynamic.lock().region.as_mut().unwrap().map(0x4000); + chipset.mmio_read(0, 0x40fc, &mut data).await; + assert_eq!(data, [0xdd; 4]); + + dynamic.lock().region.as_mut().unwrap().map(0x5000); + assert!(!chipset.is_mmio(0x4000)); + chipset.mmio_read(0, 0x4000, &mut data).await; + assert_eq!(data, [!0; 4]); + chipset.mmio_read(0, 0x5000, &mut data).await; + assert_eq!(data, [0xdd; 4]); + + dynamic.lock().region.as_mut().unwrap().map(0x1f80); + assert!(!chipset.is_mmio(0x5000)); + chipset.mmio_read(0, 0x5000, &mut data).await; + assert_eq!(data, [!0; 4]); + chipset.mmio_read(0, 0x1f80, &mut data).await; + assert_eq!(data, [0x55; 4]); + chipset.mmio_read(0, 0x2000, &mut data).await; + assert_eq!(data, [!0; 4]); + + dynamic.lock().region.as_mut().unwrap().map(0x5000); + assert!(chipset.is_mmio(0x5000)); + chipset.mmio_read(0, 0x5000, &mut data).await; + assert_eq!(data, [0xdd; 4]); + dynamic.lock().region.as_mut().unwrap().unmap(); + assert!(!chipset.is_mmio(0x5000)); + chipset.mmio_read(0, 0x5000, &mut data).await; + assert_eq!(data, [!0; 4]); + } + + // Test: A chipset without a PIC, then one with a PIC/EOI device, and a + // second PIC/EOI device added after the first. + // Expected: Acknowledgement returns no vector without a PIC, routes to the + // PIC when present, EOIs reach the handler, and the duplicate handler + // is rejected. + #[async_test] + async fn pic_and_eoi_route_to_registered_handlers(driver: DefaultDriver) { + let fixture = Fixture::new(&driver).await; + let shared = Arc::new(Mutex::new(Shared::default())); + + { + let (chipset, _devices) = build(fixture.builder(None)); + assert_eq!(chipset.acknowledge_pic_interrupt(), None); + } + + let builder = fixture.builder(None); + builder + .arc_mutex_device("pic") + .add(|_| TestDevice { + pic_vector: Some(0x20), + eoi: true, + ..TestDevice::new("pic", &shared) + }) + .unwrap(); + let err = add_error(builder.arc_mutex_device("second-pic").add(|_| TestDevice { + pic_vector: Some(0x28), + ..TestDevice::new("second-pic", &shared) + })); + assert!(err.contains("pic handler already set"), "{err}"); + let err = add_error(builder.arc_mutex_device("second-eoi").add(|_| TestDevice { + eoi: true, + ..TestDevice::new("second-eoi", &shared) + })); + assert!(err.contains("eoi handler already set"), "{err}"); + let (chipset, _devices) = build(builder); + + assert_eq!(chipset.acknowledge_pic_interrupt(), Some(0x20)); + chipset.handle_eoi(4); + chipset.handle_eoi(9); + assert_eq!(shared.lock().eois, [4, 9]); + } + + const ECAM_BASE: u64 = 0xe000_0000; + + fn ecam(bus: u8, devfn: u8, offset: u16) -> u64 { + ECAM_BASE | (u64::from(bus) << 20) | (u64::from(devfn) << 12) | u64::from(offset) + } + + async fn ecam_read(chipset: &Chipset, bus: u8, devfn: u8, offset: u16) -> u32 { + let mut data = [0; 4]; + chipset + .mmio_read(0, ecam(bus, devfn, offset), &mut data) + .await; + u32::from_le_bytes(data) + } + + /// Adds a PCIe root complex named `rc0` covering buses 0-1, with one root + /// port `rp0` at device 1. + fn add_root_complex(builder: &ChipsetBuilder<'_>, msi: &pci_core::msi::MsiTarget) { + let rc = builder + .arc_mutex_device("rc0") + .try_add(|services| { + let mut mmio = services.register_mmio(); + let mut pio = services.register_pio(); + pcie::root::GenericPcieRootComplex::builder( + &mut mmio, + &mut pio, + 0..=1, + memory_range::MemoryRange::new(ECAM_BASE..ECAM_BASE + 0x20_0000), + ) + .root_ports( + vec![pcie::GenericPciePortDefinition { + name: "rp0".into(), + devfn: Some(0x08), + hotplug: false, + settings: Default::default(), + }], + msi, + ) + .build() + }) + .unwrap(); + builder.register_weak_mutex_pcie_enumerator(crate::BusId::new("rc0"), Box::new(rc)); + } + + // Test: A root complex with an integrated endpoint at device 0 and an + // endpoint behind root port `rp0`; the guest reads config space + // through ECAM, programs the root port's bus numbers, then reads + // again. + // Expected: The integrated endpoint answers on bus 0, the endpoint is + // unreachable until the root port forwards bus 1 and answers after, + // and a config write reaches it. + #[async_test] + async fn pcie_config_space_reaches_root_complex_devices(driver: DefaultDriver) { + let fixture = Fixture::new(&driver).await; + let shared = Arc::new(Mutex::new(Shared::default())); + let msi = pci_core::msi::MsiTarget::disconnected(); + let builder = fixture.builder(None); + add_root_complex(&builder, &msi); + builder + .arc_mutex_device("rciep") + .on_pcie_root_complex(crate::BusId::new("rc0"), 0) + .add(|_| TestDevice { + pci: Pci::NoSuggestedBdf, + read_fill: 0x11, + ..TestDevice::new("rciep", &shared) + }) + .unwrap(); + builder + .arc_mutex_device("endpoint") + .on_pcie_port(crate::BusId::new("rp0")) + .add(|_| TestDevice { + pci: Pci::NoSuggestedBdf, + read_fill: 0x22, + ..TestDevice::new("endpoint", &shared) + }) + .unwrap(); + let (chipset, _devices) = build(builder); + + assert_eq!(ecam_read(&chipset, 0, 0, 0).await, 0x1111_1111); + assert_ne!(ecam_read(&chipset, 0, 0x08, 0).await, !0); + assert_eq!(ecam_read(&chipset, 0, 0x10, 0).await, !0); + assert_eq!(ecam_read(&chipset, 1, 0, 0).await, !0); + + // Primary bus 0, secondary bus 1, subordinate bus 1. + chipset + .mmio_write(0, ecam(0, 0x08, 0x18), &0x0001_0100u32.to_le_bytes()) + .await; + assert_eq!(ecam_read(&chipset, 1, 0, 0).await, 0x2222_2222); + chipset + .mmio_write(0, ecam(1, 0, 0x10), &0xfeed_0000u32.to_le_bytes()) + .await; + assert_eq!( + shared.lock().accesses, + [access( + "endpoint", + "pci", + 0x10, + &0xfeed_0000u32.to_le_bytes() + )] + ); + } + + // Test: PCIe devices placed on a port and an enumerator that don't exist, a + // second device on an occupied root port, and an integrated endpoint + // on the root port's device number. + // Expected: Build fails and reports every misplaced device by name. + #[async_test] + async fn pcie_placement_errors_fail_build(driver: DefaultDriver) { + let fixture = Fixture::new(&driver).await; + let shared = Arc::new(Mutex::new(Shared::default())); + let msi = pci_core::msi::MsiTarget::disconnected(); + let builder = fixture.builder(None); + add_root_complex(&builder, &msi); + let pci = |name| TestDevice { + pci: Pci::NoSuggestedBdf, + ..TestDevice::new(name, &shared) + }; + builder + .arc_mutex_device("first") + .on_pcie_port(crate::BusId::new("rp0")) + .add(|_| pci("first")) + .unwrap(); + builder + .arc_mutex_device("second") + .on_pcie_port(crate::BusId::new("rp0")) + .add(|_| pci("second")) + .unwrap(); + builder + .arc_mutex_device("no-port") + .on_pcie_port(crate::BusId::new("rp9")) + .add(|_| pci("no-port")) + .unwrap(); + builder + .arc_mutex_device("no-rc") + .on_pcie_root_complex(crate::BusId::new("rc9"), 0) + .add(|_| pci("no-rc")) + .unwrap(); + builder + .arc_mutex_device("on-port") + .on_pcie_root_complex(crate::BusId::new("rc0"), 0x08) + .add(|_| pci("on-port")) + .unwrap(); + + let err = build_error(builder); + for expected in [ + "cannot attach second, port already occupied by first", + "cannot attach no-port, no valid pcie downstream port", + "cannot attach no-rc, no valid pcie enumerator", + "cannot attach on-port, port already occupied by rp0", + ] { + assert!(err.contains(expected), "missing {expected:?} in {err}"); + } + } + + // IGNORED: this test fails because of a known bug. The default + // `pci_cfg_read_with_routing` accepts only `devfn == 0`, although its docs + // say "function 0". The root complex passes the real devfn to integrated + // endpoints, so one at any device other than 0 reads as absent. The only + // current user (the AMD IOMMU) sits at device 0. Re-enable this test + // together with the fix by removing #[ignore]. + // + // Test: An integrated endpoint that only implements `pci_cfg_read` is + // placed at device 2 of the root complex and read through ECAM. + // Expected: Config reads at 0:2.0 reach the device. + #[async_test] + #[ignore = "known bug: default PCI routing only reaches integrated endpoints at devfn 0"] + async fn integrated_endpoint_at_nonzero_device_is_reachable(driver: DefaultDriver) { + let fixture = Fixture::new(&driver).await; + let shared = Arc::new(Mutex::new(Shared::default())); + let msi = pci_core::msi::MsiTarget::disconnected(); + let builder = fixture.builder(None); + add_root_complex(&builder, &msi); + builder + .arc_mutex_device("rciep") + .on_pcie_root_complex(crate::BusId::new("rc0"), 0x10) + .add(|_| TestDevice { + pci: Pci::NoSuggestedBdf, + read_fill: 0x33, + ..TestDevice::new("rciep", &shared) + }) + .unwrap(); + let (chipset, _devices) = build(builder); + assert_eq!(ecam_read(&chipset, 0, 0x10, 0).await, 0x3333_3333); + } + + // Test: After the chipset is built, add a device at runtime that maps an + // MMIO region, access it, then remove the device. + // Expected: The region reaches the device while it is present and reads all + // ones after removal. + #[async_test] + async fn dynamic_device_is_reachable_until_removed(driver: DefaultDriver) { + let fixture = Fixture::new(&driver).await; + let shared = Arc::new(Mutex::new(Shared::default())); + let (chipset, devices) = build(fixture.builder(None)); + + let (unit, _device) = devices + .add_dyn_device( + &fixture.source, + &fixture.units, + "dynamic", + async |mmio: &mut (dyn RegisterMmioIntercept + Send)| { + let mut region = mmio.new_io_region("bar", 0x1000); + region.map(0x9000_0000); + Ok(TestDevice { + region: Some(region), + read_fill: 0x77, + ..TestDevice::new("dynamic", &shared) + }) + }, + ) + .await + .unwrap(); + + let mut data = [0; 4]; + chipset.mmio_read(0, 0x9000_0ffc, &mut data).await; + assert_eq!(data, [0x77; 4]); + assert!(chipset.is_mmio(0x9000_0000)); + + unit.remove().await; + chipset.mmio_read(0, 0x9000_0ffc, &mut data).await; + assert_eq!(data, [!0; 4]); + assert!(!chipset.is_mmio(0x9000_0000)); + } + + // Test: Start, stop, save, reset, restore, and restart the VM's state units + // with a device that drives an interrupt line and a second device + // that opts out of saved state. + // Expected: Every transition reaches both devices, saved state includes + // only the device that didn't opt out, restore accepts it, and I/O + // works after the restart. + #[async_test] + async fn vm_state_transitions_reach_devices(driver: DefaultDriver) { + let mut fixture = Fixture::new(&driver).await; + let shared = Arc::new(Mutex::new(Shared::default())); + let (chipset, _devices) = { + let builder = fixture.builder(None); + builder + .arc_mutex_device("saved") + .add(|services| TestDevice { + mmio: vec![("saved-mmio", 0x1000..=0x1fff)], + read_fill: 0xaa, + line: Some(services.new_line( + chipset_device_resources::IRQ_LINE_SET, + "test", + 5, + )), + ..TestDevice::new("saved", &shared) + }) + .unwrap(); + builder + .arc_mutex_device("omitted") + .omit_saved_state() + .add(|_| TestDevice::new("omitted", &shared)) + .unwrap(); + build(builder) + }; + let take_events = || { + let mut events = std::mem::take(&mut shared.lock().events); + events.sort(); + events + }; + + fixture.units.start().await; + assert_eq!(take_events(), ["omitted:start", "saved:start"]); + fixture.units.stop().await; + assert_eq!(take_events(), ["omitted:stop", "saved:stop"]); + + let saved = fixture.units.save().await.unwrap(); + let names: Vec<_> = saved.iter().map(|unit| unit.name.as_str()).collect(); + assert!(names.contains(&"saved"), "{names:?}"); + assert!(!names.contains(&"omitted"), "{names:?}"); + + fixture.units.reset().await.unwrap(); + assert_eq!(take_events(), ["omitted:reset", "saved:reset"]); + fixture.units.restore(saved).await.unwrap(); + fixture.units.start().await; + assert_eq!(take_events(), ["omitted:start", "saved:start"]); + + let mut data = [0; 4]; + chipset.mmio_read(0, 0x1000, &mut data).await; + assert_eq!(data, [0xaa; 4]); + } + + #[derive(Default)] + struct RecordBreaks(Mutex>>); + + impl DebugEventHandler for RecordBreaks { + fn on_debug_break(&self, vp: Option) { + self.0.lock().push(vp); + } + } + + // Test: Through inspect, set an MMIO break filter on one address, a port + // I/O break filter on unclaimed ports, and tracing on all MMIO, then + // access claimed and unclaimed addresses from different VPs and + // inspect the MMIO ranges. + // Expected: Only accesses matching a break filter call the debug handler, + // with the accessing VP; accesses still complete normally; and + // inspect lists the claimed range under its device. + #[async_test] + async fn inspect_controls_debug_breaks_and_lists_ranges(driver: DefaultDriver) { + let fixture = Fixture::new(&driver).await; + let shared = Arc::new(Mutex::new(Shared::default())); + let breaks = Arc::new(RecordBreaks::default()); + let builder = fixture.builder_with_debug(None, breaks.clone()); + builder + .arc_mutex_device("a") + .add(|_| TestDevice { + mmio: vec![("a-mmio", 0x1000..=0x1fff)], + pio: vec![("a-pio", 0x60..=0x63)], + read_fill: 0xaa, + ..TestDevice::new("a", &shared) + }) + .unwrap(); + let (chipset, _devices) = build(builder); + + inspect::update("mmio/break_on", "0x1004", &*chipset) + .await + .unwrap(); + inspect::update("pio/break_on", "?", &*chipset) + .await + .unwrap(); + inspect::update("mmio/trace_on", "all", &*chipset) + .await + .unwrap(); + + let mut data = [0; 4]; + chipset.mmio_read(3, 0x1000, &mut data).await; + assert!(breaks.0.lock().is_empty()); + chipset.mmio_read(3, 0x1004, &mut data).await; + assert_eq!(data, [0xaa; 4]); + chipset.mmio_read(2, 0x8000, &mut data).await; + assert_eq!(data, [!0; 4]); + let mut byte = [0]; + chipset.io_read(1, 0x60, &mut byte).await; + chipset.io_read(1, 0x80, &mut byte).await; + assert_eq!(byte, [!0]); + assert_eq!(*breaks.0.lock(), [Some(3), Some(1)]); + + let mut inspection = inspect::inspect("mmio", &*chipset); + inspection.resolve().await; + let output = inspection.results().to_string(); + assert!(output.contains("0x1000-0x1fff"), "{output}"); + assert!(output.contains("a-mmio"), "{output}"); + } + + // Test: Add a device whose constructor fails, a device built by an async + // constructor, and a PCI device marked as externally managed with no + // bus. + // Expected: The failure is reported with the device name and cause, the + // async device answers I/O, and the external PCI device doesn't need + // a bus or address for the build to succeed. + #[async_test] + async fn device_builder_variants(driver: DefaultDriver) { + let fixture = Fixture::new(&driver).await; + let shared = Arc::new(Mutex::new(Shared::default())); + let builder = fixture.builder(None); + + let err = add_error( + builder + .arc_mutex_device::("broken") + .try_add(|_| Err(anyhow::anyhow!("no backing store"))), + ); + assert!(err.contains("could not initialize broken"), "{err}"); + assert!(err.contains("could not construct device"), "{err}"); + assert!(err.contains("no backing store"), "{err}"); + + builder + .arc_mutex_device("async") + .add_async(async |_| TestDevice { + mmio: vec![("async-mmio", 0x3000..=0x3fff)], + read_fill: 0x3a, + ..TestDevice::new("async", &shared) + }) + .await + .unwrap(); + builder + .arc_mutex_device("external") + .with_external_pci() + .add(|_| TestDevice { + pci: Pci::NoSuggestedBdf, + ..TestDevice::new("external", &shared) + }) + .unwrap(); + let (chipset, _devices) = build(builder); + + let mut data = [0; 4]; + chipset.mmio_read(0, 0x3000, &mut data).await; + assert_eq!(data, [0x3a; 4]); + } +}