Skip to main content

petri/vm/openvmm/
mod.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Code managing the lifetime of a `PetriVmOpenVmm`. All VMs live the same lifecycle:
5//! * A `PetriVmConfigOpenVmm` is built for the given firmware and architecture in `construct`.
6//! * The configuration is optionally modified from the defaults using the helpers in `modify`.
7//! * The `PetriVmOpenVmm` is started by the code in `start`.
8//! * The VM is interacted with through the methods in `runtime`.
9//! * The VM is either shut down by the code in `runtime`, or gets dropped and cleaned up automatically.
10
11mod construct;
12#[cfg(target_os = "linux")]
13mod hugetlb;
14mod modify;
15mod mshv;
16mod runtime;
17mod start;
18
19#[cfg(target_os = "linux")]
20pub use hugetlb::HUGETLB_2MB_PAGE_SIZE;
21#[cfg(target_os = "linux")]
22pub use hugetlb::ensure_2mb_hugetlb_pages;
23pub use runtime::OpenVmmFramebufferAccess;
24pub use runtime::OpenVmmInspector;
25pub use runtime::PetriVmOpenVmm;
26
27use crate::Disk;
28use crate::DiskPath;
29use crate::Firmware;
30use crate::ModifyFn;
31use crate::OpenHclServicingFlags;
32use crate::OpenvmmLogConfig;
33use crate::PetriLogFile;
34use crate::PetriVmConfig;
35use crate::PetriVmResources;
36use crate::PetriVmRuntimeConfig;
37use crate::PetriVmgsDisk;
38use crate::PetriVmgsResource;
39use crate::PetriVmmBackend;
40use crate::VmmQuirks;
41use crate::linux_direct_serial_agent::LinuxDirectSerialAgent;
42use crate::vm::PetriVmProperties;
43use anyhow::Context;
44use async_trait::async_trait;
45use chipset_resources::acpi_power_button::PowerButtonRpc;
46use disk_backend_resources::DiskLayerDescription;
47use disk_backend_resources::LayeredDiskHandle;
48use disk_backend_resources::layer::DiskLayerHandle;
49use disk_backend_resources::layer::RamDiskLayerHandle;
50use disk_backend_resources::layer::SqliteAutoCacheDiskLayerHandle;
51use disk_backend_resources::layer::SqliteDiskLayerFormatParams;
52use disk_backend_resources::layer::SqliteDiskLayerHandle;
53use get_resources::ged::FirmwareEvent;
54use guid::Guid;
55use hyperv_ic_resources::shutdown::ShutdownRpc;
56use mesh::Receiver;
57use mesh::Sender;
58use net_backend_resources::mac_address::MacAddress;
59use openvmm_defs::config::Config;
60use openvmm_helpers::disk::OpenDiskOptions;
61use openvmm_helpers::disk::open_disk_type;
62use pal_async::DefaultDriver;
63use pal_async::socket::PolledSocket;
64use pal_async::task::Task;
65use petri_artifacts_common::tags::GuestQuirksInner;
66use petri_artifacts_common::tags::MachineArch;
67use petri_artifacts_core::ArtifactResolver;
68use petri_artifacts_core::ResolvedArtifact;
69use std::path::Path;
70use std::path::PathBuf;
71use std::sync::Arc;
72use std::time::Duration;
73use tempfile::TempPath;
74use unix_socket::UnixListener;
75use vm_resource::IntoResource;
76use vm_resource::Resource;
77use vm_resource::kind::DiskHandleKind;
78use vm_resource::kind::VirtioDeviceHandle;
79use vmgs_resources::VmgsDisk;
80use vmgs_resources::VmgsResource;
81
82/// The instance guid for the MANA nic automatically added when specifying [`PetriVmConfigOpenVmm::with_nic`]
83const MANA_INSTANCE: Guid = guid::guid!("f9641cf4-d915-4743-a7d8-efa75db7b85a");
84
85/// The MAC address used by the NIC assigned with [`PetriVmConfigOpenVmm::with_nic`].
86pub const NIC_MAC_ADDRESS: MacAddress = MacAddress::new([0x00, 0x15, 0x5D, 0x12, 0x12, 0x12]);
87
88/// OpenVMM Petri Backend
89#[derive(Debug)]
90pub struct OpenVmmPetriBackend {
91    openvmm_path: ResolvedArtifact,
92}
93
94impl crate::PetriVmBuilder<OpenVmmPetriBackend> {
95    /// Add a single-port Linux virtio console, captured in `hvc0.log`.
96    ///
97    /// Linux-direct boot selects `console=hvc0` and requires initrd-owned agent
98    /// startup. UEFI guests select their console through their boot configuration.
99    /// The firmware UART is unchanged.
100    pub fn with_virtio_console(mut self) -> Self {
101        assert!(
102            matches!(
103                self.config.firmware,
104                Firmware::LinuxDirect { .. } | Firmware::Uefi { .. }
105            ) && self.config.firmware.os_flavor() == petri_artifacts_common::tags::OsFlavor::Linux
106                && self.config.firmware.isolation().is_none(),
107            "virtio-console requires Linux-direct or non-isolated Linux UEFI"
108        );
109        self.use_virtio_console = true;
110        self
111    }
112}
113
114impl OpenVmmPetriBackend {
115    /// Launch a separately supplied, protocol-compatible native executable.
116    pub fn from_binary(path: PathBuf) -> Self {
117        Self {
118            openvmm_path: ResolvedArtifact::from_local_path(path),
119        }
120    }
121}
122
123#[async_trait]
124impl PetriVmmBackend for OpenVmmPetriBackend {
125    type VmmConfig = PetriVmConfigOpenVmm;
126    type VmRuntime = PetriVmOpenVmm;
127    const SUPPORTS_VMBUS: bool = true;
128    const SUPPORTS_FILE_SHARING: bool = cfg!(any(windows, target_os = "linux"));
129
130    fn check_compat(firmware: &Firmware, arch: MachineArch) -> bool {
131        if matches!(
132            firmware,
133            Firmware::Uefi {
134                guest: crate::UefiGuest::Mshv(_),
135                ..
136            }
137        ) {
138            return cfg!(any(windows, target_os = "linux"))
139                && arch == MachineArch::X86_64
140                && MachineArch::host() == MachineArch::X86_64;
141        }
142        !(firmware.is_openhcl() && (!cfg!(windows) || arch == MachineArch::Aarch64))
143    }
144
145    fn quirks(firmware: &Firmware) -> (GuestQuirksInner, VmmQuirks) {
146        (
147            firmware.quirks().openvmm,
148            VmmQuirks {
149                // Workaround for #3897
150                flaky_boot: firmware.is_pcat().then_some(Duration::from_secs(15)),
151            },
152        )
153    }
154
155    fn default_servicing_flags() -> OpenHclServicingFlags {
156        OpenHclServicingFlags {
157            enable_nvme_keepalive: true,
158            enable_mana_keepalive: true,
159            override_version_checks: false,
160            stop_timeout_hint_secs: None,
161        }
162    }
163
164    fn create_guest_dump_disk() -> anyhow::Result<
165        Option<(
166            Arc<TempPath>,
167            Box<dyn FnOnce() -> anyhow::Result<Box<dyn fatfs::ReadWriteSeek>>>,
168        )>,
169    > {
170        Ok(None) // TODO #2403
171    }
172
173    fn build_custom_init_script(_pipette_path: &str) -> Option<String> {
174        None
175    }
176
177    fn new(resolver: &ArtifactResolver<'_>, arch: MachineArch) -> Self {
178        // OpenVMM guests must have the same arch as the host
179        assert_eq!(arch, MachineArch::host());
180        OpenVmmPetriBackend {
181            openvmm_path: resolver
182                .require(petri_artifacts_vmm_test::artifacts::OPENVMM_NATIVE)
183                .erase(),
184        }
185    }
186
187    async fn run(
188        self,
189        config: PetriVmConfig,
190        modify_vmm_config: Option<ModifyFn<Self::VmmConfig>>,
191        resources: &PetriVmResources,
192        properties: &PetriVmProperties,
193    ) -> anyhow::Result<(Self::VmRuntime, PetriVmRuntimeConfig)> {
194        let mut config =
195            PetriVmConfigOpenVmm::new(&self.openvmm_path, config, resources, properties).await?;
196
197        if let Some(f) = modify_vmm_config {
198            config = f.0(config);
199        }
200
201        config.run().await
202    }
203}
204
205/// Reusable OpenVMM configuration for tests that launch the same VM recipe in
206/// multiple worker processes.
207pub struct OpenVmmRelaunchConfig {
208    builder: crate::PetriVmBuilder<OpenVmmPetriBackend>,
209    /// Holds the disk write files shared by all launched workers.
210    _diff_dir: tempfile::TempDir,
211    /// Bounds the entire recipe, including time between worker launches.
212    _watchdog_task: Option<Task<()>>,
213}
214
215impl crate::PetriVmBuilder<OpenVmmPetriBackend> {
216    /// Prepare this configuration for launching multiple OpenVMM workers with
217    /// the same VM recipe.
218    ///
219    /// Differencing disks store their writes in files shared by all launched
220    /// workers, so a restored guest sees the disk writes made before the save.
221    pub fn prepare_openvmm_relaunch(self) -> anyhow::Result<OpenVmmRelaunchConfig> {
222        anyhow::ensure!(
223            self.modify_vmm_config.is_none(),
224            "OpenVMM relaunch configurations do not support modify_backend"
225        );
226
227        let mut builder = self.add_boot_disk()?.add_agent_disks()?;
228        if builder.uses_pipette_as_init() && builder.resources.prebuilt_initrd.is_none() {
229            builder.resources.prebuilt_initrd = Some(builder.prepare_initrd()?);
230        }
231
232        let diff_dir = tempfile::tempdir().context("failed to create disk write directory")?;
233        let config = &mut builder.config;
234        let drive_disks = config
235            .vmbus_storage_controllers
236            .values_mut()
237            .flat_map(|controller| controller.drives.values_mut())
238            .chain(config.pcie_nvme_drives.iter_mut().map(|d| &mut d.drive))
239            .chain(
240                config
241                    .pcie_virtio_blk_drives
242                    .iter_mut()
243                    .map(|d| &mut d.drive),
244            )
245            .chain(
246                config
247                    .firmware
248                    .ide_controllers_mut()
249                    .into_iter()
250                    .flatten()
251                    .flatten()
252                    .flatten(),
253            )
254            .filter_map(|drive| drive.disk.as_mut());
255        let vmgs_disk = match &mut config.vmgs {
256            PetriVmgsResource::Disk(vmgs)
257            | PetriVmgsResource::ReprovisionOnFailure(vmgs)
258            | PetriVmgsResource::ReprovisionSingle(vmgs) => Some(&mut vmgs.disk),
259            PetriVmgsResource::Ephemeral => None,
260        };
261        for (i, disk) in drive_disks.chain(vmgs_disk).enumerate() {
262            if let Disk::Differencing(base) = disk {
263                *disk = Disk::SqliteDifferencing {
264                    base: base.clone(),
265                    dbhd_path: diff_dir.path().join(format!("disk{i}.dbhd")),
266                };
267            }
268        }
269
270        let watchdog_task =
271            Self::start_watchdog_timer(&builder.resources.driver, builder.watchdog_timeout);
272        Ok(OpenVmmRelaunchConfig {
273            builder,
274            _diff_dir: diff_dir,
275            _watchdog_task: watchdog_task,
276        })
277    }
278}
279
280impl OpenVmmRelaunchConfig {
281    async fn config(
282        &self,
283        memory_backing_file: impl Into<PathBuf>,
284    ) -> anyhow::Result<PetriVmConfigOpenVmm> {
285        Ok(PetriVmConfigOpenVmm::new(
286            &self.builder.backend.openvmm_path,
287            self.builder.config.clone(),
288            &self.builder.resources,
289            &self.builder.properties(),
290        )
291        .await?
292        .with_memory_backing_file(memory_backing_file))
293    }
294
295    /// Launch a new worker using this VM recipe and file-backed guest memory.
296    pub async fn launch(
297        &self,
298        memory_backing_file: impl Into<PathBuf>,
299    ) -> anyhow::Result<PetriVmOpenVmm> {
300        let (vm, _) = self.config(memory_backing_file).await?.run_core().await?;
301        Ok(vm)
302    }
303
304    /// Launch a new worker using this VM recipe and restore its state from
305    /// serialized snapshot bytes.
306    pub async fn restore(
307        &self,
308        memory_backing_file: impl Into<PathBuf>,
309        saved_state: &[u8],
310    ) -> anyhow::Result<PetriVmOpenVmm> {
311        let (vm, _) = self
312            .config(memory_backing_file)
313            .await?
314            .run_restore(saved_state)
315            .await?;
316        Ok(vm)
317    }
318}
319
320/// Configuration state for a test VM.
321pub struct PetriVmConfigOpenVmm {
322    guest_shares: std::collections::HashMap<String, crate::GuestShare>,
323    private_virtio_devices: Vec<(&'static str, Resource<VirtioDeviceHandle>)>,
324    // Direct configuration related information.
325    runtime_config: PetriVmRuntimeConfig,
326    arch: MachineArch,
327    host_log_levels: Option<OpenvmmLogConfig>,
328    config: Config,
329    skip_save_restore: bool,
330
331    // Mesh host
332    mesh: mesh_process::Mesh,
333
334    // Runtime resources
335    resources: PetriVmResourcesOpenVmm,
336
337    // Logging
338    openvmm_log_file: PetriLogFile,
339
340    // File-backed guest memory.
341    memory_backing_file: Option<PathBuf>,
342
343    // The private-memory setting explicitly requested via
344    // `MemoryConfig::private_memory`, preserved so that backend methods which
345    // force shared memory (e.g. `with_hugepages`, `with_memory_backing_file`)
346    // can fail when the caller explicitly asked for private memory rather than
347    // silently downgrading it.
348    requested_private_memory: Option<bool>,
349
350    // Resources that are only used during startup.
351    ged: Option<get_resources::ged::GuestEmulationDeviceHandle>,
352    framebuffer_view: Option<framebuffer::View>,
353
354    // Deferred IOMMU configuration: (rc_name, iommu_config) pairs resolved
355    // against pcie_root_complexes at VM start time.
356    pending_iommu: Vec<(String, openvmm_defs::config::PcieIommuConfig)>,
357}
358/// Various channels and resources used to interact with the VM while it is running.
359struct PetriVmResourcesOpenVmm {
360    log_stream_tasks: Vec<Task<anyhow::Result<()>>>,
361    firmware_event_recv: Receiver<FirmwareEvent>,
362    ipmi_sel_event_recv: Receiver<get_resources::ged::IpmiSelEvent>,
363    shutdown_ic_send: Option<Sender<ShutdownRpc>>,
364    acpi_power_button_send: Option<Sender<PowerButtonRpc>>,
365    kvp_ic_send: Option<Sender<hyperv_ic_resources::kvp::KvpConnectRpc>>,
366    ged_send: Option<Sender<get_resources::ged::GuestEmulationRequest>>,
367    pipette_listener: PolledSocket<UnixListener>,
368    vtl2_pipette_listener: Option<PolledSocket<UnixListener>>,
369    linux_direct_serial_agent: Option<LinuxDirectSerialAgent>,
370
371    /// When set, the host connects to pipette via TCP through consomme
372    /// port forwarding instead of accepting on the Unix socket listener.
373    /// Used for Windows no-vmbus guests where virtio-vsock is unavailable.
374    /// The receiver yields the OS-assigned host port once the consomme
375    /// resolver has bound the socket.
376    tcp_pipette_port: Option<mesh::OneshotReceiver<u16>>,
377
378    // Externally injected management stuff also needed at runtime.
379    driver: DefaultDriver,
380    openvmm_path: ResolvedArtifact,
381    output_dir: PathBuf,
382
383    // TempPaths that cannot be dropped until the end.
384    vtl2_vsock_path: Option<TempPath>,
385    _vsock_path: TempPath,
386
387    // properties needed at runtime
388    properties: PetriVmProperties,
389
390    // vmswitch DirectIO switch port handles, held in the test (parent)
391    // process for the lifetime of the child VMM so the kernel port object
392    // survives until the VMM detaches.
393    #[cfg(windows)]
394    _switch_ports: Vec<vmswitch::kernel::SwitchPort>,
395}
396
397/// Discovers a usable Hyper-V virtual switch for `-net dio` tests.
398///
399/// Tries the well-known Default Switch GUID first (which is provisioned
400/// automatically when Hyper-V is installed). If that switch is not
401/// available (e.g. it was removed, or this host uses a different default
402/// switch SKU), falls back to enumerating all HCN networks and returning
403/// the first one reported.
404///
405/// Returns `None` when no switch can be opened — typically because
406/// Hyper-V is not installed, the user lacks privileges, or
407/// `computenetwork.dll` is missing.
408#[cfg(windows)]
409pub fn find_switch() -> Option<Guid> {
410    if vmswitch::hcn::Network::open(&vmswitch::hcn::DEFAULT_SWITCH).is_ok() {
411        return Some(vmswitch::hcn::DEFAULT_SWITCH);
412    }
413    let networks = match vmswitch::hcn::enumerate_networks() {
414        Ok(n) => n,
415        Err(e) => {
416            tracing::warn!(
417                error = &e as &dyn std::error::Error,
418                "failed to enumerate HCN networks"
419            );
420            return None;
421        }
422    };
423    networks.into_iter().find(|guid| {
424        if let Err(e) = vmswitch::hcn::Network::open(guid) {
425            tracing::debug!(
426                %guid,
427                error = &e as &dyn std::error::Error,
428                "skipping unopenable HCN network"
429            );
430            false
431        } else {
432            true
433        }
434    })
435}
436
437/// Discovers a usable Hyper-V virtual switch.
438///
439/// Always `None` on non-Windows platforms.
440#[cfg(not(windows))]
441pub fn find_switch() -> Option<Guid> {
442    None
443}
444
445fn ram_diff_layer() -> DiskLayerDescription {
446    RamDiskLayerHandle {
447        len: None,
448        sector_size: None,
449    }
450    .into_resource()
451    .into()
452}
453
454/// Returns a SQLite diff layer stored in `dbhd_path`, creating the file if it
455/// doesn't exist yet.
456fn sqlite_diff_layer(dbhd_path: &Path) -> DiskLayerDescription {
457    SqliteDiskLayerHandle {
458        dbhd_path: dbhd_path.display().to_string(),
459        format_dbhd: (!dbhd_path.exists()).then_some(SqliteDiskLayerFormatParams {
460            logically_read_only: false,
461            len: None,
462        }),
463    }
464    .into_resource()
465    .into()
466}
467
468fn layered_disk(
469    diff: DiskLayerDescription,
470    base: Vec<DiskLayerDescription>,
471) -> Resource<DiskHandleKind> {
472    LayeredDiskHandle {
473        layers: std::iter::once(diff).chain(base).collect(),
474    }
475    .into_resource()
476}
477
478/// Memory differencing disk over a local base disk.
479async fn memdiff_disk(path: &Path) -> anyhow::Result<Resource<DiskHandleKind>> {
480    Ok(layered_disk(
481        ram_diff_layer(),
482        local_base_layers(path).await?,
483    ))
484}
485
486/// Memory differencing disk over a remote base disk.
487fn memdiff_remote_disk(url: &str) -> anyhow::Result<Resource<DiskHandleKind>> {
488    Ok(layered_disk(ram_diff_layer(), remote_base_layers(url)))
489}
490
491/// SQLite differencing disk over a local base disk, storing writes in
492/// `dbhd_path`.
493async fn sqldiff_disk(path: &Path, dbhd_path: &Path) -> anyhow::Result<Resource<DiskHandleKind>> {
494    Ok(layered_disk(
495        sqlite_diff_layer(dbhd_path),
496        local_base_layers(path).await?,
497    ))
498}
499
500/// SQLite differencing disk over a remote base disk, storing writes in
501/// `dbhd_path`.
502fn sqldiff_remote_disk(url: &str, dbhd_path: &Path) -> anyhow::Result<Resource<DiskHandleKind>> {
503    Ok(layered_disk(
504        sqlite_diff_layer(dbhd_path),
505        remote_base_layers(url),
506    ))
507}
508
509async fn local_base_layers(path: &Path) -> anyhow::Result<Vec<DiskLayerDescription>> {
510    let disk = open_disk_type(
511        path,
512        OpenDiskOptions {
513            read_only: true,
514            direct: false,
515        },
516    )
517    .await
518    .with_context(|| format!("failed to open disk: {}", path.display()))?;
519    Ok(vec![DiskLayerHandle(disk).into_resource().into()])
520}
521
522fn remote_base_layers(url: &str) -> Vec<DiskLayerDescription> {
523    // Strip query parameters and fragments before checking the file extension.
524    let url_path = url.split(['?', '#']).next().unwrap_or(url);
525    let format = if url_path.ends_with(".vhd") || url_path.ends_with(".vmgs") {
526        disk_backend_resources::BlobDiskFormat::FixedVhd1
527    } else {
528        disk_backend_resources::BlobDiskFormat::Flat
529    };
530
531    let cache_dir = super::petri_disk_cache_dir();
532
533    // For VHD1-formatted blobs, let the auto-cache layer derive the cache key
534    // from the VHD's unique ID (a UUID embedded in the footer). This means the
535    // cache automatically invalidates when the image is replaced with a new one,
536    // even if the filename stays the same. For flat-format blobs (e.g. ISOs),
537    // fall back to the URL filename since there's no embedded ID.
538    let cache_key = match format {
539        disk_backend_resources::BlobDiskFormat::FixedVhd1 => None,
540        disk_backend_resources::BlobDiskFormat::Flat => {
541            Some(url_path.rsplit('/').next().unwrap_or(url_path).to_owned())
542        }
543    };
544
545    vec![
546        DiskLayerDescription {
547            read_cache: true,
548            write_through: false,
549            layer: SqliteAutoCacheDiskLayerHandle {
550                cache_path: cache_dir,
551                cache_key,
552            }
553            .into_resource(),
554        },
555        DiskLayerHandle(
556            disk_backend_resources::BlobDiskHandle {
557                url: url.to_owned(),
558                format,
559            }
560            .into_resource(),
561        )
562        .into_resource()
563        .into(),
564    ]
565}
566
567async fn memdiff_vmgs(vmgs: &PetriVmgsResource) -> anyhow::Result<VmgsResource> {
568    async fn convert_disk(disk: &PetriVmgsDisk) -> anyhow::Result<VmgsDisk> {
569        Ok(VmgsDisk {
570            disk: petri_disk_to_openvmm(&disk.disk).await?,
571            encryption_policy: disk.encryption_policy,
572        })
573    }
574
575    Ok(match vmgs {
576        PetriVmgsResource::Disk(disk) => VmgsResource::Disk(convert_disk(disk).await?),
577        PetriVmgsResource::ReprovisionOnFailure(disk) => {
578            VmgsResource::ReprovisionOnFailure(convert_disk(disk).await?)
579        }
580        PetriVmgsResource::ReprovisionSingle(disk) => {
581            VmgsResource::ReprovisionSingle(convert_disk(disk).await?)
582        }
583        PetriVmgsResource::Ephemeral => VmgsResource::Ephemeral,
584    })
585}
586
587async fn petri_disk_to_openvmm(disk: &Disk) -> anyhow::Result<Resource<DiskHandleKind>> {
588    Ok(match disk {
589        Disk::Memory(len) => LayeredDiskHandle::single_layer(RamDiskLayerHandle {
590            len: Some(*len),
591            sector_size: None,
592        })
593        .into_resource(),
594        Disk::Differencing(DiskPath::Local(path)) => memdiff_disk(path).await?,
595        Disk::Differencing(DiskPath::Remote { url }) => memdiff_remote_disk(url)?,
596        Disk::SqliteDifferencing {
597            base: DiskPath::Local(path),
598            dbhd_path,
599        } => sqldiff_disk(path, dbhd_path).await?,
600        Disk::SqliteDifferencing {
601            base: DiskPath::Remote { url },
602            dbhd_path,
603        } => sqldiff_remote_disk(url, dbhd_path)?,
604        Disk::Persistent(path) => {
605            open_disk_type(
606                path.as_ref(),
607                OpenDiskOptions {
608                    read_only: false,
609                    direct: false,
610                },
611            )
612            .await?
613        }
614        Disk::Temporary(path) => {
615            open_disk_type(
616                path.as_ref(),
617                OpenDiskOptions {
618                    read_only: false,
619                    direct: false,
620                },
621            )
622            .await?
623        }
624    })
625}