Skip to main content

petri/vm/openvmm/
construct.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Contains [`PetriVmConfigOpenVmm::new`], which builds a [`PetriVmConfigOpenVmm`] with all
5//! default settings for a given [`Firmware`] and [`MachineArch`].
6
7use super::PetriVmConfigOpenVmm;
8use super::PetriVmResourcesOpenVmm;
9use crate::Drive;
10use crate::EfiDiagnosticsLogLevel;
11use crate::Firmware;
12use crate::IgvmFirmwareSource;
13use crate::IsolationType;
14use crate::MemoryConfig;
15use crate::OpenHclConfig;
16use crate::PcieNvmeDrive;
17use crate::PcieVirtioBlkDrive;
18use crate::PetriLogSource;
19use crate::PetriVmConfig;
20use crate::PetriVmResources;
21use crate::PetriVmgsResource;
22use crate::ProcessorTopology;
23use crate::SIZE_1_MB;
24use crate::SecureBootTemplate;
25use crate::TpmConfig;
26use crate::UefiConfig;
27use crate::VmbusStorageController;
28use crate::VmbusStorageType;
29use crate::linux_direct_serial_agent::LinuxDirectSerialAgent;
30use crate::openvmm::memdiff_vmgs;
31use crate::openvmm::petri_disk_to_openvmm;
32use crate::vm::PetriVmProperties;
33use crate::vm::append_cmdline;
34use anyhow::Context;
35use framebuffer::FRAMEBUFFER_SIZE;
36use framebuffer::Framebuffer;
37use framebuffer::FramebufferAccess;
38use fs_err::File;
39use futures::StreamExt;
40use get_resources::crash::GuestCrashDeviceHandle;
41use get_resources::ged::FirmwareEvent;
42use guid::Guid;
43use hyperv_ic_resources::shutdown::ShutdownIcHandle;
44use ide_resources::GuestMedia;
45use ide_resources::IdeDeviceConfig;
46use mesh_process::Mesh;
47use nvme_resources::NamespaceDefinition;
48use nvme_resources::NvmeControllerHandle;
49use openvmm_defs::config::Config;
50use openvmm_defs::config::DEFAULT_ACPI_POWER_BUTTON_IRQ_X64;
51use openvmm_defs::config::DEFAULT_ACPI_POWER_BUTTON_SPI_AARCH64;
52use openvmm_defs::config::DEFAULT_PCAT_BOOT_ORDER;
53use openvmm_defs::config::DeviceVtl;
54use openvmm_defs::config::HypervisorConfig;
55use openvmm_defs::config::IgvmPersonality;
56use openvmm_defs::config::LateMapVtl0MemoryPolicy;
57use openvmm_defs::config::LoadMode;
58use openvmm_defs::config::NumaNode;
59use openvmm_defs::config::NumaTopology;
60use openvmm_defs::config::PcieDeviceConfig;
61use openvmm_defs::config::ProcessorTopologyConfig;
62use openvmm_defs::config::UartId;
63use openvmm_defs::config::VmbusConfig;
64use openvmm_defs::config::VpAssignment;
65use openvmm_defs::config::VpciDeviceConfig;
66use openvmm_defs::config::Vtl2BaseAddressType;
67use openvmm_defs::config::Vtl2Config;
68use openvmm_helpers::config::supports_acpi_power_button;
69use openvmm_pcat_locator::RomFileLocation;
70use pal_async::DefaultDriver;
71use pal_async::socket::PolledSocket;
72use pal_async::task::Spawn;
73use pal_async::task::Task;
74use petri_artifacts_common::tags::MachineArch;
75use petri_artifacts_core::ResolvedArtifact;
76use pipette_client::PIPETTE_PORT;
77use scsidisk_resources::SimpleScsiDiskHandle;
78use scsidisk_resources::SimpleScsiDvdHandle;
79use serial_16550_resources::ComPort;
80use serial_core::resources::DisconnectedSerialBackendHandle;
81use serial_socket::net::OpenSocketSerialConfig;
82use sparse_mmap::alloc_shared_memory;
83use std::collections::HashMap;
84use storvsp_resources::ScsiControllerHandle;
85use storvsp_resources::ScsiDeviceAndPath;
86use storvsp_resources::ScsiPath;
87use tempfile::TempPath;
88use tpm_resources::TpmDeviceHandle;
89use tpm_resources::TpmRegisterLayout;
90use tpm_vmgs::tpm_nvram_file_id;
91use uidevices_resources::SynthVideoHandle;
92use unix_socket::UnixListener;
93use unix_socket::UnixStream;
94use video_core::SharedFramebufferHandle;
95use virtio_resources::VirtioPciDeviceHandle;
96use virtio_resources::blk::VirtioBlkHandle;
97use virtio_resources::vsock::VirtioVsockHandle;
98#[cfg(target_os = "linux")]
99use virtio_resources::vsock::VirtioVsockVhostHandle;
100use vm_manifest_builder::VmChipsetResult;
101use vm_manifest_builder::VmManifestBuilder;
102use vm_resource::IntoResource;
103use vm_resource::Resource;
104use vm_resource::kind::SerialBackendHandle;
105use vm_resource::kind::VirtioDeviceHandle;
106use vm_resource::kind::VmbusDeviceHandleKind;
107use vmbus_serial_resources::VmbusSerialDeviceHandle;
108use vmbus_serial_resources::VmbusSerialPort;
109use vmcore::non_volatile_store::resources::EphemeralNonVolatileStoreHandle;
110use vmgs_resources::GuestStateEncryptionPolicy;
111use vmgs_resources::VmgsFileHandle;
112use vmotherboard::ChipsetDeviceHandle;
113
114impl PetriVmConfigOpenVmm {
115    /// Create a new VM configuration.
116    pub async fn new(
117        openvmm_path: &ResolvedArtifact,
118        petri_vm_config: PetriVmConfig,
119        resources: &PetriVmResources,
120        properties: &PetriVmProperties,
121    ) -> anyhow::Result<Self> {
122        let PetriVmConfig {
123            name: _,
124            arch,
125            host_log_levels,
126            firmware,
127            hibernation_enabled,
128            ipmi_enabled,
129            memory,
130            proc_topology,
131            nested_virt_enabled,
132            vmgs,
133            tpm: tpm_config,
134            vmbus_storage_controllers,
135            pcie_nvme_drives,
136            pcie_virtio_blk_drives,
137            physical_nvme_devices,
138            guest_shares,
139        } = petri_vm_config;
140
141        if !physical_nvme_devices.is_empty() {
142            anyhow::bail!("Physical NVMe devices are only supported with the Hyper-V backend");
143        }
144
145        if matches!(
146            firmware.openhcl_firmware(),
147            Some(IgvmFirmwareSource::VmgsOrInBox)
148        ) {
149            anyhow::bail!("loading OpenHCL from VMGS is only supported by the Hyper-V backend");
150        }
151
152        tracing::debug!(?firmware, ?arch, "Petri VM firmware configuration");
153
154        let PetriVmResources {
155            driver,
156            log_source,
157            prebuilt_initrd,
158        } = resources;
159        anyhow::ensure!(
160            !properties.use_virtio_console
161                || !firmware.is_linux_direct()
162                || !properties.using_vtl0_pipette
163                || properties.external_pipette
164                || prebuilt_initrd.is_some(),
165            "virtio-console requires an initrd-owned Linux-direct Pipette"
166        );
167        let vhost_vsock_guest_cid: Option<u32> = cfg_select! {
168            target_os = "linux" => properties.vhost_vsock_guest_cid,
169            _ => None,
170        };
171
172        let mesh = Mesh::new("petri_mesh".to_string())?;
173
174        let setup = PetriVmConfigSetupCore {
175            arch,
176            firmware: &firmware,
177            hibernation_enabled,
178            ipmi_enabled,
179            driver,
180            logger: log_source,
181            vmgs: &vmgs,
182            tpm_config: tpm_config.as_ref(),
183            mesh: &mesh,
184            openvmm_path,
185            pipette_rdinit_param: prebuilt_initrd.as_ref().map(|x| x.rdinit_param.clone()),
186            external_pipette: properties.external_pipette,
187            enable_serial: properties.enable_serial,
188            use_virtio_console: properties.use_virtio_console,
189            use_virtio_vsock: properties.use_virtio_vsock,
190            no_vmbus: properties.no_vmbus,
191            no_hv: properties.no_hv,
192        };
193
194        let mut chipset = VmManifestBuilder::new(
195            match firmware {
196                Firmware::LinuxDirect { .. } => {
197                    vm_manifest_builder::BaseChipsetType::HyperVGen2LinuxDirect
198                }
199                Firmware::IgvmLinuxDirect { .. } => {
200                    vm_manifest_builder::BaseChipsetType::EnlightenedLinuxDirect
201                }
202                Firmware::OpenhclLinuxDirect { .. } => {
203                    vm_manifest_builder::BaseChipsetType::HclHost
204                }
205                Firmware::OpenhclUefi { .. } => vm_manifest_builder::BaseChipsetType::HclHost,
206                Firmware::Pcat { .. } => vm_manifest_builder::BaseChipsetType::HypervGen1,
207                Firmware::Uefi { .. } => vm_manifest_builder::BaseChipsetType::HypervGen2Uefi,
208                Firmware::OpenhclPcat { .. } => todo!("OpenVMM OpenHCL PCAT"),
209            },
210            match arch {
211                MachineArch::X86_64 => vm_manifest_builder::MachineArch::X86_64,
212                MachineArch::Aarch64 => vm_manifest_builder::MachineArch::Aarch64,
213            },
214        );
215
216        let mut load_mode = setup.load_firmware()?;
217
218        // A prepared initrd may contain either Petri's agent or a caller's
219        // bootstrap. Use it consistently with the selected rdinit parameter.
220        if let (Some(prebuilt), LoadMode::Linux { initrd, .. }) = (prebuilt_initrd, &mut load_mode)
221        {
222            let file = std::fs::File::open(prebuilt.path.as_ref()).with_context(|| {
223                format!(
224                    "failed to open prebuilt initrd at {}",
225                    prebuilt.path.as_ref().display()
226                )
227            })?;
228            *initrd = Some(file);
229        }
230
231        let (emulated_serial_config, mut log_stream_tasks, linux_direct_serial_agent) =
232            if !properties.enable_serial {
233                // No emulated serial backends (OpenHCL VMBus serial stubs may still exist)
234                ([None, None, None, None], Vec::new(), None)
235            } else {
236                let SerialData {
237                    emulated_serial_config,
238                    serial_tasks,
239                    linux_direct_serial_agent,
240                } = setup.configure_serial(log_source)?;
241                (
242                    emulated_serial_config,
243                    serial_tasks,
244                    linux_direct_serial_agent,
245                )
246            };
247        let mut emulated_serial_config = emulated_serial_config;
248        let mut private_virtio_devices = Vec::new();
249        if properties.use_virtio_console {
250            let (host, backend) = setup
251                .create_serial_stream()
252                .context("failed to create virtio-console stream")?;
253            log_stream_tasks.push(driver.spawn(
254                "virtio-console",
255                crate::log_task(log_source.log_file("hvc0")?, host, "virtio-console"),
256            ));
257            private_virtio_devices.push((
258                "petri-console-",
259                virtio_resources::console::VirtioConsoleHandle { backend }.into_resource(),
260            ));
261        }
262
263        let (video_dev, framebuffer, framebuffer_view) = match setup.config_video()? {
264            Some((v, fb, fba)) => {
265                chipset = chipset.with_framebuffer();
266                (Some(v), Some(fb), Some(fba.view()?))
267            }
268            None => (None, None, None),
269        };
270
271        if properties.no_vmbus {
272            chipset = chipset.without_vmbus();
273        }
274
275        let (ide_disks, storvsp_ide_handles) =
276            ide_controllers_to_openvmm(firmware.ide_controllers()).await?;
277        let (mut vmbus_devices, vpci_devices) =
278            vmbus_storage_controllers_to_openvmm(&vmbus_storage_controllers).await?;
279
280        let mut pcie_devices = Vec::new();
281        for PcieNvmeDrive {
282            port_name,
283            nsid,
284            drive: Drive { disk, .. },
285        } in pcie_nvme_drives
286        {
287            let disk = disk.ok_or_else(|| {
288                anyhow::anyhow!(
289                    "missing disk for PCIe NVMe drive on port '{port_name}' (nsid {nsid})"
290                )
291            })?;
292            let disk = petri_disk_to_openvmm(&disk).await?;
293            pcie_devices.push(PcieDeviceConfig {
294                port_name,
295                resource: NvmeControllerHandle {
296                    subsystem_id: Guid::new_random(),
297                    max_io_queues: 64,
298                    msix_count: 64,
299                    namespaces: vec![NamespaceDefinition {
300                        nsid,
301                        read_only: false,
302                        disk,
303                    }],
304                    requests: None,
305                }
306                .into_resource(),
307            });
308        }
309
310        for PcieVirtioBlkDrive {
311            port_name,
312            drive: Drive { disk, .. },
313        } in pcie_virtio_blk_drives
314        {
315            let disk = disk.ok_or_else(|| {
316                anyhow::anyhow!("missing disk for PCIe virtio-blk drive on port '{port_name}'")
317            })?;
318            let disk = petri_disk_to_openvmm(&disk).await?;
319            pcie_devices.push(PcieDeviceConfig {
320                port_name,
321                resource: VirtioPciDeviceHandle(
322                    VirtioBlkHandle {
323                        disk,
324                        read_only: false,
325                        serial: None,
326                        options: Default::default(),
327                    }
328                    .into_resource(),
329                )
330                .into_resource(),
331            });
332        }
333
334        if !storvsp_ide_handles.is_empty() {
335            anyhow::ensure!(
336                !properties.no_vmbus,
337                "IDE accelerator requires VMBus to be enabled"
338            );
339            vmbus_devices.extend(storvsp_ide_handles);
340        }
341
342        let (firmware_event_send, firmware_event_recv) = mesh::mpsc_channel();
343        let (ipmi_sel_event_send, ipmi_sel_event_recv) = mesh::mpsc_channel();
344
345        let make_vsock_listener = || -> anyhow::Result<(UnixListener, TempPath)> {
346            Ok(tempfile::Builder::new()
347                .make(|path| UnixListener::bind(path))?
348                .into_parts())
349        };
350
351        let (with_vtl2, vtl2_vmbus, ged, ged_send, vtl2_vsock_path) = if firmware.is_openhcl() {
352            let (ged, ged_send) = setup
353                .config_openhcl_vmbus_devices(
354                    &mut emulated_serial_config,
355                    &mut vmbus_devices,
356                    &firmware_event_send,
357                    &ipmi_sel_event_send,
358                    framebuffer.is_some(),
359                )
360                .await?;
361
362            let late_map_vtl0_memory = match load_mode {
363                LoadMode::Igvm {
364                    vtl2_base_address: Vtl2BaseAddressType::Vtl2Allocate { .. },
365                    ..
366                } => {
367                    // Late Map VTL0 memory not supported when test supplies Vtl2Allocate
368                    None
369                }
370                _ => Some(LateMapVtl0MemoryPolicy::InjectException),
371            };
372
373            let (vtl2_vsock_listener, vtl2_vsock_path) = make_vsock_listener()?;
374            (
375                Some(Vtl2Config {
376                    vtl0_alias_map: false, // TODO: enable when OpenVMM supports it for DMA
377                    late_map_vtl0_memory,
378                }),
379                Some(VmbusConfig {
380                    vsock_listener: Some(vtl2_vsock_listener),
381                    vsock_path: Some(vtl2_vsock_path.to_string_lossy().into_owned()),
382                    vmbus_max_version: None,
383                    vtl2_redirect: false,
384                    #[cfg(windows)]
385                    vmbusproxy_handle: None,
386                }),
387                Some(ged),
388                Some(ged_send),
389                Some(vtl2_vsock_path),
390            )
391        } else {
392            (None, None, None, None, None)
393        };
394
395        // Configure the serial ports now that they have been updated by the
396        // OpenHCL configuration.
397        if properties.enable_serial {
398            chipset = chipset.with_serial(emulated_serial_config);
399            // Set so that we don't pull serial data until the guest is
400            // ready. Otherwise, Linux will drop the input serial data
401            // on the floor during boot.
402            if matches!(firmware, Firmware::LinuxDirect { .. })
403                && prebuilt_initrd.is_none()
404                && !properties.external_pipette
405            {
406                chipset = chipset.with_serial_wait_for_rts();
407            }
408        }
409
410        // Extract video configuration
411        let vga_firmware = match video_dev {
412            Some(VideoDevice::Vga(firmware)) => Some(firmware),
413            Some(VideoDevice::Synth(vtl, resource)) => {
414                vmbus_devices.push((vtl, resource));
415                None
416            }
417            None => None,
418        };
419
420        // Add default VMBus devices (skipped in minimal mode and no-vmbus mode).
421        let (shutdown_ic_send, kvp_ic_send) = if !properties.minimal_mode && !properties.no_vmbus {
422            let (shutdown_ic_send, shutdown_ic_recv) = mesh::channel();
423            vmbus_devices.push((
424                DeviceVtl::Vtl0,
425                ShutdownIcHandle {
426                    recv: shutdown_ic_recv,
427                }
428                .into_resource(),
429            ));
430
431            let (kvp_ic_send, kvp_ic_recv) = mesh::channel();
432            vmbus_devices.push((
433                DeviceVtl::Vtl0,
434                hyperv_ic_resources::kvp::KvpIcHandle { recv: kvp_ic_recv }.into_resource(),
435            ));
436
437            vmbus_devices.push((
438                DeviceVtl::Vtl0,
439                hyperv_ic_resources::timesync::TimesyncIcHandle.into_resource(),
440            ));
441
442            (Some(shutdown_ic_send), Some(kvp_ic_send))
443        } else {
444            (None, None)
445        };
446
447        // Make a vmbus or virtio vsock path for pipette connections
448        let (vsock_listener, vsock_path) = make_vsock_listener()?;
449        let mut vsock_listener = Some(vsock_listener);
450        let vsock_path_string = vsock_path.to_string_lossy();
451
452        // Configure the UEFI helper device on the chipset for Firmware::Uefi.
453        // OpenhclUefi uses BaseChipsetType::HclHost, so it does not need this.
454        if matches!(firmware, Firmware::Uefi { .. }) {
455            use firmware_uefi_resources::aarch64_secure_boot_templates;
456            use firmware_uefi_resources::x64_secure_boot_templates;
457
458            let uefi_cfg = firmware.uefi_config();
459            let base_template =
460                uefi_cfg
461                    .and_then(|c| c.secure_boot_template)
462                    .map(|template| match (arch, template) {
463                        (MachineArch::X86_64, SecureBootTemplate::MicrosoftWindows) => {
464                            x64_secure_boot_templates::microsoft_windows()
465                        }
466                        (
467                            MachineArch::X86_64,
468                            SecureBootTemplate::MicrosoftUefiCertificateAuthority,
469                        ) => x64_secure_boot_templates::microsoft_uefi_ca(),
470                        (MachineArch::Aarch64, SecureBootTemplate::MicrosoftWindows) => {
471                            aarch64_secure_boot_templates::microsoft_windows()
472                        }
473                        (
474                            MachineArch::Aarch64,
475                            SecureBootTemplate::MicrosoftUefiCertificateAuthority,
476                        ) => aarch64_secure_boot_templates::microsoft_uefi_ca(),
477                    });
478            let custom_uefi_json = uefi_cfg
479                .and_then(|c| c.custom_uefi_json.clone())
480                .map(Into::into);
481            let secure_boot = uefi_cfg.is_some_and(|c| c.secure_boot_enabled);
482            let log_level = match uefi_cfg
483                .map(|c| c.efi_diagnostics_log_level)
484                .unwrap_or_default()
485            {
486                EfiDiagnosticsLogLevel::Default => {
487                    firmware_uefi_resources::LogLevel::make_default()
488                }
489                EfiDiagnosticsLogLevel::Info => firmware_uefi_resources::LogLevel::make_info(),
490                EfiDiagnosticsLogLevel::Full => firmware_uefi_resources::LogLevel::make_full(),
491            };
492            let diagnostics_rate_limit = uefi_cfg.and_then(|c| c.efi_diagnostics_rate_limit);
493            let nvram_storage = if vmgs.disk().is_some() {
494                VmgsFileHandle::new(vmgs_format::FileId::BIOS_NVRAM, true).into_resource()
495            } else {
496                EphemeralNonVolatileStoreHandle.into_resource()
497            };
498            chipset = chipset.with_uefi(vm_manifest_builder::UefiManifest::new(
499                match arch {
500                    MachineArch::X86_64 => vm_manifest_builder::MachineArch::X86_64,
501                    MachineArch::Aarch64 => vm_manifest_builder::MachineArch::Aarch64,
502                },
503                base_template,
504                custom_uefi_json,
505                secure_boot,
506                log_level,
507                diagnostics_rate_limit,
508                nvram_storage,
509                None,
510            ));
511        }
512
513        let acpi_power_button_send =
514            if !properties.minimal_mode && supports_acpi_power_button(&load_mode) {
515                let (send, recv) = mesh::channel();
516                let irq = match arch {
517                    MachineArch::X86_64 => DEFAULT_ACPI_POWER_BUTTON_IRQ_X64,
518                    MachineArch::Aarch64 => DEFAULT_ACPI_POWER_BUTTON_SPI_AARCH64,
519                };
520                chipset = chipset.with_acpi_power_button(irq, recv);
521                Some(send)
522            } else {
523                None
524            };
525
526        let layout_config = chipset.layout_config();
527        let chipset = chipset
528            .build()
529            .context("failed to build chipset configuration")?;
530
531        // Preserve the caller's explicit private-memory request so that backend
532        // methods which force shared memory can fail on an explicit conflict.
533        let requested_private_memory = memory.private_memory;
534
535        let numa = {
536            let MemoryConfig {
537                startup_bytes,
538                dynamic_memory_range,
539                numa_mem_sizes,
540                private_memory,
541                transparent_hugepages,
542            } = memory;
543
544            if dynamic_memory_range.is_some() {
545                anyhow::bail!("dynamic memory not supported in OpenVMM");
546            }
547
548            // Private (anonymous) guest memory is incompatible with two
549            // OpenVMM features that petri enables based on the firmware:
550            // - OpenHCL uses a remote VA mapper to share VTL0 RAM with VTL2,
551            //   which requires a shareable memory section.
552            // - PCAT (Gen1) relies on x86 legacy support (the VGA hole and
553            //   PAM registers), which toggles low RAM visibility in a way
554            //   that requires shared, file-backed memory.
555            let private_incompatible =
556                firmware.is_openhcl() || firmware.is_pcat() || vhost_vsock_guest_cid.is_some();
557            let private_memory = match private_memory {
558                // An explicit request for private memory that the firmware
559                // cannot honor is an error, rather than a silent downgrade.
560                Some(true) if private_incompatible => {
561                    anyhow::bail!(
562                        "private guest memory was explicitly requested but is \
563                         not supported with this configuration (OpenHCL, \
564                         PCAT/Gen1, and kernel vhost-vsock require shared memory)"
565                    );
566                }
567                Some(explicit) => explicit,
568                // Default: prefer private memory for performance, falling back
569                // to shared when the firmware requires it.
570                None => !private_incompatible,
571            };
572
573            // THP applies to both private anonymous and shared (file/memfd)
574            // guest RAM, and on both Linux (madvise-based) and Windows
575            // (soft large pages). The membacking layer suppresses it where it
576            // does not apply (e.g. explicit hugetlb backings), so pass the
577            // requested value through unchanged.
578            let make_mem = |size: u64| openvmm_defs::config::MemoryConfig {
579                mem_size: size,
580                prefetch_memory: false,
581                private_memory,
582                transparent_hugepages,
583                hugepages: false,
584                hugepage_size: None,
585                host_numa_node: None,
586            };
587
588            if let Some(sizes) = numa_mem_sizes {
589                NumaTopology {
590                    nodes: sizes
591                        .into_iter()
592                        .map(|size| NumaNode {
593                            mem: if size > 0 { Some(make_mem(size)) } else { None },
594                            vps: VpAssignment::FromTopology,
595                        })
596                        .collect(),
597                    distances: vec![],
598                }
599            } else {
600                NumaTopology {
601                    nodes: vec![NumaNode {
602                        mem: Some(make_mem(startup_bytes)),
603                        vps: VpAssignment::FromTopology,
604                    }],
605                    distances: vec![],
606                }
607            }
608        };
609
610        let processor_topology = {
611            let ProcessorTopology {
612                vp_count,
613                enable_smt,
614                vps_per_socket,
615                apic_mode,
616            } = proc_topology;
617
618            ProcessorTopologyConfig {
619                proc_count: vp_count,
620                vps_per_socket,
621                enable_smt,
622                arch: Some(match arch {
623                    MachineArch::X86_64 => openvmm_defs::config::ArchTopologyConfig::X86(
624                        openvmm_defs::config::X86TopologyConfig {
625                            x2apic: match apic_mode {
626                                None => openvmm_defs::config::X2ApicConfig::Auto,
627                                Some(x) => match x {
628                                    crate::ApicMode::Xapic => {
629                                        openvmm_defs::config::X2ApicConfig::Unsupported
630                                    }
631                                    crate::ApicMode::X2apicSupported => {
632                                        openvmm_defs::config::X2ApicConfig::Supported
633                                    }
634                                    crate::ApicMode::X2apicEnabled => {
635                                        openvmm_defs::config::X2ApicConfig::Enabled
636                                    }
637                                },
638                            },
639                            ..Default::default()
640                        },
641                    ),
642                    MachineArch::Aarch64 => openvmm_defs::config::ArchTopologyConfig::Aarch64(
643                        openvmm_defs::config::Aarch64TopologyConfig::default(),
644                    ),
645                }),
646            }
647        };
648
649        let vmgs = if firmware.is_openhcl() {
650            None
651        } else {
652            Some(memdiff_vmgs(&vmgs).await?)
653        };
654
655        let VmChipsetResult {
656            chipset,
657            mut chipset_devices,
658            pci_chipset_devices,
659            isa_dma_controller,
660            capabilities,
661        } = chipset;
662
663        // Add the TPM
664        if let Some(tpm) = setup.config_tpm().await? {
665            chipset_devices.push(tpm);
666        }
667
668        // Assign private ports after backend modifiers have chosen the topology.
669        if properties.use_virtio_vsock {
670            let resource: Resource<VirtioDeviceHandle> = match vhost_vsock_guest_cid {
671                #[cfg(target_os = "linux")]
672                Some(guest_cid) => {
673                    let vhost = std::fs::OpenOptions::new()
674                        .read(true)
675                        .write(true)
676                        .open("/dev/vhost-vsock")
677                        .context("failed to open /dev/vhost-vsock")?
678                        .into();
679                    // The kernel backend does not use the Unix relay. Clear it
680                    // so VmbusConfig below does not receive the listener.
681                    vsock_listener = None;
682                    VirtioVsockVhostHandle { vhost, guest_cid }.into_resource()
683                }
684                #[cfg(not(target_os = "linux"))]
685                Some(_) => unreachable!("kernel vhost-vsock is Linux-only"),
686                None => VirtioVsockHandle {
687                    guest_cid: 0x3,
688                    base_path: vsock_path_string.to_string(),
689                    listener: vsock_listener.take().unwrap(),
690                }
691                .into_resource(),
692            };
693            private_virtio_devices.push(("petri-vsock-", resource));
694        }
695
696        let config = Config {
697            // Firmware
698            load_mode,
699            firmware_event_send: Some(firmware_event_send),
700
701            // CPU and RAM
702            numa,
703            disable_guest_memory_locking: false,
704            processor_topology,
705
706            // Base chipset
707            chipset,
708            chipset_devices,
709            pci_chipset_devices,
710            isa_dma_controller,
711            chipset_capabilities: capabilities,
712            layout: layout_config,
713
714            // Basic virtualization device support
715            hypervisor: HypervisorConfig {
716                with_hv: !properties.no_hv,
717                with_vtl2,
718                with_isolation: match firmware.isolation() {
719                    Some(IsolationType::Vbs) => Some(openvmm_defs::config::IsolationType::Vbs),
720                    Some(IsolationType::Snp) => {
721                        Some(openvmm_defs::config::IsolationType::Snp { host_data: None })
722                    }
723                    None => None,
724                    _ => anyhow::bail!("unsupported isolation type"),
725                },
726                nested_virt: nested_virt_enabled,
727            },
728            vmbus: if properties.no_vmbus {
729                None
730            } else {
731                Some(VmbusConfig {
732                    // If virtio vsock is enabled, the vsock_listener will have already been taken
733                    // and is now None.
734                    vsock_listener,
735                    vsock_path: (!properties.use_virtio_vsock)
736                        .then(|| vsock_path_string.to_string()),
737                    vmbus_max_version: None,
738                    vtl2_redirect: firmware.openhcl_config().is_some_and(|c| c.vmbus_redirect),
739                    #[cfg(windows)]
740                    vmbusproxy_handle: None,
741                })
742            },
743            vtl2_vmbus,
744
745            // Devices
746            floppy_disks: vec![],
747            ide_disks,
748            pcie_root_complexes: vec![],
749            pcie_ecam_below_4gb: false,
750            pcie_devices,
751            pcie_switches: vec![],
752            pcie_generic_initiators: vec![],
753            vpci_devices,
754            vmbus_devices,
755
756            // Video support
757            framebuffer,
758            vga_firmware,
759
760            vmgs,
761
762            // Disabled for VMM tests by default
763            #[cfg(windows)]
764            kernel_vmnics: vec![],
765            input: mesh::Receiver::new(),
766            vtl2_gfx: false,
767            virtio_devices: vec![],
768            #[cfg(windows)]
769            vpci_resources: vec![],
770            debugger_rpc: None,
771            rtc_delta_milliseconds: 0,
772        };
773
774        // Make the pipette connection listener.
775        let path = format!("{vsock_path_string}_{PIPETTE_PORT}");
776        let pipette_listener = PolledSocket::new(
777            driver,
778            UnixListener::bind(path).context("failed to bind to pipette listener")?,
779        )?;
780
781        // Make the vtl2 pipette connection listener.
782        let vtl2_pipette_listener = if let Some(vtl2_vmbus) = &config.vtl2_vmbus {
783            let path = vtl2_vmbus.vsock_path.as_ref().unwrap();
784            let path = format!("{path}_{PIPETTE_PORT}");
785            Some(PolledSocket::new(
786                driver,
787                UnixListener::bind(path).context("failed to bind to vtl2 pipette listener")?,
788            )?)
789        } else {
790            None
791        };
792
793        Ok(Self {
794            guest_shares,
795            private_virtio_devices,
796            runtime_config: firmware.into_runtime_config(vmbus_storage_controllers),
797            arch,
798            host_log_levels,
799            config,
800            skip_save_restore: false,
801            mesh,
802
803            resources: PetriVmResourcesOpenVmm {
804                log_stream_tasks,
805                firmware_event_recv,
806                ipmi_sel_event_recv,
807                shutdown_ic_send,
808                acpi_power_button_send,
809                kvp_ic_send,
810                ged_send,
811                pipette_listener,
812                vtl2_pipette_listener,
813                linux_direct_serial_agent,
814                tcp_pipette_port: None,
815                driver: driver.clone(),
816                output_dir: log_source.output_dir().to_owned(),
817                openvmm_path: openvmm_path.clone(),
818                vtl2_vsock_path,
819                _vsock_path: vsock_path,
820                properties: properties.clone(),
821                #[cfg(windows)]
822                _switch_ports: Vec::new(),
823            },
824
825            openvmm_log_file: log_source.log_file("openvmm")?,
826
827            memory_backing_file: None,
828            requested_private_memory,
829
830            ged,
831            framebuffer_view,
832
833            pending_iommu: Vec::new(),
834        })
835    }
836}
837
838struct PetriVmConfigSetupCore<'a> {
839    arch: MachineArch,
840    firmware: &'a Firmware,
841    hibernation_enabled: bool,
842    ipmi_enabled: bool,
843    driver: &'a DefaultDriver,
844    logger: &'a PetriLogSource,
845    vmgs: &'a PetriVmgsResource,
846    tpm_config: Option<&'a TpmConfig>,
847    mesh: &'a Mesh,
848    openvmm_path: &'a ResolvedArtifact,
849    pipette_rdinit_param: Option<String>,
850    external_pipette: bool,
851    enable_serial: bool,
852    use_virtio_console: bool,
853    use_virtio_vsock: bool,
854    no_vmbus: bool,
855    no_hv: bool,
856}
857
858struct SerialData {
859    emulated_serial_config: [Option<Resource<SerialBackendHandle>>; 4],
860    serial_tasks: Vec<Task<anyhow::Result<()>>>,
861    linux_direct_serial_agent: Option<LinuxDirectSerialAgent>,
862}
863
864enum VideoDevice {
865    Vga(RomFileLocation),
866    Synth(DeviceVtl, Resource<VmbusDeviceHandleKind>),
867}
868
869impl PetriVmConfigSetupCore<'_> {
870    fn configure_serial(&self, logger: &PetriLogSource) -> anyhow::Result<SerialData> {
871        let mut serial_tasks = Vec::new();
872
873        let serial0_log_file = logger.log_file(match self.firmware {
874            Firmware::LinuxDirect { .. }
875            | Firmware::IgvmLinuxDirect { .. }
876            | Firmware::OpenhclLinuxDirect { .. } => "linux",
877            Firmware::Pcat { .. } | Firmware::OpenhclPcat { .. } => "pcat",
878            Firmware::Uefi { .. } | Firmware::OpenhclUefi { .. } => "uefi",
879        })?;
880
881        let (serial0_host, serial0) = self
882            .create_serial_stream()
883            .context("failed to create serial0 stream")?;
884        let (serial0_read, serial0_write) = serial0_host.split();
885        let serial0_task = self.driver.spawn(
886            "serial0-console",
887            crate::log_task(serial0_log_file, serial0_read, "serial0-console"),
888        );
889        serial_tasks.push(serial0_task);
890
891        let serial2 = if self.firmware.is_openhcl() {
892            let (serial2_host, serial2) = self
893                .create_serial_stream()
894                .context("failed to create serial2 stream")?;
895            let serial2_task = self.driver.spawn(
896                "serial2-openhcl",
897                crate::log_task(logger.log_file("openhcl")?, serial2_host, "serial2-openhcl"),
898            );
899            serial_tasks.push(serial2_task);
900            Some(serial2)
901        } else {
902            None
903        };
904
905        if self.firmware.is_linux_direct()
906            && !self.firmware.is_isolated_without_paravisor()
907            && !self.external_pipette
908            && !self.use_virtio_console
909            && self.pipette_rdinit_param.is_none()
910        {
911            // Non-pipette-as-init Linux direct: create serial1 and a serial
912            // agent so we can send shell commands to launch pipette.
913            let (serial1_host, serial1) = self.create_serial_stream()?;
914            let (serial1_read, _serial1_write) = serial1_host.split();
915            let linux_direct_serial_agent =
916                LinuxDirectSerialAgent::new(serial1_read, serial0_write);
917            Ok(SerialData {
918                emulated_serial_config: [Some(serial0), Some(serial1), serial2, None],
919                serial_tasks,
920                linux_direct_serial_agent: Some(linux_direct_serial_agent),
921            })
922        } else {
923            Ok(SerialData {
924                emulated_serial_config: [Some(serial0), None, serial2, None],
925                serial_tasks,
926                linux_direct_serial_agent: None,
927            })
928        }
929    }
930
931    fn create_serial_stream(
932        &self,
933    ) -> anyhow::Result<(PolledSocket<UnixStream>, Resource<SerialBackendHandle>)> {
934        let (host_side, guest_side) = UnixStream::pair()?;
935        let host_side = PolledSocket::new(self.driver, host_side)?;
936        let serial = OpenSocketSerialConfig::from(guest_side).into_resource();
937        Ok((host_side, serial))
938    }
939
940    fn load_firmware(&self) -> anyhow::Result<LoadMode> {
941        // The test kernel has both CONFIG_VIRTIO_VSOCK=y and
942        // CONFIG_HYPERV_VSOCKETS=y built in. The kernel only allows one G2H
943        // vsock transport, and virtio_vsock_init runs first, claiming the
944        // slot. This causes hv_sock registration to fail with -EBUSY,
945        // breaking pipette's AF_VSOCK connection. Blacklist either
946        // virtio_vsock_init or hv_sock_init depending on which vsock transport
947        // is being used.
948        let vsock_blacklist = crate::vm::linux_vsock_blacklist(self.use_virtio_vsock);
949
950        Ok(match (self.arch, &self.firmware) {
951            (MachineArch::X86_64, Firmware::IgvmLinuxDirect { igvm_path, .. }) => LoadMode::Igvm {
952                file: File::open(igvm_path.clone())
953                    .context("failed to open Linux-direct IGVM")?
954                    .into(),
955                cmdline: String::new(),
956                vtl2_base_address: Vtl2BaseAddressType::File,
957                com_serial: None,
958                personality: IgvmPersonality::LinuxDirect,
959            },
960            (arch, Firmware::LinuxDirect { kernel, initrd }) => {
961                let console = match (self.use_virtio_console, arch) {
962                    (true, _) => "console=hvc0",
963                    (false, MachineArch::X86_64) => "console=ttyS0",
964                    (false, MachineArch::Aarch64) => "console=ttyAMA0 earlycon",
965                };
966                let kernel = File::open(kernel.clone())
967                    .context("Failed to open kernel")?
968                    .into();
969                let initrd = File::open(initrd.clone())
970                    .context("Failed to open initrd")?
971                    .into();
972
973                let rdinit = match self.pipette_rdinit_param.as_deref() {
974                    Some(path) => format!(" rdinit={path}"),
975                    None if self.external_pipette => String::new(),
976                    None => " rdinit=/bin/sh".into(),
977                };
978
979                let serial_args = if self.enable_serial || self.use_virtio_console {
980                    format!("{console} debug ")
981                } else {
982                    String::new()
983                };
984
985                let cmdline = format!("{serial_args}panic=-1{rdinit} {vsock_blacklist}");
986
987                LoadMode::Linux {
988                    kernel,
989                    initrd: Some(initrd),
990                    cmdline,
991                    enable_serial: self.enable_serial,
992                    isolation: openvmm_defs::config::LinuxIsolationConfig::None,
993                    boot_mode: openvmm_defs::config::LinuxDirectBootMode::Acpi,
994                    smbios: Default::default(),
995                }
996            }
997            (
998                MachineArch::X86_64,
999                Firmware::Pcat {
1000                    bios_firmware: firmware,
1001                    guest: _,         // load_boot_disk
1002                    svga_firmware: _, // config_video
1003                    ide_controllers: _,
1004                },
1005            ) => {
1006                let firmware = openvmm_pcat_locator::find_pcat_bios(firmware.get())
1007                    .context("Failed to load packaged PCAT binary")?;
1008                LoadMode::Pcat {
1009                    firmware,
1010                    boot_order: DEFAULT_PCAT_BOOT_ORDER,
1011                    hibernation_enabled: self.hibernation_enabled,
1012                    smbios: Box::new(openvmm_defs::config::SmbiosConfig::default()),
1013                }
1014            }
1015            (
1016                _,
1017                Firmware::Uefi {
1018                    uefi_firmware: firmware,
1019                    guest: _, // load_boot_disk
1020                    uefi_config:
1021                        UefiConfig {
1022                            secure_boot_enabled: _,  // new
1023                            secure_boot_template: _, // new
1024                            custom_uefi_json: _,     // applied device-side via UefiManifest::new
1025                            disable_frontpage,
1026                            default_boot_always_attempt,
1027                            enable_vpci_boot,
1028                            force_dma_bounce,
1029                            efi_diagnostics_log_level: _, // applied device-side via UefiManifest::new
1030                            efi_diagnostics_rate_limit: _, // applied device-side via UefiManifest::new
1031                        },
1032                },
1033            ) => {
1034                anyhow::ensure!(
1035                    !(self.no_hv && self.arch == MachineArch::X86_64),
1036                    "x86_64 UEFI firmware requires Hyper-V enlightenments"
1037                );
1038                let firmware = File::open(firmware.clone())
1039                    .context("Failed to open uefi firmware file")?
1040                    .into();
1041                LoadMode::Uefi {
1042                    firmware,
1043                    enable_debugging: false,
1044                    enable_memory_protections: false,
1045                    disable_frontpage: *disable_frontpage,
1046                    tpm_version: self.tpm_config.map(|c| c.version.into()),
1047                    enable_battery: false,
1048                    enable_serial: true,
1049                    enable_vpci_boot: *enable_vpci_boot,
1050                    uefi_console_mode: Some(openvmm_defs::config::UefiConsoleMode::Com1),
1051                    default_boot_always_attempt: *default_boot_always_attempt,
1052                    smbios: Box::new(openvmm_defs::config::SmbiosConfig {
1053                        system: openvmm_defs::config::SmbiosSystemOverrides {
1054                            uuid: Guid::new_random(),
1055                            ..Default::default()
1056                        },
1057                        ..Default::default()
1058                    }),
1059                    enable_vmbus: !self.no_vmbus,
1060                    force_dma_bounce: *force_dma_bounce,
1061                    enable_hv: !self.no_hv,
1062                    hibernation_enabled: self.hibernation_enabled,
1063                    force_firmware_version: false,
1064                }
1065            }
1066            (
1067                MachineArch::X86_64,
1068                Firmware::OpenhclLinuxDirect {
1069                    igvm_firmware: IgvmFirmwareSource::File(igvm_path),
1070                    openhcl_config,
1071                }
1072                | Firmware::OpenhclUefi {
1073                    igvm_firmware: IgvmFirmwareSource::File(igvm_path),
1074                    guest: _,       // load_boot_disk
1075                    isolation: _,   // new via Firmware::isolation
1076                    uefi_config: _, // config_openhcl_vmbus_devices
1077                    openhcl_config,
1078                },
1079            ) => {
1080                let OpenHclConfig {
1081                    vmbus_redirect: _, // config_openhcl_vmbus_devices
1082                    enable_mana_keepalive: _,
1083                    custom_command_line: _,
1084                    log_levels: _,
1085                    vtl2_base_address_type,
1086                    vtl2_settings: _, // run_core
1087                } = openhcl_config;
1088
1089                let mut cmdline = Some(openhcl_config.command_line());
1090
1091                append_cmdline(&mut cmdline, "panic=-1 reboot=triple");
1092
1093                if matches!(self.firmware, Firmware::OpenhclLinuxDirect { .. }) {
1094                    // Set UNDERHILL_SERIAL_WAIT_FOR_RTS=1 so that we don't pull serial data
1095                    // until the guest is ready. Otherwise, Linux will drop the input serial
1096                    // data on the floor during boot.
1097                    append_cmdline(
1098                        &mut cmdline,
1099                        format!(
1100                            "UNDERHILL_SERIAL_WAIT_FOR_RTS=1 UNDERHILL_CMDLINE_APPEND=\"rdinit=/bin/sh {vsock_blacklist}\""
1101                        ),
1102                    );
1103                }
1104
1105                let isolation = self.firmware.isolation();
1106
1107                // For certain configurations, we need to override the override
1108                // in new_underhill_vm.
1109                //
1110                // TODO: remove this (and OpenHCL override) once host changes
1111                // are saturated.
1112                if let Firmware::OpenhclUefi {
1113                    uefi_config:
1114                        UefiConfig {
1115                            default_boot_always_attempt,
1116                            secure_boot_enabled,
1117                            ..
1118                        },
1119                    ..
1120                } = self.firmware
1121                {
1122                    if isolation.is_none()
1123                        && !secure_boot_enabled
1124                        && self.tpm_config.is_none()
1125                        && !default_boot_always_attempt
1126                    {
1127                        append_cmdline(&mut cmdline, "HCL_DEFAULT_BOOT_ALWAYS_ATTEMPT=0");
1128                    }
1129                }
1130
1131                // Plumb the EFI diagnostics rate-limit override to the
1132                // OpenHCL-side UEFI device via env var.
1133                if let Firmware::OpenhclUefi {
1134                    uefi_config:
1135                        UefiConfig {
1136                            efi_diagnostics_rate_limit: Some(limit),
1137                            ..
1138                        },
1139                    ..
1140                } = self.firmware
1141                {
1142                    append_cmdline(
1143                        &mut cmdline,
1144                        format!("HCL_EFI_DIAGNOSTICS_RATE_LIMIT={limit}"),
1145                    );
1146                }
1147
1148                let vtl2_base_address = vtl2_base_address_type.unwrap_or_else(|| {
1149                    match isolation {
1150                        // bump up the memory on release builds for VBS VMs
1151                        // (uses petri build flavor as proxy for igvm file)
1152                        #[cfg(not(debug_assertions))]
1153                        Some(IsolationType::Vbs) => Vtl2BaseAddressType::Vtl2Allocate {
1154                            size: Some(128 * 1024 * 1024),
1155                        },
1156                        // Isolated VMs must load at the location specified by
1157                        // the file, as they do not support relocation.
1158                        Some(_) => Vtl2BaseAddressType::File,
1159                        // By default, utilize IGVM relocation and tell OpenVMM
1160                        // to place VTL2 at 512MB. This tests both relocation
1161                        // support in OpenVMM, and relocation support within
1162                        // OpenHCL.
1163                        None => Vtl2BaseAddressType::Absolute(512 * SIZE_1_MB),
1164                    }
1165                });
1166
1167                let file = File::open(igvm_path.get())
1168                    .context("failed to open openhcl firmware file")?
1169                    .into();
1170                LoadMode::Igvm {
1171                    file,
1172                    cmdline: cmdline.unwrap_or_default(),
1173                    vtl2_base_address,
1174                    com_serial: self.enable_serial.then_some(UartId::Com(ComPort::Com3)),
1175                    personality: IgvmPersonality::Openhcl,
1176                }
1177            }
1178            (a, f) => anyhow::bail!("Unsupported firmware {f:?} for arch {a:?}"),
1179        })
1180    }
1181
1182    async fn config_openhcl_vmbus_devices(
1183        &self,
1184        serial: &mut [Option<Resource<SerialBackendHandle>>],
1185        devices: &mut impl Extend<(DeviceVtl, Resource<VmbusDeviceHandleKind>)>,
1186        firmware_event_send: &mesh::Sender<FirmwareEvent>,
1187        ipmi_sel_event_send: &mesh::Sender<get_resources::ged::IpmiSelEvent>,
1188        framebuffer: bool,
1189    ) -> anyhow::Result<(
1190        get_resources::ged::GuestEmulationDeviceHandle,
1191        mesh::Sender<get_resources::ged::GuestEmulationRequest>,
1192    )> {
1193        let serial0 = serial[0].take();
1194        devices.extend([(
1195            DeviceVtl::Vtl2,
1196            VmbusSerialDeviceHandle {
1197                port: VmbusSerialPort::Com1,
1198                backend: serial0.unwrap_or_else(|| DisconnectedSerialBackendHandle.into_resource()),
1199            }
1200            .into_resource(),
1201        )]);
1202        let serial1 = serial[1].take();
1203        devices.extend([(
1204            DeviceVtl::Vtl2,
1205            VmbusSerialDeviceHandle {
1206                port: VmbusSerialPort::Com2,
1207                backend: serial1.unwrap_or_else(|| DisconnectedSerialBackendHandle.into_resource()),
1208            }
1209            .into_resource(),
1210        )]);
1211
1212        let crash = spawn_dump_handler(self.driver, self.logger).into_resource();
1213        devices.extend([(DeviceVtl::Vtl2, crash)]);
1214
1215        let (guest_request_send, guest_request_recv) = mesh::channel();
1216
1217        let (
1218            UefiConfig {
1219                secure_boot_enabled,
1220                secure_boot_template,
1221                custom_uefi_json: _, // OpenHCL reads this from VMGS CUSTOM_UEFI.
1222                disable_frontpage,
1223                default_boot_always_attempt,
1224                enable_vpci_boot,
1225                force_dma_bounce,
1226                efi_diagnostics_log_level,
1227                efi_diagnostics_rate_limit: _, // applied device-side via UefiManifest::new
1228            },
1229            OpenHclConfig { vmbus_redirect, .. },
1230        ) = match self.firmware {
1231            Firmware::OpenhclUefi {
1232                uefi_config,
1233                openhcl_config,
1234                ..
1235            } => (uefi_config, openhcl_config),
1236            Firmware::OpenhclLinuxDirect { openhcl_config, .. } => {
1237                (&UefiConfig::default(), openhcl_config)
1238            }
1239            _ => anyhow::bail!("not a supported openhcl firmware config"),
1240        };
1241
1242        let test_gsp_by_id = matches!(
1243            self.vmgs.encryption_policy(),
1244            Some(GuestStateEncryptionPolicy::GspById(_))
1245        );
1246
1247        // Save the GED handle to add later after configuration is complete.
1248        let ged = get_resources::ged::GuestEmulationDeviceHandle {
1249            firmware: get_resources::ged::GuestFirmwareConfig::Uefi {
1250                firmware_debug: false,
1251                enable_memory_protections: false,
1252                disable_frontpage: *disable_frontpage,
1253                enable_vpci_boot: *enable_vpci_boot,
1254                console_mode: get_resources::ged::UefiConsoleMode::COM1,
1255                default_boot_always_attempt: *default_boot_always_attempt,
1256            },
1257            com1: true,
1258            com2: true,
1259            serial_tx_only: false,
1260            vmbus_redirection: *vmbus_redirect,
1261            vtl2_settings: None, // Will be added at startup to allow tests to modify
1262            vmgs: memdiff_vmgs(self.vmgs).await?,
1263            framebuffer: framebuffer.then(|| SharedFramebufferHandle.into_resource()),
1264            guest_request_recv,
1265            tpm_version: self.tpm_config.map(|c| c.version.into() ),
1266            firmware_event_send: Some(firmware_event_send.clone()),
1267            ipmi_sel_event_send: Some(ipmi_sel_event_send.clone()),
1268            secure_boot_enabled: *secure_boot_enabled,
1269            secure_boot_template: match secure_boot_template {
1270                Some(SecureBootTemplate::MicrosoftWindows) => {
1271                    get_resources::ged::GuestSecureBootTemplateType::MicrosoftWindows
1272                }
1273                Some(SecureBootTemplate::MicrosoftUefiCertificateAuthority) => {
1274                    get_resources::ged::GuestSecureBootTemplateType::MicrosoftUefiCertificateAuthority
1275                }
1276                None => get_resources::ged::GuestSecureBootTemplateType::None,
1277            },
1278            enable_battery: false,
1279            enable_hibernation: self.hibernation_enabled,
1280            enable_ipmi: self.ipmi_enabled,
1281            no_persistent_secrets: self.tpm_config.as_ref().is_some_and(|c| c.no_persistent_secrets),
1282            igvm_attest_test_config: None,
1283            test_gsp_by_id,
1284            efi_diagnostics_log_level: match efi_diagnostics_log_level {
1285                EfiDiagnosticsLogLevel::Default => {
1286                    get_resources::ged::EfiDiagnosticsLogLevelType::Default
1287                }
1288                EfiDiagnosticsLogLevel::Info => {
1289                    get_resources::ged::EfiDiagnosticsLogLevelType::Info
1290                }
1291                EfiDiagnosticsLogLevel::Full => {
1292                    get_resources::ged::EfiDiagnosticsLogLevelType::Full
1293                }
1294            },
1295            force_dma_bounce_enabled: *force_dma_bounce,
1296            smbios: Default::default(),
1297        };
1298
1299        Ok((ged, guest_request_send))
1300    }
1301
1302    fn config_video(
1303        &self,
1304    ) -> anyhow::Result<Option<(VideoDevice, Framebuffer, FramebufferAccess)>> {
1305        if self.firmware.isolation().is_some() {
1306            return Ok(None);
1307        }
1308
1309        let video_dev = match self.firmware {
1310            Firmware::Pcat { svga_firmware, .. } | Firmware::OpenhclPcat { svga_firmware, .. } => {
1311                Some(VideoDevice::Vga(
1312                    openvmm_pcat_locator::find_svga_bios(svga_firmware.get())
1313                        .context("Failed to load VGA BIOS")?,
1314                ))
1315            }
1316            Firmware::Uefi { .. } | Firmware::OpenhclUefi { .. } if !self.no_vmbus => {
1317                Some(VideoDevice::Synth(
1318                    DeviceVtl::Vtl0,
1319                    SynthVideoHandle {
1320                        framebuffer: SharedFramebufferHandle.into_resource(),
1321                        dirt_send: None,
1322                    }
1323                    .into_resource(),
1324                ))
1325            }
1326            Firmware::OpenhclLinuxDirect { .. }
1327            | Firmware::IgvmLinuxDirect { .. }
1328            | Firmware::LinuxDirect { .. }
1329            | Firmware::Uefi { .. }
1330            | Firmware::OpenhclUefi { .. } => None,
1331        };
1332
1333        Ok(if let Some(vdev) = video_dev {
1334            let vram =
1335                alloc_shared_memory(FRAMEBUFFER_SIZE, "vram").context("allocating framebuffer")?;
1336            let (fb, fba) = framebuffer::framebuffer(vram, FRAMEBUFFER_SIZE, 0)
1337                .context("creating framebuffer")?;
1338            Some((vdev, fb, fba))
1339        } else {
1340            None
1341        })
1342    }
1343
1344    async fn config_tpm(&self) -> anyhow::Result<Option<ChipsetDeviceHandle>> {
1345        if !self.firmware.is_openhcl()
1346            && let Some(&TpmConfig {
1347                no_persistent_secrets,
1348                version,
1349                ..
1350            }) = self.tpm_config
1351        {
1352            let register_layout = match self.arch {
1353                MachineArch::X86_64 => TpmRegisterLayout::IoPort,
1354                MachineArch::Aarch64 => TpmRegisterLayout::Mmio,
1355            };
1356
1357            let tpm_version = version.into();
1358
1359            let (ppi_store, nvram_store) = if self.vmgs.disk().is_none() || no_persistent_secrets {
1360                (
1361                    EphemeralNonVolatileStoreHandle.into_resource(),
1362                    EphemeralNonVolatileStoreHandle.into_resource(),
1363                )
1364            } else {
1365                (
1366                    VmgsFileHandle::new(vmgs_format::FileId::TPM_PPI, true).into_resource(),
1367                    VmgsFileHandle::new(tpm_nvram_file_id(tpm_version), true).into_resource(),
1368                )
1369            };
1370
1371            Ok(Some(ChipsetDeviceHandle {
1372                name: "tpm".to_string(),
1373                resource: chipset_device_worker_defs::RemoteChipsetDeviceHandle {
1374                    device: TpmDeviceHandle {
1375                        version: tpm_version,
1376                        ppi_store,
1377                        nvram_store,
1378                        refresh_tpm_seeds: false,
1379                        ak_cert_type: tpm_resources::TpmAkCertTypeResource::None,
1380                        register_layout,
1381                        guest_secret_key: None,
1382                        logger: None,
1383                        is_confidential_vm: self.firmware.isolation().is_some(),
1384                        // TODO: generate an actual BIOS GUID and put it here
1385                        bios_guid: Guid::ZERO,
1386                        nvram_size: None,
1387                    }
1388                    .into_resource(),
1389                    worker_host: self.make_device_worker("tpm").await?,
1390                }
1391                .into_resource(),
1392            }))
1393        } else {
1394            Ok(None)
1395        }
1396    }
1397
1398    async fn make_device_worker(&self, name: &str) -> anyhow::Result<mesh_worker::WorkerHost> {
1399        let (host, runner) = mesh_worker::worker_host();
1400        self.mesh
1401            .launch_host(
1402                mesh_process::ProcessConfig::new(name).process_name(self.openvmm_path),
1403                openvmm_defs::entrypoint::MeshHostParams { runner },
1404            )
1405            .await?;
1406        Ok(host)
1407    }
1408}
1409
1410fn spawn_dump_handler(driver: &DefaultDriver, logger: &PetriLogSource) -> GuestCrashDeviceHandle {
1411    let (send, mut recv) = mesh::channel();
1412    let handle = GuestCrashDeviceHandle {
1413        request_dump: send,
1414        max_dump_size: 256 * 1024 * 1024,
1415    };
1416    driver
1417        .spawn("openhcl-dump-handler", {
1418            let logger = logger.clone();
1419            let driver = driver.clone();
1420            async move {
1421                while let Some(rpc) = recv.next().await {
1422                    rpc.handle_failable_sync(|done| {
1423                        let (file, path) = logger.create_attachment("openhcl.core")?.into_parts();
1424                        driver
1425                            .spawn("crash-waiter", async move {
1426                                let filename = path.file_name().unwrap().to_str().unwrap();
1427                                if done.await.is_ok() {
1428                                    tracing::warn!(filename, "openhcl crash dump complete");
1429                                } else {
1430                                    tracing::error!(
1431                                        filename,
1432                                        "openhcl crash dump incomplete, may be corrupted"
1433                                    );
1434                                }
1435                            })
1436                            .detach();
1437                        anyhow::Ok(file)
1438                    })
1439                }
1440            }
1441        })
1442        .detach();
1443    handle
1444}
1445
1446/// Convert the generic IDE configuration to OpenVMM IDE disks and storvsp
1447/// IDE accelerator handles.
1448async fn ide_controllers_to_openvmm(
1449    ide_controllers: Option<&[[Option<Drive>; 2]; 2]>,
1450) -> anyhow::Result<(
1451    Vec<IdeDeviceConfig>,
1452    Vec<(DeviceVtl, Resource<VmbusDeviceHandleKind>)>,
1453)> {
1454    let mut ide_disks = Vec::new();
1455    let mut storvsp_ide_handles = Vec::new();
1456
1457    if let Some(ide_controllers) = ide_controllers {
1458        for (controller_number, controller) in ide_controllers.iter().enumerate() {
1459            for (controller_location, drive) in controller.iter().enumerate() {
1460                if let Some(drive) = drive {
1461                    if let Some(disk) = &drive.disk {
1462                        // Create storvsp accelerator resource before consuming
1463                        // the disk reference, since petri_disk_to_openvmm
1464                        // shadows the binding.
1465                        let storvsp_disk = if !drive.is_dvd {
1466                            Some(petri_disk_to_openvmm(disk).await?)
1467                        } else {
1468                            None
1469                        };
1470
1471                        let disk = petri_disk_to_openvmm(disk).await?;
1472                        let guest_media = if drive.is_dvd {
1473                            GuestMedia::Dvd(
1474                                SimpleScsiDvdHandle {
1475                                    media: Some(disk),
1476                                    requests: None,
1477                                }
1478                                .into_resource(),
1479                            )
1480                        } else {
1481                            GuestMedia::Disk {
1482                                disk_type: disk,
1483                                read_only: false,
1484                            }
1485                        };
1486
1487                        let channel = controller_number as u8;
1488                        let device = controller_location as u8;
1489
1490                        ide_disks.push(IdeDeviceConfig {
1491                            path: ide_resources::IdePath {
1492                                channel,
1493                                drive: device,
1494                            },
1495                            guest_media,
1496                        });
1497
1498                        // Hard disks also get a storvsp IDE accelerator channel.
1499                        if let Some(storvsp_disk) = storvsp_disk {
1500                            storvsp_ide_handles.push((
1501                                DeviceVtl::Vtl0,
1502                                storvsp_resources::StorvspIdeDeviceHandle {
1503                                    channel_id: channel,
1504                                    device_id: device,
1505                                    disk: SimpleScsiDiskHandle {
1506                                        disk: storvsp_disk,
1507                                        read_only: false,
1508                                        parameters: Default::default(),
1509                                    }
1510                                    .into_resource(),
1511                                    io_queue_depth: None,
1512                                }
1513                                .into_resource(),
1514                            ));
1515                        }
1516                    }
1517                }
1518            }
1519        }
1520    }
1521
1522    Ok((ide_disks, storvsp_ide_handles))
1523}
1524
1525/// Convert the generic VMBUS storage configuration to OpenVMM VMBUS and VPCI devices.
1526async fn vmbus_storage_controllers_to_openvmm(
1527    vmbus_storage_controllers: &HashMap<Guid, VmbusStorageController>,
1528) -> anyhow::Result<(
1529    Vec<(DeviceVtl, Resource<VmbusDeviceHandleKind>)>,
1530    Vec<VpciDeviceConfig>,
1531)> {
1532    let mut vmbus_devices = Vec::new();
1533    let mut vpci_devices = Vec::new();
1534
1535    // Add VMBus storage
1536    for (instance_id, controller) in vmbus_storage_controllers {
1537        let vtl = match controller.target_vtl {
1538            crate::Vtl::Vtl0 => DeviceVtl::Vtl0,
1539            crate::Vtl::Vtl1 => DeviceVtl::Vtl1,
1540            crate::Vtl::Vtl2 => DeviceVtl::Vtl2,
1541        };
1542        match controller.controller_type {
1543            VmbusStorageType::Scsi => {
1544                let mut devices = Vec::new();
1545                for (lun, Drive { disk, is_dvd }) in &controller.drives {
1546                    if !*is_dvd && let Some(disk) = disk {
1547                        devices.push(ScsiDeviceAndPath {
1548                            path: ScsiPath {
1549                                path: 0,
1550                                target: 0,
1551                                lun: (*lun).try_into().expect("invalid scsi lun"),
1552                            },
1553                            device: SimpleScsiDiskHandle {
1554                                disk: petri_disk_to_openvmm(disk).await?,
1555                                read_only: false,
1556                                parameters: Default::default(),
1557                            }
1558                            .into_resource(),
1559                        });
1560                    } else {
1561                        todo!("dvd ({}) or empty ({})", *is_dvd, disk.is_none())
1562                    }
1563                }
1564
1565                vmbus_devices.push((
1566                    vtl,
1567                    ScsiControllerHandle {
1568                        instance_id: *instance_id,
1569                        max_sub_channel_count: 1,
1570                        io_queue_depth: None,
1571                        devices,
1572                        requests: None,
1573                        poll_mode_queue_depth: None,
1574                    }
1575                    .into_resource(),
1576                ));
1577            }
1578            VmbusStorageType::Nvme => {
1579                let mut namespaces = Vec::new();
1580                for (nsid, Drive { disk, is_dvd }) in &controller.drives {
1581                    if !*is_dvd && let Some(disk) = disk {
1582                        namespaces.push(NamespaceDefinition {
1583                            nsid: *nsid,
1584                            read_only: false,
1585                            disk: petri_disk_to_openvmm(disk).await?,
1586                        });
1587                    } else {
1588                        todo!("dvd ({}) or empty ({})", *is_dvd, disk.is_none())
1589                    }
1590                }
1591
1592                vpci_devices.push(VpciDeviceConfig {
1593                    vtl,
1594                    instance_id: *instance_id,
1595                    resource: NvmeControllerHandle {
1596                        subsystem_id: *instance_id,
1597                        max_io_queues: 64,
1598                        msix_count: 64,
1599                        namespaces,
1600                        requests: None,
1601                    }
1602                    .into_resource(),
1603                    vnode: None,
1604                });
1605            }
1606            VmbusStorageType::VirtioBlk => {
1607                // Each virtio-blk drive needs a unique VPCI instance ID.
1608                // Use a fixed template GUID with data1 set to the LUN.
1609                const VIRTIO_BLK_INSTANCE_ID_TEMPLATE: Guid = Guid {
1610                    data1: 0,
1611                    data2: 0x1234,
1612                    data3: 0x5678,
1613                    data4: [0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89],
1614                };
1615                for (lun, Drive { disk, is_dvd }) in &controller.drives {
1616                    if *is_dvd {
1617                        anyhow::bail!("dvd not supported with virtio-blk");
1618                    }
1619                    let Some(disk) = disk else {
1620                        anyhow::bail!("empty drive not supported with virtio-blk");
1621                    };
1622                    let mut drive_id = VIRTIO_BLK_INSTANCE_ID_TEMPLATE;
1623                    drive_id.data1 = *lun;
1624                    vpci_devices.push(VpciDeviceConfig {
1625                        vtl,
1626                        instance_id: drive_id,
1627                        resource: VirtioPciDeviceHandle(
1628                            VirtioBlkHandle {
1629                                disk: petri_disk_to_openvmm(disk).await?,
1630                                read_only: false,
1631                                serial: None,
1632                                options: Default::default(),
1633                            }
1634                            .into_resource(),
1635                        )
1636                        .into_resource(),
1637                        vnode: None,
1638                    });
1639                }
1640            }
1641        }
1642    }
1643
1644    Ok((vmbus_devices, vpci_devices))
1645}