Skip to main content

petri/vm/
mod.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4/// Hyper-V VM management
5#[cfg(windows)]
6pub mod hyperv;
7/// OpenVMM VM management
8pub mod openvmm;
9/// QEMU full machine emulation management
10pub mod qemu;
11pub mod vtl2_settings;
12
13use crate::PetriLogSource;
14use crate::PetriTestParams;
15use crate::ShutdownKind;
16use crate::disk_image::AgentImage;
17use crate::disk_image::ImageEntry;
18use crate::disk_image::SECTOR_SIZE;
19use crate::mshv_boot::MshvBoot;
20use crate::openhcl_diag::OpenHclDiagHandler;
21use crate::test::PetriPostTestHook;
22use crate::vtl2_settings::ControllerType;
23use crate::vtl2_settings::Vtl2LunBuilder;
24use crate::vtl2_settings::Vtl2StorageBackingDeviceBuilder;
25use crate::vtl2_settings::Vtl2StorageControllerBuilder;
26use anyhow::Context;
27use async_trait::async_trait;
28use futures::FutureExt as _;
29use get_resources::ged::FirmwareEvent;
30use guid::Guid;
31use mesh::CancelContext;
32use openvmm_defs::config::Vtl2BaseAddressType;
33use pal_async::DefaultDriver;
34use pal_async::task::Spawn;
35use pal_async::task::Task;
36use pal_async::timer::PolledTimer;
37use petri_artifact_resolver_openvmm_known_paths::resolve_artifact;
38use petri_artifacts_common::tags::GuestQuirks;
39use petri_artifacts_common::tags::GuestQuirksInner;
40use petri_artifacts_common::tags::InitialRebootCondition;
41use petri_artifacts_common::tags::IsLoadable;
42use petri_artifacts_common::tags::IsOpenhclIgvm;
43use petri_artifacts_common::tags::IsTestVmgs;
44use petri_artifacts_common::tags::MachineArch;
45use petri_artifacts_common::tags::OsFlavor;
46use petri_artifacts_core::ArtifactHandle;
47use petri_artifacts_core::ArtifactId;
48use petri_artifacts_core::ArtifactResolver;
49use petri_artifacts_core::ArtifactSource;
50use petri_artifacts_core::ErasedArtifactHandle;
51use petri_artifacts_core::ResolvedArtifact;
52use petri_artifacts_core::ResolvedArtifactSource;
53use petri_artifacts_core::ResolvedOptionalArtifact;
54use petri_artifacts_core::env::PETRI_REMOTE_ARTIFACTS;
55use petri_artifacts_core::tags::IsNextestArchive;
56use petri_artifacts_vmm_test::env::*;
57use pipette_client::PipetteClient;
58use std::collections::BTreeMap;
59use std::collections::HashMap;
60use std::fmt::Debug;
61use std::io::Write;
62use std::panic::AssertUnwindSafe;
63use std::path::Path;
64use std::path::PathBuf;
65use std::path::absolute;
66use std::sync::Arc;
67use std::time::Duration;
68use tempfile::TempPath;
69use vmgs_resources::GuestStateEncryptionPolicy;
70use vtl2_settings_proto::StorageController;
71use vtl2_settings_proto::Vtl2Settings;
72
73/// The set of artifacts and resources needed to instantiate a
74/// [`PetriVmBuilder`].
75pub struct PetriVmArtifacts<T: PetriVmmBackend> {
76    /// Artifacts needed to launch the host VMM used for the test
77    pub backend: T,
78    /// Firmware and/or OS to load into the VM and associated settings
79    pub firmware: Firmware,
80    /// The architecture of the VM
81    pub arch: MachineArch,
82    /// Agent to run in the guest
83    pub agent_image: Option<AgentImage>,
84    /// Agent to run in OpenHCL
85    pub openhcl_agent_image: Option<AgentImage>,
86    /// Raw pipette binary path (for embedding in initrd via CPIO append)
87    pub pipette_binary: Option<ResolvedArtifact>,
88    /// Nested test deps
89    pub nested_test: Option<NestedTestDeps>,
90}
91
92impl<T: PetriVmmBackend> PetriVmArtifacts<T> {
93    /// Resolves the artifacts needed to instantiate a [`PetriVmBuilder`].
94    ///
95    /// Returns `None` if the supplied configuration is not supported on this platform.
96    pub fn new(
97        resolver: &ArtifactResolver<'_>,
98        firmware: Firmware,
99        arch: MachineArch,
100        with_vtl0_pipette: bool,
101    ) -> Option<Self> {
102        Self::new_maybe_nested(resolver, firmware, arch, with_vtl0_pipette, None)
103    }
104
105    /// Resolves the artifacts needed to instantiate a [`PetriVmBuilder`].
106    ///
107    /// Returns `None` if the supplied configuration is not supported on this platform.
108    pub fn new_maybe_nested(
109        resolver: &ArtifactResolver<'_>,
110        firmware: Firmware,
111        arch: MachineArch,
112        with_vtl0_pipette: bool,
113        nested_test: Option<NestedTestDeps>,
114    ) -> Option<Self> {
115        // Cross-OS nesting needs shared artifacts because the host cannot query
116        // the nested binary.
117        let different_nested_target = nested_test
118            .as_ref()
119            .map(|t| t.archive.target_triple().unwrap())
120            .is_some_and(|t| {
121                let host_target = target_lexicon::Triple::host();
122                host_target.operating_system != t.operating_system
123            });
124
125        if !(T::SUPPORTS_CPU_EMULATION || arch == MachineArch::host())
126            || !T::check_compat(&firmware, arch)
127            || different_nested_target && !T::supports_file_sharing(&firmware)
128        {
129            return None;
130        }
131
132        let pipette_binary = if with_vtl0_pipette {
133            Some(Self::resolve_pipette_binary(
134                resolver,
135                firmware.os_flavor(),
136                arch,
137            ))
138        } else {
139            None
140        };
141
142        Some(Self {
143            backend: T::new(resolver, arch),
144            arch,
145            agent_image: (!firmware.is_isolated_without_paravisor()).then(|| {
146                if with_vtl0_pipette {
147                    AgentImage::new(firmware.os_flavor()).with_pipette(resolver, arch)
148                } else {
149                    AgentImage::new(firmware.os_flavor())
150                }
151            }),
152            openhcl_agent_image: if firmware.is_openhcl() {
153                Some(AgentImage::new(OsFlavor::Linux).with_pipette(resolver, arch))
154            } else {
155                None
156            },
157            pipette_binary,
158            firmware,
159            nested_test,
160        })
161    }
162
163    fn resolve_pipette_binary(
164        resolver: &ArtifactResolver<'_>,
165        os_flavor: OsFlavor,
166        arch: MachineArch,
167    ) -> ResolvedArtifact {
168        use petri_artifacts_common::artifacts as common_artifacts;
169        match (os_flavor, arch) {
170            (OsFlavor::Linux, MachineArch::X86_64) => resolver
171                .require(common_artifacts::PIPETTE_LINUX_X64_MUSL)
172                .erase(),
173            (OsFlavor::Linux, MachineArch::Aarch64) => resolver
174                .require(common_artifacts::PIPETTE_LINUX_AARCH64_MUSL)
175                .erase(),
176            (OsFlavor::Windows, MachineArch::X86_64) => resolver
177                .require(common_artifacts::PIPETTE_WINDOWS_X64)
178                .erase(),
179            (OsFlavor::Windows, MachineArch::Aarch64) => resolver
180                .require(common_artifacts::PIPETTE_WINDOWS_AARCH64)
181                .erase(),
182            (OsFlavor::FreeBsd | OsFlavor::Uefi, _) => {
183                panic!("No pipette binary for this OS flavor")
184            }
185        }
186    }
187}
188
189/// Petri VM builder
190pub struct PetriVmBuilder<T: PetriVmmBackend> {
191    /// Artifacts needed to launch the host VMM used for the test
192    backend: T,
193    /// VM configuration
194    config: PetriVmConfig,
195    /// Function to modify the VMM-specific configuration
196    modify_vmm_config: Option<ModifyFn<T::VmmConfig>>,
197    /// VMM-agnostic resources
198    resources: PetriVmResources,
199
200    // VMM-specific quirks for the configured firmware
201    guest_quirks: GuestQuirksInner,
202    vmm_quirks: VmmQuirks,
203
204    // Test-specific boot behavior expectations.
205    // Defaults to expected behavior for firmware configuration.
206    expected_boot_event: Option<FirmwareEvent>,
207    override_expect_reset: bool,
208
209    // Config that is used to modify the `PetriVmConfig` before it is passed
210    // to the VMM backend.
211    /// Agent to run in the guest
212    agent_image: Option<AgentImage>,
213    /// Agent to run in OpenHCL
214    openhcl_agent_image: Option<AgentImage>,
215    /// The boot device type for the VM
216    boot_device_type: BootDeviceType,
217    /// Override for the PCIe root port used for a PCIe boot disk.
218    /// Defaults to `s0rc0rp0`.
219    pcie_boot_port: Option<String>,
220
221    // Minimal mode: skip default devices, serial, save/restore.
222    minimal_mode: bool,
223    // Raw pipette binary path (for CPIO embedding in initrd).
224    pipette_binary: Option<ResolvedArtifact>,
225    // Enable serial output even in minimal mode (for diagnostics).
226    enable_serial: bool,
227    use_virtio_console: bool,
228    // Enable periodic framebuffer screenshots.
229    enable_screenshots: bool,
230    // Use virtio vsock instead of VMBus-based hvsocket for guest communication.
231    use_virtio_vsock: bool,
232    // Use the Linux kernel vhost-vsock backend with this guest CID.
233    #[cfg(target_os = "linux")]
234    vhost_vsock_guest_cid: Option<u32>,
235    // Disable VMBus entirely (no vmbus server, no vmbus storage controllers).
236    no_vmbus: bool,
237    // Disable the hypervisor (HV#1) enlightenments. Implies `no_vmbus`.
238    no_hv: bool,
239    // Capture the VM's inspect output on test failure.
240    capture_inspect_on_failure: bool,
241    watchdog_timeout: Option<Duration>,
242    external_pipette: bool,
243
244    nested_test: Option<ResolvedNestedTestDeps>,
245}
246
247/// How long to wait on a single inspect before giving up on it.
248const INSPECT_TIMEOUT: Duration = Duration::from_secs(10);
249
250impl<T: PetriVmmBackend> Debug for PetriVmBuilder<T> {
251    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
252        let Self {
253            backend,
254            config,
255            modify_vmm_config,
256            resources,
257            guest_quirks,
258            vmm_quirks,
259            expected_boot_event,
260            override_expect_reset,
261            agent_image,
262            openhcl_agent_image,
263            boot_device_type,
264            pcie_boot_port,
265            minimal_mode,
266            pipette_binary,
267            enable_serial,
268            use_virtio_console,
269            enable_screenshots,
270            use_virtio_vsock,
271            #[cfg(target_os = "linux")]
272            vhost_vsock_guest_cid,
273            no_vmbus,
274            no_hv,
275            capture_inspect_on_failure,
276            watchdog_timeout,
277            external_pipette,
278            nested_test,
279        } = self;
280
281        let mut s = f.debug_struct("PetriVmBuilder");
282        s.field("backend", backend)
283            .field("config", config)
284            .field("modify_vmm_config", modify_vmm_config)
285            .field("resources", resources)
286            .field("guest_quirks", guest_quirks)
287            .field("vmm_quirks", vmm_quirks)
288            .field("expected_boot_event", expected_boot_event)
289            .field("override_expect_reset", override_expect_reset)
290            .field("agent_image", agent_image)
291            .field("openhcl_agent_image", openhcl_agent_image)
292            .field("boot_device_type", boot_device_type)
293            .field("pcie_boot_port", pcie_boot_port)
294            .field("minimal_mode", minimal_mode)
295            .field("pipette_binary", pipette_binary)
296            .field("enable_serial", enable_serial)
297            .field("use_virtio_console", use_virtio_console)
298            .field("enable_screenshots", enable_screenshots)
299            .field("use_virtio_vsock", use_virtio_vsock);
300        #[cfg(target_os = "linux")]
301        s.field("vhost_vsock_guest_cid", vhost_vsock_guest_cid);
302        s.field("no_vmbus", no_vmbus)
303            .field("no_hv", no_hv)
304            .field("capture_inspect_on_failure", capture_inspect_on_failure)
305            .field("watchdog_timeout", watchdog_timeout)
306            .field("external_pipette", external_pipette)
307            .field("nested_test", nested_test)
308            .finish()
309    }
310}
311
312/// Petri VM configuration
313#[derive(Debug, Clone)]
314pub struct PetriVmConfig {
315    /// The name of the VM
316    pub name: String,
317    /// The architecture of the VM
318    pub arch: MachineArch,
319    /// Log levels for the host VMM process.
320    pub host_log_levels: Option<OpenvmmLogConfig>,
321    /// Firmware and/or OS to load into the VM and associated settings
322    pub firmware: Firmware,
323    /// Whether to enable guest hibernation support.
324    pub hibernation_enabled: bool,
325    /// Whether to expose an IPMI KCS interface to the guest.
326    pub ipmi_enabled: bool,
327    /// The amount of memory, in bytes, to assign to the VM
328    pub memory: MemoryConfig,
329    /// The processor topology for the VM
330    pub proc_topology: ProcessorTopology,
331    /// Expose nested virtualization capabilities to the guest
332    pub nested_virt_enabled: bool,
333    /// VM guest state
334    pub vmgs: PetriVmgsResource,
335    /// TPM configuration
336    pub tpm: Option<TpmConfig>,
337    /// Storage controllers and associated disks
338    pub vmbus_storage_controllers: HashMap<Guid, VmbusStorageController>,
339    /// PCIe NVMe drives.
340    pub pcie_nvme_drives: Vec<PcieNvmeDrive>,
341    /// PCIe virtio-blk drives.
342    pub pcie_virtio_blk_drives: Vec<PcieVirtioBlkDrive>,
343    /// Physical NVMe devices to attach
344    pub physical_nvme_devices: HashMap<Guid, PhysicalNvmeDevice>,
345    /// Path to share with the guest
346    pub guest_shares: HashMap<String, GuestShare>,
347}
348
349/// A host directory exposed through a guest filesystem device.
350#[derive(Debug, Clone)]
351pub struct GuestShare {
352    /// Directory on the host.
353    pub host_path: PathBuf,
354    /// Absolute mount point in the Linux guest.
355    pub guest_path: String,
356}
357
358/// PCIe NVMe drive configuration.
359#[derive(Debug, Clone)]
360pub struct PcieNvmeDrive {
361    /// PCIe root port name (e.g. "s0rc0rp0").
362    pub port_name: String,
363    /// NVMe namespace ID.
364    pub nsid: u32,
365    /// The drive to attach.
366    pub drive: Drive,
367}
368
369/// PCIe virtio-blk drive configuration.
370#[derive(Debug, Clone)]
371pub struct PcieVirtioBlkDrive {
372    /// PCIe root port name (e.g. "s0rc0rp0").
373    pub port_name: String,
374    /// The drive to attach.
375    pub drive: Drive,
376}
377
378/// Physical NVMe device to assign to a VM.
379/// Only used in closed-source HyperV tests
380#[derive(Debug, Clone)]
381pub struct PhysicalNvmeDevice {
382    /// The VTL to assign the physical NVMe device to.
383    pub target_vtl: Vtl,
384    /// NVMe namespace ID.
385    pub nsid: u32,
386    /// Namespace size in MiB
387    pub namespace_size_mib: u64,
388}
389
390/// Static properties about the VM for convenience during contruction and
391/// runtime of a VMM backend
392#[derive(Clone)]
393pub struct PetriVmProperties {
394    /// Whether this VM uses OpenHCL
395    pub is_openhcl: bool,
396    /// Whether this VM is isolated
397    pub is_isolated: bool,
398    /// Whether this VM uses the PCAT BIOS
399    pub is_pcat: bool,
400    /// Whether this VM boots with linux direct
401    pub is_linux_direct: bool,
402    /// Whether this VM is using pipette in VTL0
403    pub using_vtl0_pipette: bool,
404    /// Pipette is supplied and started by the guest rather than Petri.
405    pub external_pipette: bool,
406    /// Whether this VM is using VPCI
407    pub using_vpci: bool,
408    /// The OS flavor of the guest in the VM
409    pub os_flavor: OsFlavor,
410    /// Minimal mode: skip default devices, serial, save/restore
411    pub minimal_mode: bool,
412    /// Petri injects Pipette into the initrd as PID 1.
413    pub uses_pipette_as_init: bool,
414    /// Enable serial output even in minimal mode
415    pub enable_serial: bool,
416    /// Capture a Linux virtio console independently of the firmware UART.
417    pub use_virtio_console: bool,
418    /// Whether the VM has a CIDATA agent disk attached
419    pub has_agent_disk: bool,
420    /// Use virtio vsock instead of VMBus-based hvsocket
421    pub use_virtio_vsock: bool,
422    /// Linux kernel vhost-vsock guest CID, when that backend is enabled.
423    #[cfg(target_os = "linux")]
424    pub vhost_vsock_guest_cid: Option<u32>,
425    /// VMBus is entirely disabled
426    pub no_vmbus: bool,
427    /// The hypervisor (HV#1) enlightenments are entirely disabled
428    pub no_hv: bool,
429}
430
431/// VM configuration that can be changed after the VM is created
432pub struct PetriVmRuntimeConfig {
433    /// VTL2 settings
434    pub vtl2_settings: Option<Vtl2Settings>,
435    /// IDE controllers and associated disks
436    pub ide_controllers: Option<[[Option<Drive>; 2]; 2]>,
437    /// Storage controllers and associated disks
438    pub vmbus_storage_controllers: HashMap<Guid, VmbusStorageController>,
439}
440
441/// Resources used by a Petri VM during contruction and runtime
442#[derive(Debug)]
443pub struct PetriVmResources {
444    /// Driver to use for async tasks during VM construction and runtime
445    pub driver: DefaultDriver,
446    /// Log source
447    pub log_source: PetriLogSource,
448    /// Pre-built initrd with pipette already injected (skips runtime injection).
449    pub prebuilt_initrd: Option<PetriInitrd>,
450}
451
452/// Trait for VMM-specific contruction and runtime resources
453#[async_trait]
454pub trait PetriVmmBackend: Debug {
455    /// VMM-specific configuration
456    type VmmConfig: 'static;
457
458    /// Runtime object
459    type VmRuntime: PetriVmRuntime;
460
461    /// Whether the backend supports VMBus.
462    const SUPPORTS_VMBUS: bool;
463
464    /// Whether the backend supports full CPU emulation
465    ///
466    /// If this is false, then tests are silently skipped if the host
467    /// architecture does not match the guest architecture.
468    const SUPPORTS_CPU_EMULATION: bool = false;
469
470    /// Whether this backend supports sharing host directories with Linux guests.
471    const SUPPORTS_FILE_SHARING: bool = false;
472
473    /// Whether this guest can use the backend's Linux 9p shares.
474    fn supports_file_sharing(firmware: &Firmware) -> bool {
475        Self::SUPPORTS_FILE_SHARING && firmware.os_flavor() == OsFlavor::Linux
476    }
477
478    /// Check whether the combination of guest firmware, guest architecture, and
479    /// internally determined host properties is supported by the backend.
480    ///
481    /// Any combinations that return false will be silently skipped. This should
482    /// not be used to skip configurations that are never valid (for example,
483    /// PCAT AARCH64 should always result in an error), and only be used if the
484    /// configuration is sometimes valid (for example, OpenVMM + OpenHCL is only
485    /// valid on Windows X64 hosts).
486    fn check_compat(firmware: &Firmware, arch: MachineArch) -> bool;
487
488    /// Select backend specific quirks guest and vmm quirks.
489    fn quirks(firmware: &Firmware) -> (GuestQuirksInner, VmmQuirks);
490
491    /// Get the default servicing flags (based on what this backend supports)
492    fn default_servicing_flags() -> OpenHclServicingFlags;
493
494    /// Create a disk for guest crash dumps, and a post-test hook to open the disk
495    /// to allow for reading the dumps.
496    fn create_guest_dump_disk() -> anyhow::Result<
497        Option<(
498            Arc<TempPath>,
499            Box<dyn FnOnce() -> anyhow::Result<Box<dyn fatfs::ReadWriteSeek>>>,
500        )>,
501    >;
502
503    /// Generate an rdinit script that does the necessary configuration to
504    /// launch pipette for linux direct
505    fn build_custom_init_script(pipette_path: &str) -> Option<String>;
506
507    /// Resolve any artifacts needed to use this backend
508    ///
509    /// The architecture here is that of the guest, which may or may not be the
510    /// same as the host.
511    fn new(resolver: &ArtifactResolver<'_>, arch: MachineArch) -> Self;
512
513    /// Create and start VM from the generic config using the VMM backend
514    async fn run(
515        self,
516        config: PetriVmConfig,
517        modify_vmm_config: Option<ModifyFn<Self::VmmConfig>>,
518        resources: &PetriVmResources,
519        properties: &PetriVmProperties,
520    ) -> anyhow::Result<(Self::VmRuntime, PetriVmRuntimeConfig)>;
521}
522
523// IDE is only ever offered to VTL0
524pub(crate) const PETRI_IDE_BOOT_CONTROLLER_NUMBER: u32 = 0;
525pub(crate) const PETRI_IDE_BOOT_LUN: u8 = 0;
526pub(crate) const PETRI_IDE_BOOT_CONTROLLER: Guid =
527    guid::guid!("ca56751f-e643-4bef-bf54-f73678e8b7b5");
528
529// SCSI luns used for both VTL0 and VTL2
530pub(crate) const PETRI_SCSI_BOOT_LUN: u32 = 0;
531pub(crate) const PETRI_SCSI_PIPETTE_LUN: u32 = 1;
532pub(crate) const PETRI_SCSI_CRASH_LUN: u32 = 2;
533/// VTL0 SCSI controller instance guid used by Petri
534pub(crate) const PETRI_SCSI_VTL0_CONTROLLER: Guid =
535    guid::guid!("27b553e8-8b39-411b-a55f-839971a7884f");
536/// VTL2 SCSI controller instance guid used by Petri
537pub(crate) const PETRI_SCSI_VTL2_CONTROLLER: Guid =
538    guid::guid!("766e96f8-2ceb-437e-afe3-a93169e48a7c");
539/// SCSI controller instance guid offered to VTL0 by VTL2
540pub(crate) const PETRI_SCSI_VTL0_VIA_VTL2_CONTROLLER: Guid =
541    guid::guid!("6c474f47-ed39-49e6-bbb9-142177a1da6e");
542
543/// The namespace ID used by Petri for the boot disk
544pub(crate) const PETRI_NVME_BOOT_NSID: u32 = 37;
545/// VTL0 NVMe controller instance guid used by Petri
546pub(crate) const PETRI_NVME_BOOT_VTL0_CONTROLLER: Guid =
547    guid::guid!("e23a04e2-90f5-4852-bc9d-e7ac691b756c");
548/// VTL2 NVMe controller instance guid used by Petri
549pub(crate) const PETRI_NVME_BOOT_VTL2_CONTROLLER: Guid =
550    guid::guid!("92bc8346-718b-449a-8751-edbf3dcd27e4");
551
552/// PCIe root port used by Petri for the agent/cidata disk (no-vmbus mode)
553pub(crate) const PETRI_PCIE_NVME_AGENT_PORT: &str = "s0rc0rp1";
554/// NVMe namespace ID used by Petri for the agent/cidata disk (no-vmbus mode)
555pub(crate) const PETRI_PCIE_NVME_AGENT_NSID: u32 = 1;
556
557const NESTED_TEST_CONTENT_DIR: &str = "vmm_tests";
558const NESTED_IMAGES_DIR: &str = "images";
559const NESTED_RESULTS_DIR: &str = "test_results";
560const NESTED_TEST_BINARY: &str = "nested_test";
561const NESTED_TEMP_DIR: &str = "temp";
562const NESTED_CONTENT_TAG: &str = "testcontent";
563const NESTED_IMAGES_TAG: &str = "testimages";
564
565/// A constructed Petri VM
566pub struct PetriVm<T: PetriVmmBackend> {
567    resources: PetriVmResources,
568    runtime: PetriVmRuntimeGuard<T::VmRuntime>,
569    watchdog_tasks: Vec<Task<()>>,
570    openhcl_diag_handler: Option<OpenHclDiagHandler>,
571
572    arch: MachineArch,
573    guest_quirks: GuestQuirksInner,
574    vmm_quirks: VmmQuirks,
575    expected_boot_event: Option<FirmwareEvent>,
576
577    config: PetriVmRuntimeConfig,
578    properties: PetriVmProperties,
579
580    nested_test: Option<ResolvedNestedTestDeps>,
581    guest_shares: HashMap<String, GuestShare>,
582    name: String,
583}
584
585/// Wrapper around the VMM backend's runtime that captures inspect state if the
586/// VM is dropped without being torn down, which is what happens when a test
587/// fails partway through.
588struct PetriVmRuntimeGuard<T: PetriVmRuntime> {
589    runtime: Option<T>,
590    driver: DefaultDriver,
591    log_source: PetriLogSource,
592    capture_inspect_on_drop: bool,
593}
594
595impl<T: PetriVmRuntime> PetriVmRuntimeGuard<T> {
596    fn take_for_teardown(&mut self) -> T {
597        self.runtime.take().expect("runtime has already been taken")
598    }
599}
600
601impl<T: PetriVmRuntime> std::ops::Deref for PetriVmRuntimeGuard<T> {
602    type Target = T;
603
604    fn deref(&self) -> &T {
605        self.runtime
606            .as_ref()
607            .expect("runtime has already been taken")
608    }
609}
610
611impl<T: PetriVmRuntime> std::ops::DerefMut for PetriVmRuntimeGuard<T> {
612    fn deref_mut(&mut self) -> &mut T {
613        self.runtime
614            .as_mut()
615            .expect("runtime has already been taken")
616    }
617}
618
619impl<T: PetriVmRuntime> Drop for PetriVmRuntimeGuard<T> {
620    fn drop(&mut self) {
621        let Some(runtime) = self.runtime.take() else {
622            return;
623        };
624        if !self.capture_inspect_on_drop {
625            return;
626        }
627        let inspector = runtime.inspector();
628        let openhcl_diag_handler = runtime.openhcl_diag();
629        if inspector.is_none() && openhcl_diag_handler.is_none() {
630            return;
631        }
632        let log_source = self.log_source.clone();
633
634        let capture = async move {
635            let vmm = async {
636                if let Some(inspector) = &inspector {
637                    collect_inspect("vmm", inspector.inspect(""), &log_source, "failure").await;
638                }
639            };
640            let openhcl = async {
641                if let Some(diag) = &openhcl_diag_handler {
642                    collect_inspect(
643                        "openhcl",
644                        diag.inspect("", None, None),
645                        &log_source,
646                        "failure",
647                    )
648                    .await;
649                }
650            };
651            futures::future::join(vmm, openhcl).await;
652            drop(runtime);
653        };
654
655        // `SimpleTest::new_async` joins the test body with the task pool, so
656        // the pool keeps polling detached tasks until they complete. This
657        // finishes before the post-test hooks run.
658        self.driver
659            .spawn("petri-inspect-on-drop", async move {
660                // A panic here would propagate out of the task pool and replace
661                // the failure the test is already reporting.
662                if let Err(e) = AssertUnwindSafe(capture).catch_unwind().await {
663                    tracing::error!(?e, "panicked while collecting inspect state");
664                }
665            })
666            .detach();
667    }
668}
669
670impl<T: PetriVmmBackend> PetriVmBuilder<T> {
671    /// Create a new VM configuration.
672    pub fn new(
673        params: PetriTestParams<'_>,
674        artifacts: PetriVmArtifacts<T>,
675        driver: &DefaultDriver,
676    ) -> anyhow::Result<Self> {
677        let isolated_without_paravisor = artifacts.firmware.is_isolated_without_paravisor();
678        let mshv = artifacts.firmware.mshv_boot().is_some();
679        let builder = Self::minimal(params.test_name, params.log_source, artifacts, driver)?
680            .clear_minimal_mode()
681            .with_serial_output()
682            .with_capture_inspect_on_failure();
683        if isolated_without_paravisor || mshv {
684            Ok(builder)
685        } else {
686            builder
687                .add_petri_scsi_controllers()
688                .add_guest_crash_disk(params.post_test_hooks)
689        }
690    }
691
692    /// Create a minimal VM builder with only the bare minimum device set.
693    ///
694    /// Unlike [`new()`](Self::new), this constructor:
695    /// - Does not add default VMBus devices (shutdown IC, KVP, etc.)
696    /// - Does not add serial ports
697    /// - Does not add SCSI controllers or crash dump disks
698    /// - Does not verify save/restore on boot
699    ///
700    /// Use builder methods to opt in to specific devices. Intended for
701    /// performance tests where minimal overhead is critical.
702    pub fn minimal(
703        test_name: &str,
704        log_source: &PetriLogSource,
705        artifacts: PetriVmArtifacts<T>,
706        driver: &DefaultDriver,
707    ) -> anyhow::Result<Self> {
708        let isolated_without_paravisor = artifacts.firmware.is_isolated_without_paravisor();
709        match &artifacts.firmware {
710            Firmware::Uefi {
711                guest: UefiGuest::Mshv(_),
712                ..
713            } => anyhow::ensure!(
714                artifacts.arch == MachineArch::X86_64,
715                "mshv boot requires x86-64 UEFI"
716            ),
717            Firmware::OpenhclUefi {
718                guest: UefiGuest::Mshv(_),
719                ..
720            } => anyhow::bail!("mshv boot with OpenHCL is not supported"),
721            _ => {}
722        }
723        let (guest_quirks, vmm_quirks) = T::quirks(&artifacts.firmware);
724        let expected_boot_event = artifacts.firmware.expected_boot_event();
725        let boot_device_type = match artifacts.firmware {
726            Firmware::LinuxDirect { .. } | Firmware::IgvmLinuxDirect { .. } => BootDeviceType::None,
727            Firmware::OpenhclLinuxDirect { .. } => BootDeviceType::None,
728            Firmware::Pcat { .. } => BootDeviceType::Ide,
729            Firmware::OpenhclPcat { .. } => BootDeviceType::IdeViaScsi,
730            Firmware::Uefi {
731                guest: UefiGuest::None,
732                ..
733            }
734            | Firmware::OpenhclUefi {
735                guest: UefiGuest::None,
736                ..
737            } => BootDeviceType::None,
738            Firmware::Uefi { .. } | Firmware::OpenhclUefi { .. } => BootDeviceType::Scsi,
739        };
740
741        let supports_file_sharing = T::supports_file_sharing(&artifacts.firmware);
742        let external_pipette = isolated_without_paravisor && artifacts.pipette_binary.is_some();
743        let builder = Self {
744            backend: artifacts.backend,
745            config: PetriVmConfig {
746                name: test_name.to_string(),
747                arch: artifacts.arch,
748                host_log_levels: None,
749                firmware: artifacts.firmware,
750                hibernation_enabled: false,
751                ipmi_enabled: false,
752                memory: Default::default(),
753                proc_topology: Default::default(),
754                nested_virt_enabled: false,
755
756                vmgs: PetriVmgsResource::Ephemeral,
757                tpm: None,
758                vmbus_storage_controllers: HashMap::new(),
759                pcie_nvme_drives: Vec::new(),
760                pcie_virtio_blk_drives: Vec::new(),
761                physical_nvme_devices: HashMap::new(),
762                guest_shares: HashMap::new(),
763            },
764            modify_vmm_config: None,
765            resources: PetriVmResources {
766                driver: driver.clone(),
767                log_source: log_source.clone(),
768                prebuilt_initrd: None,
769            },
770
771            guest_quirks,
772            vmm_quirks,
773            expected_boot_event,
774            override_expect_reset: false,
775
776            agent_image: artifacts.agent_image,
777            openhcl_agent_image: artifacts.openhcl_agent_image,
778            boot_device_type,
779            pcie_boot_port: None,
780
781            minimal_mode: true,
782            pipette_binary: artifacts.pipette_binary,
783            enable_serial: false,
784            use_virtio_console: false,
785            enable_screenshots: true,
786            use_virtio_vsock: isolated_without_paravisor,
787            #[cfg(target_os = "linux")]
788            vhost_vsock_guest_cid: None,
789            no_vmbus: !T::SUPPORTS_VMBUS || isolated_without_paravisor,
790            no_hv: false,
791            capture_inspect_on_failure: false,
792            watchdog_timeout: Some(Duration::from_mins(10)),
793            external_pipette: false,
794
795            nested_test: artifacts
796                .nested_test
797                .map(|t| t.resolve(!supports_file_sharing))
798                .transpose()?,
799        };
800        Ok(if external_pipette {
801            builder.with_external_pipette()
802        } else {
803            builder
804        })
805    }
806
807    fn clear_minimal_mode(mut self) -> Self {
808        self.minimal_mode = false;
809        self
810    }
811
812    /// Share a directory over 9p and mount it after Pipette connects.
813    ///
814    /// The backend attaches the filesystem device automatically.
815    pub fn with_shared_directory(
816        mut self,
817        tag: &str,
818        host_path: impl AsRef<Path>,
819        guest_path: &str,
820    ) -> Self {
821        assert!(
822            T::supports_file_sharing(&self.config.firmware),
823            "directory sharing requires a backend with Linux file-sharing support"
824        );
825        assert!(
826            !tag.is_empty()
827                && !tag.starts_with('-')
828                && tag
829                    .bytes()
830                    .all(|c| c.is_ascii_alphanumeric() || b"-_".contains(&c)),
831            "invalid filesystem share tag"
832        );
833        assert!(
834            guest_path.starts_with('/')
835                && !guest_path.contains('\0')
836                && !guest_path.split('/').any(|c| c == ".."),
837            "guest mount point must be an absolute path without parent traversal"
838        );
839        assert!(
840            !self.config.guest_shares.contains_key(tag),
841            "duplicate filesystem share tag: {tag}"
842        );
843        self.config.guest_shares.insert(
844            tag.into(),
845            GuestShare {
846                host_path: host_path.as_ref().to_path_buf(),
847                guest_path: guest_path.into(),
848            },
849        );
850        self
851    }
852
853    fn with_capture_inspect_on_failure(mut self) -> Self {
854        self.capture_inspect_on_failure = true;
855        self
856    }
857
858    /// Whether this builder is in minimal mode.
859    pub fn is_minimal(&self) -> bool {
860        self.minimal_mode
861    }
862
863    /// Set the diagnostic watchdog deadline. A standalone runner that owns its
864    /// own cancellation policy can disable the test watchdog with `None`.
865    pub fn with_watchdog_timeout(mut self, timeout: Option<Duration>) -> Self {
866        self.watchdog_timeout = timeout;
867        self
868    }
869
870    /// Use Pipette supplied and started by the guest image, without adding an
871    /// agent disk or injecting Pipette into a Linux-direct initrd.
872    ///
873    /// OpenVMM Linux-direct boot leaves the initrd's default entry point intact
874    /// unless [`Self::with_prebuilt_initrd`] supplies an explicit `rdinit`.
875    pub fn with_external_pipette(mut self) -> Self {
876        self.external_pipette = true;
877        self.agent_image = None;
878        self.pipette_binary = None;
879        self
880    }
881
882    /// Supply a pre-built initrd with pipette already injected.
883    ///
884    /// When set, the builder skips the runtime gzip decompress/inject/
885    /// recompress cycle, using this initrd directly. Use
886    /// [`prepare_initrd`](Self::prepare_initrd) to build the initrd
887    /// ahead of time.
888    pub fn with_prebuilt_initrd(mut self, initrd: PetriInitrd) -> Self {
889        self.resources.prebuilt_initrd = Some(initrd);
890        self
891    }
892
893    /// Pre-build the modified initrd with pipette injected.
894    ///
895    /// Reads the original initrd from the firmware artifacts, injects
896    /// the pipette binary via CPIO, and writes the result to a temp file.
897    /// Returns a [`PetriInitrd`] struct that contains a `TempFile` that
898    /// must not be dropped until after the VM boots.
899    ///
900    /// Call this once before timing, then pass the path to
901    /// [`with_prebuilt_initrd`](Self::with_prebuilt_initrd) for each
902    /// iteration.
903    pub fn prepare_initrd(&self) -> anyhow::Result<PetriInitrd> {
904        if let Some(boot) = self.config.firmware.mshv_boot() {
905            return boot.prepare_initrd(
906                self.pipette_binary
907                    .as_ref()
908                    .context("mshv initrd preparation requires Pipette")?,
909            );
910        }
911        self.prepare_custom_initrd(T::build_custom_init_script)
912    }
913
914    /// Prepare an initrd with a custom script
915    pub fn prepare_custom_initrd(
916        &self,
917        build_custom_init_script: impl FnOnce(&str) -> Option<String>,
918    ) -> anyhow::Result<PetriInitrd> {
919        const PIPETTE_PATH: &str = "pipette";
920        const INIT_SCRIPT_NAME: &str = "custom-init.sh";
921
922        let initrd_path = self
923            .config
924            .firmware
925            .linux_direct_initrd()
926            .context("prepare_initrd requires Linux direct boot with initrd")?;
927        let pipette_path = self
928            .pipette_binary
929            .as_ref()
930            .context("prepare_initrd requires a pipette binary")?;
931
932        let pipette_data = std::fs::read(pipette_path.get()).with_context(|| {
933            format!(
934                "failed to read pipette binary at {}",
935                pipette_path.get().display()
936            )
937        })?;
938
939        let mut files = vec![crate::initrd::InitrdFile {
940            name: PIPETTE_PATH,
941            contents: &pipette_data,
942            permissions: 0o755,
943        }];
944        let script = build_custom_init_script(PIPETTE_PATH);
945        let rdinit = if let Some(script) = &script {
946            files.push(crate::initrd::InitrdFile {
947                name: INIT_SCRIPT_NAME,
948                contents: script.as_bytes(),
949                permissions: 0o755,
950            });
951            format!("/{INIT_SCRIPT_NAME}")
952        } else {
953            format!("/{PIPETTE_PATH}")
954        };
955        PetriInitrd::prepare(initrd_path, &files, &rdinit, None)
956    }
957
958    /// Enable serial port output even in minimal mode.
959    ///
960    /// Useful for diagnostics — the serial device overhead is negligible;
961    /// the cost comes from kernel console output, which is controlled via
962    /// the kernel cmdline (`quiet loglevel=0`).
963    ///
964    /// Note: this currently only affects LinuxDirect boot (kernel cmdline
965    /// and emulated serial backends). UEFI paths are unaffected.
966    pub fn with_serial_output(mut self) -> Self {
967        self.enable_serial = true;
968        self
969    }
970
971    /// Disable serial port output.
972    ///
973    /// Suppresses serial device creation, eliminating the `[uefi]` / `[openhcl]`
974    /// log lines. Useful for performance tests where serial noise is unwanted.
975    pub fn without_serial_output(mut self) -> Self {
976        self.enable_serial = false;
977        self
978    }
979
980    /// Disable periodic framebuffer screenshots.
981    ///
982    /// Suppresses the watchdog task that takes screenshots every 2 seconds,
983    /// eliminating the "No change in framebuffer" debug log lines.
984    pub fn without_screenshots(mut self) -> Self {
985        self.enable_screenshots = false;
986        self
987    }
988
989    /// Use virtio vsock instead of VMBus-based hvsocket for guest communication.
990    /// The virtio-vsock device will use PCIe, so a PCIe root topology must be
991    /// configured.
992    ///
993    /// When enabled, a virtio-vsock device is added to the VM. This device uses
994    /// the same Unix socket relay path that hvsocket would otherwise use, so
995    /// pipette will connect using this.
996    ///
997    /// For Linux direct boot, this also adjusts the kernel command line to
998    /// blacklist hv_sock instead of virtio_vsock.
999    ///
1000    /// Disable it after [`Self::with_no_vmbus`] when selecting another transport.
1001    pub fn with_virtio_vsock(mut self, enable: bool) -> Self {
1002        self.use_virtio_vsock = enable;
1003        #[cfg(target_os = "linux")]
1004        {
1005            self.vhost_vsock_guest_cid = None;
1006        }
1007        self
1008    }
1009
1010    /// Use the Linux kernel vhost-vsock backend for guest communication.
1011    ///
1012    /// The host connects directly to the guest's `AF_VSOCK` listener at
1013    /// `guest_cid`. The OpenVMM backend automatically uses shared guest memory,
1014    /// which is required by kernel vhost.
1015    #[cfg(target_os = "linux")]
1016    pub fn with_vhost_vsock(mut self, guest_cid: u32) -> Self {
1017        assert!(
1018            (3..u32::MAX).contains(&guest_cid),
1019            "vhost-vsock guest CID must be between 3 and {}",
1020            u32::MAX - 1
1021        );
1022        self.use_virtio_vsock = true;
1023        self.vhost_vsock_guest_cid = Some(guest_cid);
1024        self
1025    }
1026
1027    /// Disable VMBus entirely.
1028    ///
1029    /// This removes all VMBus storage controllers. For Linux guests,
1030    /// virtio-vsock is used for pipette communication. For Windows guests,
1031    /// the caller must also configure TCP pipette transport via
1032    /// `modify_backend(|b| b.with_tcp_pipette_nic(port, mac_address))`. The
1033    /// guest must boot from a non-VMBus device (e.g. PCIe NVMe).
1034    pub fn with_no_vmbus(mut self) -> Self {
1035        self.no_vmbus = true;
1036        if self.config.firmware.os_flavor() != OsFlavor::Windows {
1037            self.use_virtio_vsock = true;
1038        }
1039        self.config.vmbus_storage_controllers.clear();
1040        self
1041    }
1042
1043    /// Disable the hypervisor (HV#1) enlightenments.
1044    ///
1045    /// This also disables VMBus, since VMBus depends on the hypervisor. On
1046    /// aarch64 UEFI this causes the loader to pass the generic SEC platform
1047    /// type to the firmware. This mode is not supported on x86_64 UEFI.
1048    pub fn with_no_hv(mut self) -> Self {
1049        self.no_hv = true;
1050        self.with_no_vmbus()
1051    }
1052
1053    fn add_petri_scsi_controllers(mut self) -> Self {
1054        if T::SUPPORTS_VMBUS {
1055            self = self.add_vmbus_storage_controller(
1056                &PETRI_SCSI_VTL0_CONTROLLER,
1057                Vtl::Vtl0,
1058                VmbusStorageType::Scsi,
1059            );
1060
1061            if self.is_openhcl() {
1062                self = self.add_vmbus_storage_controller(
1063                    &PETRI_SCSI_VTL2_CONTROLLER,
1064                    Vtl::Vtl2,
1065                    VmbusStorageType::Scsi,
1066                )
1067            }
1068        }
1069        self
1070    }
1071
1072    fn add_guest_crash_disk(
1073        self,
1074        post_test_hooks: &mut Vec<PetriPostTestHook>,
1075    ) -> anyhow::Result<Self> {
1076        let supports_vmbus_crash_disk = !self.no_vmbus
1077            && matches!(
1078                self.config.firmware.os_flavor(),
1079                OsFlavor::Windows | OsFlavor::Linux
1080            );
1081
1082        let (disk, disk_hook) = supports_vmbus_crash_disk
1083            .then(|| T::create_guest_dump_disk().context("failed to create guest dump disk"))
1084            .transpose()?
1085            .flatten()
1086            .unzip();
1087
1088        if let Some(disk_hook) = disk_hook {
1089            let logger = self.resources.log_source.clone();
1090            post_test_hooks.push(PetriPostTestHook::new(
1091                "extract guest crash dumps".into(),
1092                move |test_passed| {
1093                    if test_passed {
1094                        return Ok(());
1095                    }
1096                    let mut disk = disk_hook()?;
1097                    let gpt = gptman::GPT::read_from(&mut disk, SECTOR_SIZE)?;
1098                    let partition = fscommon::StreamSlice::new(
1099                        &mut disk,
1100                        gpt[1].starting_lba * SECTOR_SIZE,
1101                        gpt[1].ending_lba * SECTOR_SIZE,
1102                    )?;
1103                    let fs = fatfs::FileSystem::new(partition, fatfs::FsOptions::new())?;
1104                    for entry in fs.root_dir().iter() {
1105                        let Ok(entry) = entry else {
1106                            tracing::warn!(?entry, "failed to read entry in guest crash dump disk");
1107                            continue;
1108                        };
1109                        if !entry.is_file() {
1110                            tracing::warn!(
1111                                ?entry,
1112                                "skipping non-file entry in guest crash dump disk"
1113                            );
1114                            continue;
1115                        }
1116                        logger.write_attachment(&entry.file_name(), entry.to_file())?;
1117                    }
1118                    Ok(())
1119                },
1120            ));
1121        }
1122
1123        Ok(if let Some(disk) = disk {
1124            self.add_vmbus_drive(
1125                Drive::new(Some(Disk::Temporary(disk)), false),
1126                &PETRI_SCSI_VTL0_CONTROLLER,
1127                Some(PETRI_SCSI_CRASH_LUN),
1128            )
1129        } else {
1130            self
1131        })
1132    }
1133
1134    fn add_agent_disks(self) -> anyhow::Result<Self> {
1135        self.add_agent_disk_inner(Vtl::Vtl0)?
1136            .add_agent_disk_inner(Vtl::Vtl2)
1137    }
1138
1139    fn add_agent_disk_inner(mut self, target_vtl: Vtl) -> anyhow::Result<Self> {
1140        let (agent_image, controller_id) = match target_vtl {
1141            Vtl::Vtl0 => (self.agent_image.as_ref(), PETRI_SCSI_VTL0_CONTROLLER),
1142            Vtl::Vtl1 => panic!("no VTL1 agent disk"),
1143            Vtl::Vtl2 => (
1144                self.openhcl_agent_image.as_ref(),
1145                PETRI_SCSI_VTL2_CONTROLLER,
1146            ),
1147        };
1148
1149        // When using pipette-as-init, the VTL0 agent disk is only needed
1150        // if it carries extra files (pipette itself is in the initrd).
1151        if target_vtl == Vtl::Vtl0
1152            && self.uses_pipette_as_init()
1153            && !agent_image.is_some_and(|i| i.has_extras())
1154        {
1155            return Ok(self);
1156        }
1157
1158        let Some(agent_disk) = agent_image
1159            .map(|i| {
1160                i.build(crate::disk_image::ImageType::Vhd)
1161                    .context("failed to build agent image")
1162            })
1163            .transpose()?
1164            .flatten()
1165        else {
1166            return Ok(self);
1167        };
1168
1169        // When VMBus is disabled, route the agent disk through PCIe NVMe
1170        // instead of VMBus SCSI.
1171        if self.no_vmbus {
1172            self.config.pcie_nvme_drives.push(PcieNvmeDrive {
1173                port_name: PETRI_PCIE_NVME_AGENT_PORT.into(),
1174                nsid: PETRI_PCIE_NVME_AGENT_NSID,
1175                drive: Drive::new(
1176                    Some(Disk::Temporary(Arc::new(agent_disk.into_temp_path()))),
1177                    false,
1178                ),
1179            });
1180            return Ok(self);
1181        }
1182
1183        // Ensure the storage controller exists (minimal mode doesn't
1184        // add controllers upfront).
1185        if !self
1186            .config
1187            .vmbus_storage_controllers
1188            .contains_key(&controller_id)
1189        {
1190            self = self.add_vmbus_storage_controller(
1191                &controller_id,
1192                target_vtl,
1193                VmbusStorageType::Scsi,
1194            );
1195        }
1196
1197        Ok(self.add_vmbus_drive(
1198            Drive::new(
1199                Some(Disk::Temporary(Arc::new(agent_disk.into_temp_path()))),
1200                false,
1201            ),
1202            &controller_id,
1203            Some(PETRI_SCSI_PIPETTE_LUN),
1204        ))
1205    }
1206
1207    fn add_boot_disk(mut self) -> anyhow::Result<Self> {
1208        if self.boot_device_type.requires_vtl2() && !self.is_openhcl() {
1209            panic!("boot device type {:?} requires vtl2", self.boot_device_type);
1210        }
1211
1212        if self.no_vmbus && self.boot_device_type.requires_vmbus() {
1213            panic!(
1214                "boot device type {:?} requires vmbus, but vmbus is disabled; \
1215                 use with_boot_device_type(BootDeviceType::PcieNvme) or similar",
1216                self.boot_device_type
1217            );
1218        }
1219
1220        if self.boot_device_type.requires_vpci_boot() {
1221            self.config
1222                .firmware
1223                .uefi_config_mut()
1224                .expect("vpci boot requires uefi")
1225                .enable_vpci_boot = true;
1226        }
1227
1228        let builder = if let Some(boot_drive) = self.config.firmware.boot_drive(
1229            self.use_virtio_vsock,
1230            self.resources.prebuilt_initrd.as_ref(),
1231        )? {
1232            match self.boot_device_type {
1233                BootDeviceType::None => unreachable!(),
1234                BootDeviceType::Ide => self.add_ide_drive(
1235                    boot_drive,
1236                    PETRI_IDE_BOOT_CONTROLLER_NUMBER,
1237                    PETRI_IDE_BOOT_LUN,
1238                ),
1239                BootDeviceType::IdeViaScsi => self
1240                    .add_vmbus_drive(
1241                        boot_drive,
1242                        &PETRI_SCSI_VTL2_CONTROLLER,
1243                        Some(PETRI_SCSI_BOOT_LUN),
1244                    )
1245                    .add_vtl2_storage_controller(
1246                        Vtl2StorageControllerBuilder::new(ControllerType::Ide)
1247                            .with_instance_id(PETRI_IDE_BOOT_CONTROLLER)
1248                            .add_lun(
1249                                Vtl2LunBuilder::disk()
1250                                    .with_channel(PETRI_IDE_BOOT_CONTROLLER_NUMBER)
1251                                    .with_location(PETRI_IDE_BOOT_LUN as u32)
1252                                    .with_physical_device(Vtl2StorageBackingDeviceBuilder::new(
1253                                        ControllerType::Scsi,
1254                                        PETRI_SCSI_VTL2_CONTROLLER,
1255                                        PETRI_SCSI_BOOT_LUN,
1256                                    )),
1257                            )
1258                            .build(),
1259                    ),
1260                BootDeviceType::IdeViaNvme => todo!(),
1261                BootDeviceType::Scsi => self.add_vmbus_drive(
1262                    boot_drive,
1263                    &PETRI_SCSI_VTL0_CONTROLLER,
1264                    Some(PETRI_SCSI_BOOT_LUN),
1265                ),
1266                BootDeviceType::ScsiViaScsi => self
1267                    .add_vmbus_drive(
1268                        boot_drive,
1269                        &PETRI_SCSI_VTL2_CONTROLLER,
1270                        Some(PETRI_SCSI_BOOT_LUN),
1271                    )
1272                    .add_vtl2_storage_controller(
1273                        Vtl2StorageControllerBuilder::new(ControllerType::Scsi)
1274                            .with_instance_id(PETRI_SCSI_VTL0_VIA_VTL2_CONTROLLER)
1275                            .add_lun(
1276                                Vtl2LunBuilder::disk()
1277                                    .with_location(PETRI_SCSI_BOOT_LUN)
1278                                    .with_physical_device(Vtl2StorageBackingDeviceBuilder::new(
1279                                        ControllerType::Scsi,
1280                                        PETRI_SCSI_VTL2_CONTROLLER,
1281                                        PETRI_SCSI_BOOT_LUN,
1282                                    )),
1283                            )
1284                            .build(),
1285                    ),
1286                BootDeviceType::ScsiViaNvme => self
1287                    .add_vmbus_storage_controller(
1288                        &PETRI_NVME_BOOT_VTL2_CONTROLLER,
1289                        Vtl::Vtl2,
1290                        VmbusStorageType::Nvme,
1291                    )
1292                    .add_vmbus_drive(
1293                        boot_drive,
1294                        &PETRI_NVME_BOOT_VTL2_CONTROLLER,
1295                        Some(PETRI_NVME_BOOT_NSID),
1296                    )
1297                    .add_vtl2_storage_controller(
1298                        Vtl2StorageControllerBuilder::new(ControllerType::Scsi)
1299                            .with_instance_id(PETRI_SCSI_VTL0_VIA_VTL2_CONTROLLER)
1300                            .add_lun(
1301                                Vtl2LunBuilder::disk()
1302                                    .with_location(PETRI_SCSI_BOOT_LUN)
1303                                    .with_physical_device(Vtl2StorageBackingDeviceBuilder::new(
1304                                        ControllerType::Nvme,
1305                                        PETRI_NVME_BOOT_VTL2_CONTROLLER,
1306                                        PETRI_NVME_BOOT_NSID,
1307                                    )),
1308                            )
1309                            .build(),
1310                    ),
1311                BootDeviceType::Nvme => self
1312                    .add_vmbus_storage_controller(
1313                        &PETRI_NVME_BOOT_VTL0_CONTROLLER,
1314                        Vtl::Vtl0,
1315                        VmbusStorageType::Nvme,
1316                    )
1317                    .add_vmbus_drive(
1318                        boot_drive,
1319                        &PETRI_NVME_BOOT_VTL0_CONTROLLER,
1320                        Some(PETRI_NVME_BOOT_NSID),
1321                    ),
1322                BootDeviceType::NvmeViaScsi => todo!(),
1323                BootDeviceType::NvmeViaNvme => todo!(),
1324                BootDeviceType::PcieNvme => {
1325                    let port_name = self
1326                        .pcie_boot_port
1327                        .clone()
1328                        .unwrap_or_else(|| "s0rc0rp0".into());
1329                    self.config.pcie_nvme_drives.push(PcieNvmeDrive {
1330                        port_name,
1331                        nsid: 1,
1332                        drive: boot_drive,
1333                    });
1334                    self
1335                }
1336                BootDeviceType::PcieVirtioBlk => {
1337                    self.config.pcie_virtio_blk_drives.push(PcieVirtioBlkDrive {
1338                        port_name: self
1339                            .pcie_boot_port
1340                            .clone()
1341                            .unwrap_or_else(|| "s0rc0rp0".into()),
1342                        drive: boot_drive,
1343                    });
1344                    self
1345                }
1346            }
1347        } else {
1348            self
1349        };
1350        Ok(builder)
1351    }
1352
1353    /// Whether the VTL0 agent disk will actually be added.
1354    ///
1355    /// False when using pipette-as-init with no extra files (pipette is
1356    /// in the initrd, so the CIDATA disk isn't needed).
1357    fn has_agent_disk(&self) -> bool {
1358        if self.uses_pipette_as_init() {
1359            self.agent_image.as_ref().is_some_and(|i| i.has_extras())
1360        } else {
1361            self.agent_image.is_some()
1362        }
1363    }
1364
1365    /// Get properties about the vm for convenience
1366    pub fn properties(&self) -> PetriVmProperties {
1367        PetriVmProperties {
1368            is_openhcl: self.config.firmware.is_openhcl(),
1369            is_isolated: self.config.firmware.isolation().is_some(),
1370            is_pcat: self.config.firmware.is_pcat(),
1371            is_linux_direct: self.config.firmware.is_linux_direct(),
1372            using_vtl0_pipette: self.using_vtl0_pipette(),
1373            external_pipette: self.external_pipette,
1374            using_vpci: self.boot_device_type.requires_vpci_boot(),
1375            os_flavor: self.config.firmware.os_flavor(),
1376            minimal_mode: self.minimal_mode,
1377            uses_pipette_as_init: self.uses_pipette_as_init(),
1378            enable_serial: self.enable_serial,
1379            use_virtio_console: self.use_virtio_console,
1380            has_agent_disk: self.has_agent_disk(),
1381            use_virtio_vsock: self.use_virtio_vsock,
1382            #[cfg(target_os = "linux")]
1383            vhost_vsock_guest_cid: self.vhost_vsock_guest_cid,
1384            no_vmbus: self.no_vmbus,
1385            no_hv: self.no_hv,
1386        }
1387    }
1388
1389    /// Whether Petri will inject Pipette as PID 1 init in the initrd.
1390    ///
1391    /// True for non-OpenHCL Linux direct boot or an mshv base initrd when a
1392    /// Pipette binary is available. Caller-prepared mshv userspace is unchanged.
1393    fn uses_pipette_as_init(&self) -> bool {
1394        ((self.config.firmware.is_linux_direct() && !self.config.firmware.is_openhcl())
1395            || self
1396                .config
1397                .firmware
1398                .mshv_boot()
1399                .is_some_and(|boot| matches!(&boot.initrd, crate::mshv_boot::MshvInitrd::Base(_))))
1400            && self.pipette_binary.is_some()
1401    }
1402
1403    /// Whether this VM is using pipette in VTL0
1404    pub fn using_vtl0_pipette(&self) -> bool {
1405        self.external_pipette
1406            || self.uses_pipette_as_init()
1407            || self
1408                .agent_image
1409                .as_ref()
1410                .is_some_and(|x| x.contains_pipette())
1411    }
1412
1413    /// Build and run the VM, then wait for the VM to emit the expected boot
1414    /// event (if configured). Does not configure and start pipette. Should
1415    /// only be used for testing platforms that pipette does not support.
1416    pub async fn run_without_agent(self) -> anyhow::Result<PetriVm<T>> {
1417        self.run_core().await
1418    }
1419
1420    /// Build and run the VM, then wait for the VM to emit the expected boot
1421    /// event (if configured). Launches pipette and returns a client to it.
1422    pub async fn run(self) -> anyhow::Result<(PetriVm<T>, PipetteClient)> {
1423        assert!(self.using_vtl0_pipette());
1424
1425        let mut vm = self.add_nested_artifacts_to_agent_disk().run_core().await?;
1426        let client = vm.wait_for_agent().await?;
1427
1428        Ok((vm, client))
1429    }
1430
1431    async fn run_core(mut self) -> anyhow::Result<PetriVm<T>> {
1432        // Auto-prepare the initrd with pipette injected if needed.
1433        // This centralizes the injection logic so backends only ever
1434        // receive a prebuilt_initrd path.
1435        if self.uses_pipette_as_init() && self.resources.prebuilt_initrd.is_none() {
1436            self.resources.prebuilt_initrd = Some(self.prepare_initrd()?);
1437        }
1438        // mshv boot media consumes the prepared userspace.
1439        self = self.add_boot_disk()?.add_agent_disks()?;
1440
1441        tracing::debug!(builder = ?self);
1442
1443        let arch = self.config.arch;
1444        let expect_reset = self.expect_reset();
1445        let properties = self.properties();
1446        let guest_shares = self.config.guest_shares.clone();
1447        let name = self.config.name.clone();
1448
1449        let (mut runtime, config) = self
1450            .backend
1451            .run(
1452                self.config,
1453                self.modify_vmm_config,
1454                &self.resources,
1455                &properties,
1456            )
1457            .await?;
1458        let openhcl_diag_handler = runtime.openhcl_diag();
1459        let watchdog_tasks = Self::start_watchdog_tasks(
1460            &self.resources,
1461            &mut runtime,
1462            self.enable_screenshots,
1463            self.watchdog_timeout,
1464        )?;
1465
1466        let mut vm = PetriVm {
1467            runtime: PetriVmRuntimeGuard {
1468                runtime: Some(runtime),
1469                driver: self.resources.driver.clone(),
1470                log_source: self.resources.log_source.clone(),
1471                capture_inspect_on_drop: self.capture_inspect_on_failure,
1472            },
1473            resources: self.resources,
1474            watchdog_tasks,
1475            openhcl_diag_handler,
1476
1477            arch,
1478            guest_quirks: self.guest_quirks,
1479            vmm_quirks: self.vmm_quirks,
1480            expected_boot_event: self.expected_boot_event,
1481
1482            config,
1483            properties,
1484
1485            nested_test: self.nested_test,
1486            guest_shares,
1487            name,
1488        };
1489
1490        if expect_reset {
1491            vm.wait_for_reset_core().await?;
1492        }
1493
1494        vm.wait_for_expected_boot_event().await?;
1495
1496        Ok(vm)
1497    }
1498
1499    fn expect_reset(&self) -> bool {
1500        self.override_expect_reset
1501            || matches!(
1502                (
1503                    self.guest_quirks.initial_reboot,
1504                    self.expected_boot_event,
1505                    &self.config.firmware,
1506                    &self.config.tpm,
1507                ),
1508                (
1509                    Some(InitialRebootCondition::Always),
1510                    Some(FirmwareEvent::BootSuccess | FirmwareEvent::BootAttempt),
1511                    _,
1512                    _,
1513                ) | (
1514                    Some(InitialRebootCondition::WithTpm),
1515                    Some(FirmwareEvent::BootSuccess | FirmwareEvent::BootAttempt),
1516                    _,
1517                    Some(_),
1518                )
1519            )
1520    }
1521
1522    fn start_watchdog_timer(
1523        driver: &DefaultDriver,
1524        watchdog_timeout: Option<Duration>,
1525    ) -> Option<Task<()>> {
1526        watchdog_timeout.map(|timeout| {
1527            // Unwind out of the task pool so Petri records a test failure.
1528            let timer_driver = driver.clone();
1529            driver.spawn("timer-watchdog", async move {
1530                PolledTimer::new(&timer_driver).sleep(timeout).await;
1531                tracing::error!(?timeout, "Test timeout reached, aborting.");
1532                panic!("Test timed out");
1533            })
1534        })
1535    }
1536
1537    fn start_watchdog_tasks(
1538        resources: &PetriVmResources,
1539        runtime: &mut T::VmRuntime,
1540        enable_screenshots: bool,
1541        watchdog_timeout: Option<Duration>,
1542    ) -> anyhow::Result<Vec<Task<()>>> {
1543        let mut tasks = Vec::new();
1544
1545        tasks.extend(Self::start_watchdog_timer(
1546            &resources.driver,
1547            watchdog_timeout,
1548        ));
1549
1550        if enable_screenshots {
1551            if let Some(mut framebuffer_access) = runtime.take_framebuffer_access() {
1552                let mut timer = PolledTimer::new(&resources.driver);
1553                let log_source = resources.log_source.clone();
1554
1555                tasks.push(
1556                    resources
1557                        .driver
1558                        .spawn("petri-watchdog-screenshot", async move {
1559                            let mut image = Vec::new();
1560                            let mut last_image = Vec::new();
1561                            loop {
1562                                timer.sleep(Duration::from_secs(2)).await;
1563                                tracing::trace!("Taking screenshot.");
1564
1565                                let VmScreenshotMeta {
1566                                    color,
1567                                    width,
1568                                    height,
1569                                } = match framebuffer_access.screenshot(&mut image).await {
1570                                    Ok(Some(meta)) => meta,
1571                                    Ok(None) => {
1572                                        tracing::debug!("VM off, skipping screenshot.");
1573                                        continue;
1574                                    }
1575                                    Err(e) => {
1576                                        tracing::error!(?e, "Failed to take screenshot");
1577                                        continue;
1578                                    }
1579                                };
1580
1581                                if image == last_image {
1582                                    tracing::debug!(
1583                                        "No change in framebuffer, skipping screenshot."
1584                                    );
1585                                    continue;
1586                                }
1587
1588                                let r = log_source.create_attachment("screenshot.png").and_then(
1589                                    |mut f| {
1590                                        image::write_buffer_with_format(
1591                                            &mut f,
1592                                            &image,
1593                                            width.into(),
1594                                            height.into(),
1595                                            color,
1596                                            image::ImageFormat::Png,
1597                                        )
1598                                        .map_err(Into::into)
1599                                    },
1600                                );
1601
1602                                if let Err(e) = r {
1603                                    tracing::error!(?e, "Failed to save screenshot");
1604                                } else {
1605                                    tracing::info!("Screenshot saved.");
1606                                }
1607
1608                                std::mem::swap(&mut image, &mut last_image);
1609                            }
1610                        }),
1611                );
1612            }
1613        }
1614
1615        Ok(tasks)
1616    }
1617
1618    /// Configure the test to expect a boot failure from the VM.
1619    /// Useful for negative tests.
1620    pub fn with_expect_boot_failure(mut self) -> Self {
1621        self.expected_boot_event = Some(FirmwareEvent::BootFailed);
1622        self
1623    }
1624
1625    /// Configure the test to not expect any boot event.
1626    /// Useful for tests that do not boot a VTL0 guest.
1627    pub fn with_expect_no_boot_event(mut self) -> Self {
1628        self.expected_boot_event = None;
1629        self
1630    }
1631
1632    /// Allow the VM to reset once at the beginning of the test. Should only be
1633    /// used if you are using a special VM configuration that causes the guest
1634    /// to reboot when it usually wouldn't.
1635    pub fn with_expect_reset(mut self) -> Self {
1636        self.override_expect_reset = true;
1637        self
1638    }
1639
1640    /// Set the VM to enable secure boot and inject the templates per OS flavor.
1641    pub fn with_secure_boot(mut self) -> Self {
1642        self.config
1643            .firmware
1644            .uefi_config_mut()
1645            .expect("Secure boot is only supported for UEFI firmware.")
1646            .secure_boot_enabled = true;
1647
1648        match self.os_flavor() {
1649            OsFlavor::Windows => self.with_windows_secure_boot_template(),
1650            OsFlavor::Linux => self.with_uefi_ca_secure_boot_template(),
1651            _ => panic!(
1652                "Secure boot unsupported for OS flavor {:?}",
1653                self.os_flavor()
1654            ),
1655        }
1656    }
1657
1658    /// Inject Windows secure boot templates into the VM's UEFI.
1659    pub fn with_windows_secure_boot_template(mut self) -> Self {
1660        self.config
1661            .firmware
1662            .uefi_config_mut()
1663            .expect("Secure boot is only supported for UEFI firmware.")
1664            .secure_boot_template = Some(SecureBootTemplate::MicrosoftWindows);
1665        self
1666    }
1667
1668    /// Inject UEFI CA secure boot templates into the VM's UEFI.
1669    pub fn with_uefi_ca_secure_boot_template(mut self) -> Self {
1670        self.config
1671            .firmware
1672            .uefi_config_mut()
1673            .expect("Secure boot is only supported for UEFI firmware.")
1674            .secure_boot_template = Some(SecureBootTemplate::MicrosoftUefiCertificateAuthority);
1675        self
1676    }
1677
1678    /// Apply a custom UEFI variable delta encoded as JSON.
1679    pub fn with_custom_uefi_json(mut self, json: impl Into<Vec<u8>>) -> Self {
1680        self.config
1681            .firmware
1682            .uefi_config_mut()
1683            .expect("Custom UEFI variables are only supported for UEFI firmware.")
1684            .custom_uefi_json = Some(json.into());
1685        self
1686    }
1687
1688    /// Set the VM to use the specified processor topology.
1689    pub fn with_processor_topology(mut self, topology: ProcessorTopology) -> Self {
1690        self.config.proc_topology = topology;
1691        self
1692    }
1693
1694    /// Set the VM to use the specified memory config.
1695    pub fn with_memory(mut self, memory: MemoryConfig) -> Self {
1696        self.config.memory = memory;
1697        self
1698    }
1699
1700    /// Sets a custom OpenHCL IGVM VTL2 address type. This controls the behavior
1701    /// of where VTL2 is placed in address space, and also the total size of memory
1702    /// allocated for VTL2. VTL2 start will fail if `address_type` is specified
1703    /// and leads to the loader allocating less memory than what is in the IGVM file.
1704    pub fn with_vtl2_base_address_type(mut self, address_type: Vtl2BaseAddressType) -> Self {
1705        self.config
1706            .firmware
1707            .openhcl_config_mut()
1708            .expect("OpenHCL firmware is required to set custom VTL2 address type.")
1709            .vtl2_base_address_type = Some(address_type);
1710        self
1711    }
1712
1713    /// Sets a custom OpenHCL IGVM file to use.
1714    pub fn with_custom_openhcl(mut self, artifact: ResolvedArtifact<impl IsOpenhclIgvm>) -> Self {
1715        match &mut self.config.firmware {
1716            Firmware::OpenhclLinuxDirect { igvm_firmware, .. }
1717            | Firmware::OpenhclPcat { igvm_firmware, .. }
1718            | Firmware::OpenhclUefi { igvm_firmware, .. } => {
1719                *igvm_firmware = IgvmFirmwareSource::File(artifact.erase());
1720            }
1721            Firmware::LinuxDirect { .. }
1722            | Firmware::IgvmLinuxDirect { .. }
1723            | Firmware::Uefi { .. }
1724            | Firmware::Pcat { .. } => {
1725                panic!("Custom OpenHCL is only supported for OpenHCL firmware.")
1726            }
1727        }
1728        self
1729    }
1730
1731    /// Load OpenHCL from VMGS, falling back to in-box firmware (Hyper-V only).
1732    pub fn with_openhcl_from_vmgs(mut self) -> Self {
1733        match &mut self.config.firmware {
1734            Firmware::OpenhclLinuxDirect { igvm_firmware, .. }
1735            | Firmware::OpenhclPcat { igvm_firmware, .. }
1736            | Firmware::OpenhclUefi { igvm_firmware, .. } => {
1737                *igvm_firmware = IgvmFirmwareSource::VmgsOrInBox;
1738            }
1739            Firmware::LinuxDirect { .. }
1740            | Firmware::IgvmLinuxDirect { .. }
1741            | Firmware::Uefi { .. }
1742            | Firmware::Pcat { .. } => {
1743                panic!("Loading OpenHCL from VMGS is only supported for OpenHCL firmware.")
1744            }
1745        }
1746        self
1747    }
1748
1749    /// Append additional command line arguments to pass to the paravisor.
1750    pub fn with_openhcl_command_line(mut self, additional_command_line: &str) -> Self {
1751        append_cmdline(
1752            &mut self
1753                .config
1754                .firmware
1755                .openhcl_config_mut()
1756                .expect("OpenHCL command line is only supported for OpenHCL firmware.")
1757                .custom_command_line,
1758            additional_command_line,
1759        );
1760        self
1761    }
1762
1763    /// Configure whether OpenHCL enables MANA keepalive at boot.
1764    pub fn with_mana_keepalive(mut self, enable: bool) -> Self {
1765        self.config
1766            .firmware
1767            .openhcl_config_mut()
1768            .expect("MANA keepalive is only supported for OpenHCL firmware.")
1769            .enable_mana_keepalive = enable;
1770        self
1771    }
1772
1773    /// Enable confidential filtering, even if the VM is not confidential.
1774    pub fn with_confidential_filtering(self) -> Self {
1775        if !self.config.firmware.is_openhcl() {
1776            panic!("Confidential filtering is only supported for OpenHCL");
1777        }
1778        self.with_openhcl_command_line(&format!(
1779            "{}=1 {}=0",
1780            underhill_confidentiality::OPENHCL_CONFIDENTIAL_ENV_VAR_NAME,
1781            underhill_confidentiality::OPENHCL_CONFIDENTIAL_DEBUG_ENV_VAR_NAME
1782        ))
1783    }
1784
1785    /// Sets the command line parameters passed to OpenHCL related to logging.
1786    pub fn with_openhcl_log_levels(mut self, levels: OpenvmmLogConfig) -> Self {
1787        self.config
1788            .firmware
1789            .openhcl_config_mut()
1790            .expect("OpenHCL firmware is required to set custom OpenHCL log levels.")
1791            .log_levels = levels;
1792        self
1793    }
1794
1795    /// Sets the log levels for the host OpenVMM process.
1796    /// DEVNOTE: In the future, this could be generalized for both HyperV and OpenVMM.
1797    /// For now, this is only implemented for OpenVMM.
1798    pub fn with_host_log_levels(mut self, levels: OpenvmmLogConfig) -> Self {
1799        if let OpenvmmLogConfig::Custom(ref custom_levels) = levels {
1800            for key in custom_levels.keys() {
1801                if !["OPENVMM_LOG", "OPENVMM_SHOW_SPANS"].contains(&key.as_str()) {
1802                    panic!("Unsupported OpenVMM log level key: {}", key);
1803                }
1804            }
1805        }
1806
1807        self.config.host_log_levels = Some(levels.clone());
1808        self
1809    }
1810
1811    /// Adds a file to the VM's pipette agent image.
1812    pub fn with_agent_file(mut self, name: &str, file_path: impl AsRef<Path>) -> Self {
1813        self.agent_image
1814            .as_mut()
1815            .expect("no guest pipette")
1816            .add_file(name, file_path);
1817        self
1818    }
1819
1820    /// Adds a file to the paravisor's pipette agent image.
1821    pub fn with_openhcl_agent_file(mut self, name: &str, file_path: impl AsRef<Path>) -> Self {
1822        self.openhcl_agent_image
1823            .as_mut()
1824            .expect("no openhcl pipette")
1825            .add_file(name, file_path);
1826        self
1827    }
1828
1829    /// Sets whether UEFI frontpage is enabled.
1830    pub fn with_uefi_frontpage(mut self, enable: bool) -> Self {
1831        self.config
1832            .firmware
1833            .uefi_config_mut()
1834            .expect("UEFI frontpage is only supported for UEFI firmware.")
1835            .disable_frontpage = !enable;
1836        self
1837    }
1838
1839    /// Sets the UEFI diagnostics log level filter.
1840    ///
1841    /// By default only ERROR and WARN level entries are forwarded to the
1842    /// host tracing infrastructure. Use this to also surface INFO (or all)
1843    /// entries when a test needs to observe them.
1844    pub fn with_efi_diagnostics_log_level(mut self, level: EfiDiagnosticsLogLevel) -> Self {
1845        self.config
1846            .firmware
1847            .uefi_config_mut()
1848            .expect("EFI diagnostics log level is only supported for UEFI firmware.")
1849            .efi_diagnostics_log_level = level;
1850        self
1851    }
1852
1853    /// Sets the per-period rate-limit override for UEFI diagnostics emission.
1854    ///
1855    /// - Not called: use the built-in defaults.
1856    /// - `0`: disable rate limiting entirely (emit every entry).
1857    /// - `n > 0`: use `n` as the per-period limit.
1858    pub fn with_efi_diagnostics_rate_limit(mut self, limit: u32) -> Self {
1859        self.config
1860            .firmware
1861            .uefi_config_mut()
1862            .expect("EFI diagnostics rate limit is only supported for UEFI firmware.")
1863            .efi_diagnostics_rate_limit = Some(limit);
1864        self
1865    }
1866
1867    /// Sets whether UEFI should always attempt a default boot.
1868    pub fn with_default_boot_always_attempt(mut self, enable: bool) -> Self {
1869        self.config
1870            .firmware
1871            .uefi_config_mut()
1872            .expect("Default boot always attempt is only supported for UEFI firmware.")
1873            .default_boot_always_attempt = enable;
1874        self
1875    }
1876
1877    /// Force UEFI to bounce-buffer all DMA traffic.
1878    pub fn with_uefi_force_dma_bounce(mut self, enable: bool) -> Self {
1879        self.config
1880            .firmware
1881            .uefi_config_mut()
1882            .expect("force DMA bounce is only supported for UEFI firmware.")
1883            .force_dma_bounce = enable;
1884        self
1885    }
1886
1887    /// Run the VM with Enable VMBus relay enabled
1888    pub fn with_vmbus_redirect(mut self, enable: bool) -> Self {
1889        self.config
1890            .firmware
1891            .openhcl_config_mut()
1892            .expect("VMBus redirection is only supported for OpenHCL firmware.")
1893            .vmbus_redirect = enable;
1894        self
1895    }
1896
1897    /// Enable guest hibernation support.
1898    ///
1899    /// Applies to any firmware type: for OpenHCL this sets the DPS
1900    /// `enable_hibernation` flag; for OpenVMM UEFI/PCAT firmware it enables the
1901    /// firmware's hibernation support.
1902    pub fn with_hibernation_enabled(mut self, enable: bool) -> Self {
1903        self.config.hibernation_enabled = enable;
1904        self
1905    }
1906
1907    /// Enable the IPMI KCS interface for an OpenHCL UEFI VM.
1908    pub fn with_ipmi(mut self, enable: bool) -> Self {
1909        self.config.ipmi_enabled = enable;
1910        self
1911    }
1912
1913    /// Specify the guest state lifetime for the VM
1914    pub fn with_guest_state_lifetime(
1915        mut self,
1916        guest_state_lifetime: PetriGuestStateLifetime,
1917    ) -> Self {
1918        let disk = match self.config.vmgs {
1919            PetriVmgsResource::Disk(disk)
1920            | PetriVmgsResource::ReprovisionOnFailure(disk)
1921            | PetriVmgsResource::ReprovisionSingle(disk) => disk,
1922            PetriVmgsResource::Ephemeral => PetriVmgsDisk::default(),
1923        };
1924        self.config.vmgs = match guest_state_lifetime {
1925            PetriGuestStateLifetime::Disk => PetriVmgsResource::Disk(disk),
1926            PetriGuestStateLifetime::ReprovisionOnFailure => {
1927                PetriVmgsResource::ReprovisionOnFailure(disk)
1928            }
1929            PetriGuestStateLifetime::ReprovisionSingle => {
1930                PetriVmgsResource::ReprovisionSingle(disk)
1931            }
1932            PetriGuestStateLifetime::Ephemeral => {
1933                if !matches!(disk.disk, Disk::Memory(_)) {
1934                    panic!("attempted to use ephemeral guest state after specifying backing vmgs")
1935                }
1936                PetriVmgsResource::Ephemeral
1937            }
1938        };
1939        self
1940    }
1941
1942    /// Specify the guest state encryption policy for the VM
1943    pub fn with_guest_state_encryption(mut self, policy: GuestStateEncryptionPolicy) -> Self {
1944        match &mut self.config.vmgs {
1945            PetriVmgsResource::Disk(vmgs)
1946            | PetriVmgsResource::ReprovisionOnFailure(vmgs)
1947            | PetriVmgsResource::ReprovisionSingle(vmgs) => {
1948                vmgs.encryption_policy = policy;
1949            }
1950            PetriVmgsResource::Ephemeral => {
1951                panic!("attempted to encrypt ephemeral guest state")
1952            }
1953        }
1954        self
1955    }
1956
1957    /// Use the specified backing VMGS file
1958    pub fn with_initial_vmgs(self, disk: ResolvedArtifact<impl IsTestVmgs>) -> Self {
1959        self.with_backing_vmgs(Disk::Differencing(DiskPath::Local(disk.into())))
1960    }
1961
1962    /// Use the specified backing VMGS file
1963    pub fn with_persistent_vmgs(self, disk: impl AsRef<Path>) -> Self {
1964        self.with_backing_vmgs(Disk::Persistent(disk.as_ref().to_path_buf()))
1965    }
1966
1967    fn with_backing_vmgs(mut self, disk: Disk) -> Self {
1968        match &mut self.config.vmgs {
1969            PetriVmgsResource::Disk(vmgs)
1970            | PetriVmgsResource::ReprovisionOnFailure(vmgs)
1971            | PetriVmgsResource::ReprovisionSingle(vmgs) => {
1972                if !matches!(vmgs.disk, Disk::Memory(_)) {
1973                    panic!("already specified a backing vmgs file");
1974                }
1975                vmgs.disk = disk;
1976            }
1977            PetriVmgsResource::Ephemeral => {
1978                panic!("attempted to specify a backing vmgs with ephemeral guest state")
1979            }
1980        }
1981        self
1982    }
1983
1984    /// Set the boot device type for the VM.
1985    ///
1986    /// This overrides the default, which is determined by the firmware type.
1987    pub fn with_boot_device_type(mut self, boot: BootDeviceType) -> Self {
1988        self.boot_device_type = boot;
1989        self
1990    }
1991
1992    /// Override the PCIe root port used by [`BootDeviceType::PcieNvme`] or
1993    /// [`BootDeviceType::PcieVirtioBlk`].
1994    ///
1995    /// The named port must exist in the PCIe topology added via the backend's
1996    /// `with_pcie_root_topology`. Defaults to `s0rc0rp0`.
1997    pub fn with_pcie_boot_port(mut self, port_name: &str) -> Self {
1998        self.pcie_boot_port = Some(port_name.to_string());
1999        self
2000    }
2001
2002    /// Enable the TPM for the VM.
2003    pub fn with_tpm(mut self, enable: bool) -> Self {
2004        if enable {
2005            self.config.tpm.get_or_insert_default();
2006        } else {
2007            self.config.tpm = None;
2008        }
2009        self
2010    }
2011
2012    /// Enable or disable the TPM state persistence for the VM.
2013    pub fn with_tpm_state_persistence(mut self, tpm_state_persistence: bool) -> Self {
2014        self.config
2015            .tpm
2016            .as_mut()
2017            .expect("TPM persistence requires a TPM")
2018            .no_persistent_secrets = !tpm_state_persistence;
2019        self
2020    }
2021
2022    /// Set the hardware sealing policy for the VM's TPM.
2023    pub fn with_hardware_sealing_policy(mut self, policy: PetriHardwareSealingPolicy) -> Self {
2024        self.config
2025            .tpm
2026            .as_mut()
2027            .expect("hardware sealing policy requires a TPM")
2028            .hardware_sealing_policy = policy;
2029        self
2030    }
2031
2032    /// Select which TPM reference implementation version the VM's TPM runs.
2033    pub fn with_tpm_version(mut self, version: PetriTpmVersion) -> Self {
2034        self.config
2035            .tpm
2036            .as_mut()
2037            .expect("TPM version requires a TPM")
2038            .version = version;
2039        self
2040    }
2041
2042    /// Add custom VTL 2 settings.
2043    // TODO: At some point we want to replace uses of this with nicer with_disk,
2044    // with_nic, etc. methods.
2045    pub fn with_custom_vtl2_settings(
2046        mut self,
2047        f: impl FnOnce(&mut Vtl2Settings) + 'static + Send + Sync,
2048    ) -> Self {
2049        f(self
2050            .config
2051            .firmware
2052            .vtl2_settings()
2053            .expect("Custom VTL 2 settings are only supported with OpenHCL"));
2054        self
2055    }
2056
2057    /// Add a storage controller to VTL2
2058    pub fn add_vtl2_storage_controller(self, controller: StorageController) -> Self {
2059        self.with_custom_vtl2_settings(move |v| {
2060            v.dynamic
2061                .as_mut()
2062                .unwrap()
2063                .storage_controllers
2064                .push(controller)
2065        })
2066    }
2067
2068    /// Add an additional SCSI controller to the VM.
2069    pub fn add_vmbus_storage_controller(
2070        mut self,
2071        id: &Guid,
2072        target_vtl: Vtl,
2073        controller_type: VmbusStorageType,
2074    ) -> Self {
2075        if self
2076            .config
2077            .vmbus_storage_controllers
2078            .insert(
2079                *id,
2080                VmbusStorageController::new(target_vtl, controller_type),
2081            )
2082            .is_some()
2083        {
2084            panic!("storage controller {id} already existed");
2085        }
2086        self
2087    }
2088
2089    /// Add a VMBus disk drive to the VM
2090    pub fn add_vmbus_drive(
2091        mut self,
2092        drive: Drive,
2093        controller_id: &Guid,
2094        controller_location: Option<u32>,
2095    ) -> Self {
2096        let controller = self
2097            .config
2098            .vmbus_storage_controllers
2099            .get_mut(controller_id)
2100            .unwrap_or_else(|| panic!("storage controller {controller_id} does not exist"));
2101
2102        _ = controller.set_drive(controller_location, drive, false);
2103
2104        self
2105    }
2106
2107    /// Add a VMBus disk drive to the VM
2108    pub fn add_ide_drive(
2109        mut self,
2110        drive: Drive,
2111        controller_number: u32,
2112        controller_location: u8,
2113    ) -> Self {
2114        self.config
2115            .firmware
2116            .ide_controllers_mut()
2117            .expect("Host IDE requires PCAT with no HCL")[controller_number as usize]
2118            [controller_location as usize] = Some(drive);
2119
2120        self
2121    }
2122
2123    /// Add a physical NVMe device to the VM
2124    pub fn add_physical_nvme_device(mut self, vsid: Guid, device: PhysicalNvmeDevice) -> Self {
2125        if self
2126            .config
2127            .physical_nvme_devices
2128            .insert(vsid, device)
2129            .is_some()
2130        {
2131            panic!("physical NVMe device {vsid} already existed");
2132        }
2133        self
2134    }
2135
2136    /// Get VM's guest OS flavor
2137    pub fn os_flavor(&self) -> OsFlavor {
2138        self.config.firmware.os_flavor()
2139    }
2140
2141    /// Get whether the VM will use OpenHCL
2142    pub fn is_openhcl(&self) -> bool {
2143        self.config.firmware.is_openhcl()
2144    }
2145
2146    /// Get the isolation type of the VM
2147    pub fn isolation(&self) -> Option<IsolationType> {
2148        self.config.firmware.isolation()
2149    }
2150
2151    /// Get the machine architecture
2152    pub fn arch(&self) -> MachineArch {
2153        self.config.arch
2154    }
2155
2156    /// Get the log source for creating additional log files.
2157    pub fn log_source(&self) -> &PetriLogSource {
2158        &self.resources.log_source
2159    }
2160
2161    /// Get the default OpenHCL servicing flags for this config
2162    pub fn default_servicing_flags(&self) -> OpenHclServicingFlags {
2163        T::default_servicing_flags()
2164    }
2165
2166    /// Apply a backend-specific modification in registration order.
2167    /// May be called multiple times, including around platform presets.
2168    pub fn modify_backend(
2169        mut self,
2170        f: impl FnOnce(T::VmmConfig) -> T::VmmConfig + 'static + Send,
2171    ) -> Self {
2172        let previous = self.modify_vmm_config.take();
2173        self.modify_vmm_config = Some(ModifyFn(Box::new(move |config| {
2174            let config = match previous {
2175                Some(previous) => previous.0(config),
2176                None => config,
2177            };
2178            f(config)
2179        })));
2180        self
2181    }
2182
2183    fn add_nested_artifacts_to_agent_disk(mut self) -> Self {
2184        let Some(nested_test) = self.nested_test.as_ref() else {
2185            return self;
2186        };
2187
2188        // if we can just the files directly, make sure the nested test is under
2189        // the test content dir.
2190        if T::supports_file_sharing(&self.config.firmware) {
2191            self.config.guest_shares.insert(
2192                NESTED_CONTENT_TAG.into(),
2193                GuestShare {
2194                    host_path: PathBuf::from(
2195                        std::env::var(VMM_TESTS_CONTENT_DIR).expect("test content dir not set"),
2196                    ),
2197                    guest_path: self.agent_disk_path(&[NESTED_TEST_CONTENT_DIR.into()]),
2198                },
2199            );
2200            self.config.guest_shares.insert(
2201                NESTED_IMAGES_TAG.into(),
2202                GuestShare {
2203                    host_path: PathBuf::from(
2204                        std::env::var(VMM_TEST_IMAGES).expect("test images dir not set"),
2205                    ),
2206                    guest_path: self.agent_disk_path(&[NESTED_IMAGES_DIR.into()]),
2207                },
2208            );
2209
2210            return self;
2211        }
2212
2213        let mut extras = Vec::new();
2214
2215        let path_builder = FatFsPathBuilder(self.os_flavor());
2216
2217        extras.push((NESTED_TEST_CONTENT_DIR.to_string(), ImageEntry::Dir));
2218        extras.push((
2219            path_builder
2220                .build_guest_path(&[NESTED_TEST_CONTENT_DIR.into(), NESTED_RESULTS_DIR.into()]),
2221            ImageEntry::Dir,
2222        ));
2223        extras.push((
2224            path_builder.build_guest_path(&[NESTED_IMAGES_DIR.into()]),
2225            ImageEntry::Dir,
2226        ));
2227        extras.push((
2228            path_builder.build_guest_path(&[
2229                NESTED_TEST_CONTENT_DIR.into(),
2230                path_builder.binary_with_extension(NESTED_TEST_BINARY),
2231            ]),
2232            ImageEntry::File(nested_test.test_binary.to_path_buf()),
2233        ));
2234
2235        for (handle, src) in &nested_test.artifacts {
2236            let relative_path = path_builder.convert_guest_path(&handle.relative_path());
2237            let dest = if handle.is_image() {
2238                path_builder.build_guest_path(&[NESTED_IMAGES_DIR.into(), relative_path])
2239            } else {
2240                path_builder.build_guest_path(&[NESTED_TEST_CONTENT_DIR.into(), relative_path])
2241            };
2242
2243            for parent in path_builder.parents(&dest) {
2244                if !extras.iter().any(|(p, _)| p == parent) {
2245                    extras.push((parent.to_string(), ImageEntry::Dir))
2246                }
2247            }
2248
2249            extras.push((dest, ImageEntry::File(src.clone())));
2250        }
2251
2252        let image = self.agent_image.as_mut().expect("no guest pipette");
2253        image.add_extras(extras);
2254        // Allocate an extra 150 MB for logs and crash dumps
2255        image.allocate_free_space(150 * 1024 * 1024);
2256
2257        self
2258    }
2259
2260    /// Request nested virtualization support from the host hypervisor.
2261    pub fn with_nested_virt(mut self) -> Self {
2262        self.config.nested_virt_enabled = true;
2263        self
2264    }
2265
2266    /// Use a non-standard kernel for Linux direct tests
2267    pub fn with_custom_linux_kernel(
2268        mut self,
2269        custom_kernel: ResolvedArtifact<impl IsLoadable>,
2270    ) -> Self {
2271        let Firmware::LinuxDirect { kernel, .. } = &mut self.config.firmware else {
2272            panic!("VM is not linux direct");
2273        };
2274        *kernel = custom_kernel.erase();
2275        self
2276    }
2277}
2278
2279impl<T: PetriVmmBackend> PetriVm<T> {
2280    /// Immediately tear down the VM.
2281    pub async fn teardown(mut self) -> anyhow::Result<()> {
2282        tracing::info!("Tearing down VM...");
2283        self.runtime.take_for_teardown().teardown().await?;
2284        Ok(())
2285    }
2286
2287    /// Wait for the VM to halt, returning the reason for the halt.
2288    pub async fn wait_for_halt(&mut self) -> anyhow::Result<PetriHaltReasonDetail> {
2289        tracing::info!("Waiting for VM to halt...");
2290        let halt_reason = self.runtime.wait_for_halt(false).await?;
2291        tracing::info!("VM halted: {halt_reason:?}. Cancelling watchdogs...");
2292        futures::future::join_all(self.watchdog_tasks.drain(..).map(|t| t.cancel())).await;
2293        Ok(halt_reason)
2294    }
2295
2296    /// Wait for the VM to cleanly shutdown.
2297    pub async fn wait_for_clean_shutdown(&mut self) -> anyhow::Result<()> {
2298        let halt_reason = self.wait_for_halt().await?;
2299        if halt_reason.reason != PetriHaltReason::PowerOff {
2300            anyhow::bail!("Expected PowerOff, got {halt_reason:?}");
2301        }
2302        tracing::info!("VM was cleanly powered off and torn down.");
2303        Ok(())
2304    }
2305
2306    /// Wait for the VM to halt, returning the reason for the halt,
2307    /// and tear down the VM.
2308    pub async fn wait_for_teardown(mut self) -> anyhow::Result<PetriHaltReasonDetail> {
2309        let halt_reason = self.wait_for_halt().await?;
2310        self.teardown().await?;
2311        Ok(halt_reason)
2312    }
2313
2314    /// Wait for the VM to cleanly shutdown and tear down the VM.
2315    pub async fn wait_for_clean_teardown(mut self) -> anyhow::Result<()> {
2316        self.wait_for_clean_shutdown().await?;
2317        self.teardown().await
2318    }
2319
2320    /// Wait for the VM to reset. Does not wait for pipette.
2321    pub async fn wait_for_reset_no_agent(&mut self) -> anyhow::Result<()> {
2322        self.wait_for_reset_core().await?;
2323        self.wait_for_expected_boot_event().await?;
2324        Ok(())
2325    }
2326
2327    /// Wait for the VM to reset and pipette to connect.
2328    pub async fn wait_for_reset(&mut self) -> anyhow::Result<PipetteClient> {
2329        self.wait_for_reset_no_agent().await?;
2330        self.wait_for_agent().await
2331    }
2332
2333    async fn wait_for_reset_core(&mut self) -> anyhow::Result<()> {
2334        tracing::info!("Waiting for VM to reset...");
2335        let halt_reason = self.runtime.wait_for_halt(true).await?;
2336        if halt_reason.reason != PetriHaltReason::Reset {
2337            anyhow::bail!("Expected reset, got {halt_reason:?}");
2338        }
2339        tracing::info!("VM reset.");
2340        Ok(())
2341    }
2342
2343    /// Invoke Inspect on the running OpenHCL instance.
2344    ///
2345    /// IMPORTANT: As mentioned in the Guide, inspect output is *not* guaranteed
2346    /// to be stable. Use this to test that components in OpenHCL are working as
2347    /// you would expect. But, if you are adding a test simply to verify that
2348    /// the inspect output as some other tool depends on it, then that is
2349    /// incorrect.
2350    ///
2351    /// - `timeout` is enforced on the client side
2352    /// - `path` and `depth` are passed to the [`inspect::Inspect`] machinery.
2353    pub async fn inspect_openhcl(
2354        &self,
2355        path: impl Into<String>,
2356        depth: Option<usize>,
2357        timeout: Option<Duration>,
2358    ) -> anyhow::Result<inspect::Node> {
2359        self.openhcl_diag()?
2360            .inspect(path.into().as_str(), depth, timeout)
2361            .await
2362    }
2363
2364    /// Invoke Update (Inspect protocol) on the running OpenHCL instance.
2365    ///
2366    /// IMPORTANT: As mentioned in the Guide, inspect output is *not* guaranteed
2367    /// to be stable. Use this to test that components in OpenHCL are working as
2368    /// you would expect. But, if you are adding a test simply to verify that
2369    /// the inspect output as some other tool depends on it, then that is
2370    /// incorrect.
2371    ///
2372    /// - `path` and `value` are passed to the [`inspect::Inspect`] machinery.
2373    pub async fn inspect_update_openhcl(
2374        &self,
2375        path: impl Into<String>,
2376        value: impl Into<String>,
2377    ) -> anyhow::Result<inspect::Value> {
2378        self.openhcl_diag()?
2379            .inspect_update(path.into(), value.into())
2380            .await
2381    }
2382
2383    /// Test that we are able to inspect OpenHCL.
2384    pub async fn test_inspect_openhcl(&mut self) -> anyhow::Result<()> {
2385        self.inspect_openhcl("", None, None).await.map(|_| ())
2386    }
2387
2388    /// Dump OpenHCL's saved state through the diagnostic interface.
2389    ///
2390    /// A running VM is briefly paused to capture its state, then resumed.
2391    pub async fn dump_openhcl_saved_state(&self) -> anyhow::Result<Vec<u8>> {
2392        self.openhcl_diag()?.dump_saved_state().await
2393    }
2394
2395    /// Invoke Inspect on the running VMM process itself (e.g. OpenVMM),
2396    /// returning the inspect tree rooted at `path` (pass `""` for the whole
2397    /// tree).
2398    ///
2399    /// Only backends that expose an inspect interface (currently OpenVMM)
2400    /// support this; other backends return an error.
2401    ///
2402    /// IMPORTANT: As mentioned in the Guide, inspect output is *not* guaranteed
2403    /// to be stable. Use this to verify that components are working as you
2404    /// expect, not to assert on output that some other tool depends on.
2405    pub async fn inspect_vmm(&self, path: &str) -> anyhow::Result<inspect::Node> {
2406        use anyhow::Context;
2407
2408        let inspector = self
2409            .runtime
2410            .inspector()
2411            .context("this VMM backend does not support inspect")?;
2412        inspector.inspect(path).await
2413    }
2414
2415    /// Wait for VTL 2 to report that it is ready to respond to commands.
2416    /// Will fail if the VM is not running OpenHCL.
2417    ///
2418    /// This should only be necessary if you're doing something manual. All
2419    /// Petri-provided methods will wait for VTL 2 to be ready automatically.
2420    pub async fn wait_for_vtl2_ready(&mut self) -> anyhow::Result<()> {
2421        self.openhcl_diag()?.wait_for_vtl2().await
2422    }
2423
2424    /// Get the kmsg stream from OpenHCL.
2425    pub async fn kmsg(&self) -> anyhow::Result<diag_client::kmsg_stream::KmsgStream> {
2426        self.openhcl_diag()?.kmsg().await
2427    }
2428
2429    /// Gets a live core dump of the OpenHCL process specified by 'name' and
2430    /// writes it to 'path'
2431    pub async fn openhcl_core_dump(&self, name: &str, path: &Path) -> anyhow::Result<()> {
2432        self.openhcl_diag()?.core_dump(name, path).await
2433    }
2434
2435    /// Crashes the specified openhcl process
2436    pub async fn openhcl_crash(&self, name: &str) -> anyhow::Result<()> {
2437        self.openhcl_diag()?.crash(name).await
2438    }
2439
2440    /// Wait for a connection from a pipette agent running in the guest.
2441    /// Useful if you've rebooted the vm or are otherwise expecting a fresh connection.
2442    async fn wait_for_agent(&mut self) -> anyhow::Result<PipetteClient> {
2443        // As a workaround for #2470 (where the guest crashes when the pipette
2444        // connection timeout expires due to a vmbus bug), wait for the shutdown
2445        // IC to come online first so that we probably won't time out when
2446        // connecting to the agent.
2447        // TODO: remove this once the bug is fixed, since it shouldn't be
2448        // necessary and a guest could in theory support pipette and not the IC
2449        //
2450        // This is a no-op when the shutdown IC is not configured (e.g.,
2451        // no VMBus or minimal mode).
2452        self.runtime.wait_for_enlightened_shutdown_ready().await?;
2453        let client = self.runtime.wait_for_agent(false).await?;
2454        self.mount_guest_shares(&client).await?;
2455        Ok(client)
2456    }
2457
2458    async fn mount_guest_shares(&self, client: &PipetteClient) -> anyhow::Result<()> {
2459        if !self.guest_shares.is_empty() {
2460            anyhow::ensure!(
2461                self.properties.os_flavor == OsFlavor::Linux,
2462                "directory sharing requires a Linux guest"
2463            );
2464            let mut shares = self.guest_shares.iter().collect::<Vec<_>>();
2465            // Mount parents first so they do not hide descendant shares.
2466            shares.sort_by_key(|(tag, share)| {
2467                (
2468                    share
2469                        .guest_path
2470                        .split('/')
2471                        .filter(|part| !part.is_empty() && *part != ".")
2472                        .count(),
2473                    *tag,
2474                )
2475            });
2476            for (tag, share) in shares {
2477                let shell = client.unix_shell();
2478                shell
2479                    .cmd("mkdir")
2480                    .args(["-p", &share.guest_path])
2481                    .run()
2482                    .await?;
2483                shell
2484                    .cmd("mount")
2485                    .args([
2486                        "-t",
2487                        "9p",
2488                        "-o",
2489                        "trans=virtio,version=9p2000.L",
2490                        tag,
2491                        &share.guest_path,
2492                    ])
2493                    .run()
2494                    .await
2495                    .with_context(|| format!("mounting guest share {tag}"))?;
2496            }
2497        }
2498        Ok(())
2499    }
2500
2501    /// Wait for a connection from a pipette agent running in VTL 2.
2502    /// Useful if you've reset VTL 2 or are otherwise expecting a fresh connection.
2503    /// Will fail if the VM is not running OpenHCL.
2504    pub async fn wait_for_vtl2_agent(&mut self) -> anyhow::Result<PipetteClient> {
2505        // VTL 2's pipette doesn't auto launch, only launch it on demand
2506        self.launch_vtl2_pipette().await?;
2507        self.runtime.wait_for_agent(true).await
2508    }
2509
2510    /// Waits for an event emitted by the firmware about its boot status, and
2511    /// verifies that it is the expected success value.
2512    ///
2513    /// * Linux Direct guests do not emit a boot event, so this method immediately returns Ok.
2514    /// * PCAT guests may not emit an event depending on the PCAT version, this
2515    ///   method is best effort for them.
2516    async fn wait_for_expected_boot_event(&mut self) -> anyhow::Result<()> {
2517        if let Some(expected_event) = self.expected_boot_event {
2518            let event = self.wait_for_boot_event().await?;
2519
2520            anyhow::ensure!(
2521                event == expected_event,
2522                "Did not receive expected boot event"
2523            );
2524        } else {
2525            tracing::warn!("Boot event not emitted for configured firmware or manually ignored.");
2526        }
2527
2528        Ok(())
2529    }
2530
2531    /// Waits for an event emitted by the firmware about its boot status, and
2532    /// returns that status.
2533    async fn wait_for_boot_event(&mut self) -> anyhow::Result<FirmwareEvent> {
2534        tracing::info!("Waiting for boot event...");
2535        let boot_event = loop {
2536            if let Some(event) = self
2537                .runtime
2538                .wait_for_boot_event(self.vmm_quirks.flaky_boot)
2539                .await?
2540            {
2541                break event;
2542            }
2543
2544            tracing::error!("Did not get boot event in required time, resetting...");
2545            if let Some(inspector) = self.runtime.inspector() {
2546                collect_inspect(
2547                    "vmm",
2548                    Box::pin(async move { inspector.inspect("").await }),
2549                    &self.resources.log_source,
2550                    "timeout",
2551                )
2552                .await;
2553            }
2554
2555            self.runtime.reset().await?;
2556        };
2557        tracing::info!("Got boot event: {boot_event:?}");
2558        Ok(boot_event)
2559    }
2560
2561    /// Wait for the Hyper-V shutdown IC to be ready and use it to instruct
2562    /// the guest to shutdown.
2563    pub async fn send_enlightened_shutdown(&mut self, kind: ShutdownKind) -> anyhow::Result<()> {
2564        tracing::info!("Waiting for enlightened shutdown to be ready");
2565        self.runtime.wait_for_enlightened_shutdown_ready().await?;
2566
2567        // all guests used in testing have been observed to intermittently
2568        // drop shutdown requests if they are sent too soon after the shutdown
2569        // ic comes online. give them a little extra time.
2570        // TODO: use a different method of determining whether the VM has booted
2571        // or debug and fix the shutdown IC.
2572        let mut wait_time = Duration::from_secs(10);
2573
2574        // some guests need even more time
2575        if let Some(duration) = self.guest_quirks.hyperv_shutdown_ic_sleep {
2576            wait_time += duration;
2577        }
2578
2579        tracing::info!(
2580            "Shutdown IC reported ready, waiting for an extra {}s",
2581            wait_time.as_secs()
2582        );
2583        PolledTimer::new(&self.resources.driver)
2584            .sleep(wait_time)
2585            .await;
2586
2587        tracing::info!("Sending enlightened shutdown command");
2588        self.runtime.send_enlightened_shutdown(kind).await
2589    }
2590
2591    /// Instruct the OpenHCL to restart the VTL2 paravisor. Will fail if the VM
2592    /// is not running OpenHCL. Will also fail if the VM is not running.
2593    pub async fn restart_openhcl(
2594        &mut self,
2595        new_openhcl: ResolvedArtifact<impl IsOpenhclIgvm>,
2596        flags: OpenHclServicingFlags,
2597    ) -> anyhow::Result<()> {
2598        self.runtime
2599            .restart_openhcl(&new_openhcl.erase(), flags)
2600            .await
2601    }
2602
2603    /// Update the command line parameter of the running VM that will apply on next boot.
2604    /// Will fail if the VM is not using IGVM load mode.
2605    pub async fn update_command_line(&mut self, command_line: &str) -> anyhow::Result<()> {
2606        self.runtime.update_command_line(command_line).await
2607    }
2608
2609    /// Hot-add a PCIe device to a named port at runtime.
2610    pub async fn add_pcie_device(
2611        &mut self,
2612        port_name: String,
2613        resource: vm_resource::Resource<vm_resource::kind::PciDeviceHandleKind>,
2614    ) -> anyhow::Result<()> {
2615        self.runtime.add_pcie_device(port_name, resource).await
2616    }
2617
2618    /// Hot-remove a PCIe device from a named port at runtime.
2619    pub async fn remove_pcie_device(&mut self, port_name: String) -> anyhow::Result<()> {
2620        self.runtime.remove_pcie_device(port_name).await
2621    }
2622
2623    /// Instruct the OpenHCL to save the state of the VTL2 paravisor. Will fail if the VM
2624    /// is not running OpenHCL. Will also fail if the VM is not running or if this is called twice in succession
2625    pub async fn save_openhcl(
2626        &mut self,
2627        new_openhcl: ResolvedArtifact<impl IsOpenhclIgvm>,
2628        flags: OpenHclServicingFlags,
2629    ) -> anyhow::Result<()> {
2630        self.runtime.save_openhcl(&new_openhcl.erase(), flags).await
2631    }
2632
2633    /// Instruct the OpenHCL to restore the state of the VTL2 paravisor. Will fail if the VM
2634    /// is not running OpenHCL. Will also fail if the VM is running or if this is called without prior save
2635    pub async fn restore_openhcl(&mut self) -> anyhow::Result<()> {
2636        self.runtime.restore_openhcl().await
2637    }
2638
2639    /// Get VM's guest OS flavor
2640    pub fn arch(&self) -> MachineArch {
2641        self.arch
2642    }
2643
2644    /// Get the inner runtime backend to make backend-specific calls
2645    pub fn backend(&mut self) -> &mut T::VmRuntime {
2646        &mut self.runtime
2647    }
2648
2649    async fn launch_vtl2_pipette(&self) -> anyhow::Result<()> {
2650        tracing::debug!("Launching VTL 2 pipette...");
2651
2652        // Start pipette through DiagClient
2653        let res = self
2654            .openhcl_diag()?
2655            .run_vtl2_command("sh", &["-c", "mkdir /cidata && mount LABEL=cidata /cidata"])
2656            .await?;
2657
2658        if !res.exit_status.success() {
2659            anyhow::bail!("Failed to mount VTL 2 pipette drive: {:?}", res);
2660        }
2661
2662        let res = self
2663            .openhcl_diag()?
2664            .run_detached_vtl2_command("sh", &["-c", "/cidata/pipette 2>&1 | logger &"])
2665            .await?;
2666
2667        if !res.success() {
2668            anyhow::bail!("Failed to spawn VTL 2 pipette: {:?}", res);
2669        }
2670
2671        Ok(())
2672    }
2673
2674    fn openhcl_diag(&self) -> anyhow::Result<&OpenHclDiagHandler> {
2675        if let Some(ohd) = self.openhcl_diag_handler.as_ref() {
2676            Ok(ohd)
2677        } else {
2678            anyhow::bail!("VM is not configured with OpenHCL")
2679        }
2680    }
2681
2682    /// Get the path to the VM's guest state file
2683    pub async fn get_guest_state_file(&self) -> anyhow::Result<Option<PathBuf>> {
2684        self.runtime.get_guest_state_file().await
2685    }
2686
2687    /// Modify OpenHCL VTL2 settings.
2688    pub async fn modify_vtl2_settings(
2689        &mut self,
2690        f: impl FnOnce(&mut Vtl2Settings),
2691    ) -> anyhow::Result<()> {
2692        if self.openhcl_diag_handler.is_none() {
2693            panic!("Custom VTL 2 settings are only supported with OpenHCL");
2694        }
2695        f(self
2696            .config
2697            .vtl2_settings
2698            .get_or_insert_with(default_vtl2_settings));
2699        self.runtime
2700            .set_vtl2_settings(self.config.vtl2_settings.as_ref().unwrap())
2701            .await
2702    }
2703
2704    /// Get the list of storage controllers added to this VM
2705    pub fn get_vmbus_storage_controllers(&self) -> &HashMap<Guid, VmbusStorageController> {
2706        &self.config.vmbus_storage_controllers
2707    }
2708
2709    /// Add or modify a VMBus disk drive
2710    pub async fn set_vmbus_drive(
2711        &mut self,
2712        drive: Drive,
2713        controller_id: &Guid,
2714        controller_location: Option<u32>,
2715    ) -> anyhow::Result<()> {
2716        let controller = self
2717            .config
2718            .vmbus_storage_controllers
2719            .get_mut(controller_id)
2720            .unwrap_or_else(|| panic!("storage controller {controller_id} does not exist"));
2721
2722        let controller_location = controller.set_drive(controller_location, drive, true);
2723        let disk = controller.drives.get(&controller_location).unwrap();
2724
2725        self.runtime
2726            .set_vmbus_drive(disk, controller_id, controller_location)
2727            .await?;
2728
2729        Ok(())
2730    }
2731
2732    /// Run the nested test. Failed if a nested test was not configured.
2733    pub async fn run_nested_test(
2734        &self,
2735        client: &PipetteClient,
2736        env: BTreeMap<String, String>,
2737    ) -> anyhow::Result<()> {
2738        self.run_nested_test_with_suffix(client, env, "").await
2739    }
2740
2741    /// Run the nested test with separate results for each invocation.
2742    ///
2743    /// Use a unique suffix when running the same nested test more than once.
2744    pub async fn run_nested_test_with_suffix(
2745        &self,
2746        client: &PipetteClient,
2747        env: BTreeMap<String, String>,
2748        suffix: &str,
2749    ) -> anyhow::Result<()> {
2750        let nested_test = self.nested_test.as_ref().context("no nested test")?;
2751        let results_dir = if self.guest_shares.contains_key(NESTED_CONTENT_TAG) {
2752            NESTED_RESULTS_DIR.to_owned()
2753        } else {
2754            format!("{NESTED_RESULTS_DIR}{suffix}")
2755        };
2756
2757        let test_binary_path =
2758            if let Some(test_content_dir) = self.guest_shares.get(NESTED_CONTENT_TAG) {
2759                let test_content_dir = absolute(&test_content_dir.host_path)?;
2760                let local_test_binary_path = absolute(&nested_test.test_binary)?;
2761
2762                self.convert_guest_path(
2763                    local_test_binary_path
2764                        .strip_prefix(&test_content_dir)
2765                        .context("test binary should be under content dir")?,
2766                )
2767            } else {
2768                self.binary_with_extension(NESTED_TEST_BINARY)
2769            };
2770
2771        let mut cmd = client
2772            .command(self.agent_disk_path(&[NESTED_TEST_CONTENT_DIR.into(), test_binary_path]));
2773        cmd.arg("--ignored")
2774            .arg("--exact")
2775            .arg(&nested_test.test_name)
2776            .env(
2777                VMM_TESTS_CONTENT_DIR,
2778                self.agent_disk_path(&[NESTED_TEST_CONTENT_DIR.into()]),
2779            )
2780            .env(
2781                VMM_TEST_IMAGES,
2782                self.agent_disk_path(&[NESTED_IMAGES_DIR.into()]),
2783            )
2784            .env(
2785                TEST_OUTPUT_PATH,
2786                self.agent_disk_path(&[NESTED_TEST_CONTENT_DIR.into(), results_dir.clone()]),
2787            )
2788            .stdout(crate::pipette::process::Stdio::piped())
2789            .stderr(crate::pipette::process::Stdio::piped());
2790
2791        for (k, v) in env {
2792            cmd.env(k, v);
2793        }
2794
2795        if self.guest_shares.contains_key(NESTED_CONTENT_TAG) {
2796            // Keep shared results under the normal results directory so the
2797            // host collects them, but give each invocation its own test name.
2798            cmd.env(PETRI_NESTED_TEST_PARENT, format!("{}{suffix}", self.name));
2799        }
2800
2801        if let Ok(v) = std::env::var(PETRI_REMOTE_ARTIFACTS) {
2802            cmd.env(PETRI_REMOTE_ARTIFACTS, v);
2803        }
2804
2805        let mut child = cmd.spawn().await?;
2806
2807        // TODO: output JSON, parse, and correctly format in logs
2808        self.resources
2809            .driver
2810            .spawn(
2811                "log_nested",
2812                crate::log_task(
2813                    self.resources
2814                        .log_source
2815                        .log_file(&format!("stdout{suffix}"))?,
2816                    child.stdout.take().unwrap(),
2817                    "nested stdout",
2818                ),
2819            )
2820            .detach();
2821
2822        let output = child.wait_with_output().await?;
2823
2824        // copy the files if we aren't sharing the results folder directly
2825        if !self.guest_shares.contains_key(NESTED_CONTENT_TAG) {
2826            let test_results_dir = self.agent_disk_path(&[
2827                NESTED_TEST_CONTENT_DIR.into(),
2828                results_dir,
2829                nested_test.test_name.replace("::", "__"),
2830            ]);
2831
2832            for file in client.list_dir(&test_results_dir).await? {
2833                let data = client
2834                    .read_file(self.build_guest_path(&[test_results_dir.clone(), file.clone()]))
2835                    .await?;
2836                let mut output = self
2837                    .resources
2838                    .log_source
2839                    .create_attachment_no_prefix(&format!("{suffix}{file}"))?;
2840                output.write_all(&data)?;
2841            }
2842        }
2843
2844        if !output.status.success() {
2845            anyhow::bail!(
2846                "nested test exited with status {}: {}",
2847                output.status,
2848                String::from_utf8_lossy(&output.stderr)
2849            );
2850        }
2851
2852        Ok(())
2853    }
2854}
2855
2856/// A running VM that tests can interact with.
2857#[async_trait]
2858pub trait PetriVmRuntime: Send + Sync + 'static {
2859    /// Interface for inspecting the VM
2860    type VmInspector: PetriVmInspector;
2861    /// Interface for accessing the framebuffer
2862    type VmFramebufferAccess: PetriVmFramebufferAccess;
2863
2864    /// Cleanly tear down the VM immediately.
2865    async fn teardown(self) -> anyhow::Result<()>;
2866    /// Wait for the VM to halt, returning the reason for the halt. The VM
2867    /// should automatically restart the VM on reset if `allow_reset` is true.
2868    async fn wait_for_halt(&mut self, allow_reset: bool) -> anyhow::Result<PetriHaltReasonDetail>;
2869    /// Wait for a connection from a pipette agent
2870    async fn wait_for_agent(&mut self, set_high_vtl: bool) -> anyhow::Result<PipetteClient>;
2871    /// Get an OpenHCL diagnostics handler for the VM
2872    fn openhcl_diag(&self) -> Option<OpenHclDiagHandler>;
2873    /// Waits for an event emitted by the firmware about its boot status, and
2874    /// returns that status. Returns `None` if `timeout` elapsed first.
2875    async fn wait_for_boot_event(
2876        &mut self,
2877        timeout: Option<Duration>,
2878    ) -> anyhow::Result<Option<FirmwareEvent>>;
2879    /// Waits for the Hyper-V shutdown IC to be ready
2880    // TODO: return a receiver that will be closed when it is no longer ready.
2881    async fn wait_for_enlightened_shutdown_ready(&mut self) -> anyhow::Result<()>;
2882    /// Instruct the guest to shutdown via the Hyper-V shutdown IC.
2883    async fn send_enlightened_shutdown(&mut self, kind: ShutdownKind) -> anyhow::Result<()>;
2884    /// Instruct the OpenHCL to restart the VTL2 paravisor. Will fail if the VM
2885    /// is not running OpenHCL. Will also fail if the VM is not running.
2886    async fn restart_openhcl(
2887        &mut self,
2888        new_openhcl: &ResolvedArtifact,
2889        flags: OpenHclServicingFlags,
2890    ) -> anyhow::Result<()>;
2891    /// Instruct the OpenHCL to save the state of the VTL2 paravisor. Will fail if the VM
2892    /// is not running OpenHCL. Will also fail if the VM is not running or if this is called twice in succession
2893    /// without a call to `restore_openhcl`.
2894    async fn save_openhcl(
2895        &mut self,
2896        new_openhcl: &ResolvedArtifact,
2897        flags: OpenHclServicingFlags,
2898    ) -> anyhow::Result<()>;
2899    /// Instruct the OpenHCL to restore the state of the VTL2 paravisor. Will fail if the VM
2900    /// is not running OpenHCL. Will also fail if the VM is running or if this is called without prior save.
2901    async fn restore_openhcl(&mut self) -> anyhow::Result<()>;
2902    /// Update the command line parameter of the running VM that will apply on next boot.
2903    /// Will fail if the VM is not using IGVM load mode.
2904    async fn update_command_line(&mut self, command_line: &str) -> anyhow::Result<()>;
2905    /// If the backend supports it, get an inspect interface
2906    fn inspector(&self) -> Option<Self::VmInspector> {
2907        None
2908    }
2909    /// If the backend supports it, take the screenshot interface
2910    /// (subsequent calls may return None).
2911    fn take_framebuffer_access(&mut self) -> Option<Self::VmFramebufferAccess> {
2912        None
2913    }
2914    /// Issue a hard reset to the VM
2915    async fn reset(&mut self) -> anyhow::Result<()>;
2916    /// Get the path to the VM's guest state file
2917    async fn get_guest_state_file(&self) -> anyhow::Result<Option<PathBuf>> {
2918        Ok(None)
2919    }
2920    /// Set the OpenHCL VTL2 settings
2921    async fn set_vtl2_settings(&mut self, settings: &Vtl2Settings) -> anyhow::Result<()>;
2922    /// Add or modify a VMBus disk drive
2923    async fn set_vmbus_drive(
2924        &mut self,
2925        disk: &Drive,
2926        controller_id: &Guid,
2927        controller_location: u32,
2928    ) -> anyhow::Result<()>;
2929    /// Hot-add a PCIe device to a named port at runtime.
2930    async fn add_pcie_device(
2931        &mut self,
2932        port_name: String,
2933        resource: vm_resource::Resource<vm_resource::kind::PciDeviceHandleKind>,
2934    ) -> anyhow::Result<()> {
2935        let _ = (port_name, resource);
2936        anyhow::bail!("PCIe hotplug not supported by this backend")
2937    }
2938    /// Hot-remove a PCIe device from a named port at runtime.
2939    async fn remove_pcie_device(&mut self, port_name: String) -> anyhow::Result<()> {
2940        let _ = port_name;
2941        anyhow::bail!("PCIe hotplug not supported by this backend")
2942    }
2943}
2944
2945/// Interface for getting information about the state of the VM
2946#[async_trait]
2947pub trait PetriVmInspector: Send + Sync + 'static {
2948    /// Get information about the state of the VM at the given inspect `path`.
2949    /// Pass `""` to inspect the entire tree.
2950    async fn inspect(&self, path: &str) -> anyhow::Result<inspect::Node>;
2951}
2952
2953/// Use this for the associated type if not supported
2954pub struct NoPetriVmInspector;
2955#[async_trait]
2956impl PetriVmInspector for NoPetriVmInspector {
2957    async fn inspect(&self, _path: &str) -> anyhow::Result<inspect::Node> {
2958        unreachable!()
2959    }
2960}
2961
2962/// Raw VM screenshot
2963pub struct VmScreenshotMeta {
2964    /// color encoding used by the image
2965    pub color: image::ExtendedColorType,
2966    /// x dimension
2967    pub width: u16,
2968    /// y dimension
2969    pub height: u16,
2970}
2971
2972/// Interface for getting screenshots of the VM
2973#[async_trait]
2974pub trait PetriVmFramebufferAccess: Send + 'static {
2975    /// Populates the provided buffer with a screenshot of the VM,
2976    /// returning the dimensions and color type.
2977    async fn screenshot(&mut self, image: &mut Vec<u8>)
2978    -> anyhow::Result<Option<VmScreenshotMeta>>;
2979}
2980
2981/// Use this for the associated type if not supported
2982pub struct NoPetriVmFramebufferAccess;
2983#[async_trait]
2984impl PetriVmFramebufferAccess for NoPetriVmFramebufferAccess {
2985    async fn screenshot(
2986        &mut self,
2987        _image: &mut Vec<u8>,
2988    ) -> anyhow::Result<Option<VmScreenshotMeta>> {
2989        unreachable!()
2990    }
2991}
2992
2993/// Common processor topology information for the VM.
2994#[derive(Debug, Clone)]
2995pub struct ProcessorTopology {
2996    /// The number of virtual processors.
2997    pub vp_count: u32,
2998    /// Whether SMT (hyperthreading) is enabled.
2999    pub enable_smt: Option<bool>,
3000    /// The number of virtual processors per socket.
3001    pub vps_per_socket: Option<u32>,
3002    /// The APIC configuration (x86-64 only).
3003    pub apic_mode: Option<ApicMode>,
3004}
3005
3006impl Default for ProcessorTopology {
3007    fn default() -> Self {
3008        Self {
3009            vp_count: 2,
3010            enable_smt: None,
3011            vps_per_socket: None,
3012            apic_mode: None,
3013        }
3014    }
3015}
3016
3017impl ProcessorTopology {
3018    /// A large number of VPs
3019    pub fn heavy() -> Self {
3020        Self {
3021            vp_count: 16,
3022            vps_per_socket: Some(8),
3023            ..Default::default()
3024        }
3025    }
3026
3027    /// A very large number of VPs
3028    pub fn very_heavy() -> Self {
3029        Self {
3030            vp_count: 32,
3031            vps_per_socket: Some(16),
3032            ..Default::default()
3033        }
3034    }
3035}
3036
3037/// The APIC mode for the VM.
3038#[derive(Debug, Clone, Copy)]
3039pub enum ApicMode {
3040    /// xAPIC mode only.
3041    Xapic,
3042    /// x2APIC mode supported but not enabled at boot.
3043    X2apicSupported,
3044    /// x2APIC mode enabled at boot.
3045    X2apicEnabled,
3046}
3047
3048/// Common memory configuration information for the VM.
3049#[derive(Debug, Clone)]
3050pub struct MemoryConfig {
3051    /// Specifies the amount of memory, in bytes, to assign to the
3052    /// virtual machine.
3053    pub startup_bytes: u64,
3054    /// Specifies the minimum and maximum amount of dynamic memory, in bytes.
3055    ///
3056    /// Dynamic memory will be disabled if this is `None`.
3057    pub dynamic_memory_range: Option<(u64, u64)>,
3058    /// Per-NUMA-node memory sizes. When set, RAM is distributed across
3059    /// vNUMA nodes instead of assigning all RAM to node 0.
3060    pub numa_mem_sizes: Option<Vec<u64>>,
3061    /// Whether to back guest RAM with private anonymous memory rather than a
3062    /// shared (file/memfd-backed) memory section.
3063    ///
3064    /// - `None` (the default) uses private memory whenever the configuration
3065    ///   allows it, falling back to shared memory otherwise. Private anonymous
3066    ///   memory is cheaper to set up and eligible for Transparent Huge Pages,
3067    ///   so it is preferred for performance; this lets each VM get the best
3068    ///   backing for its firmware without the test having to know the details.
3069    /// - `Some(true)` explicitly requires private memory. This is an error if
3070    ///   the configuration is incompatible with private memory (OpenHCL, which
3071    ///   shares VTL0 RAM with VTL2 via a remote mapper, and PCAT/Gen1, which
3072    ///   relies on x86 legacy support, both require shared memory), rather than
3073    ///   silently downgrading to shared.
3074    /// - `Some(false)` explicitly requires shared memory, for tests that need
3075    ///   the guest RAM backing to be shareable with another process, such as
3076    ///   vhost-user backends.
3077    ///
3078    /// Only applies to the OpenVMM backend; ignored by Hyper-V.
3079    pub private_memory: Option<bool>,
3080    /// Mark guest RAM as eligible for Transparent Huge Pages (THP),
3081    /// improving performance for large allocations.
3082    ///
3083    /// Defaults to `true`. Applies to private anonymous guest RAM and to
3084    /// shared memfd-backed RAM, on Linux (via `madvise`) and on Windows (via
3085    /// soft large pages). It has no effect on explicit hugetlb/large-page
3086    /// backings (see
3087    /// [`with_hugepages`](crate::openvmm::PetriVmConfigOpenVmm::with_hugepages)),
3088    /// which are already huge.
3089    ///
3090    /// Only applies to the OpenVMM backend; ignored by Hyper-V.
3091    pub transparent_hugepages: bool,
3092}
3093
3094impl Default for MemoryConfig {
3095    fn default() -> Self {
3096        Self {
3097            startup_bytes: 4 * 1024 * 1024 * 1024, // 4 GiB
3098            dynamic_memory_range: None,
3099            numa_mem_sizes: None,
3100            private_memory: None,
3101            transparent_hugepages: true,
3102        }
3103    }
3104}
3105
3106/// UEFI firmware configuration
3107#[derive(Debug, Clone)]
3108pub struct UefiConfig {
3109    /// Enable secure boot
3110    pub secure_boot_enabled: bool,
3111    /// Secure boot template
3112    pub secure_boot_template: Option<SecureBootTemplate>,
3113    /// Custom UEFI variable delta JSON
3114    pub custom_uefi_json: Option<Vec<u8>>,
3115    /// Disable the UEFI frontpage which will cause the VM to shutdown instead when unable to boot.
3116    pub disable_frontpage: bool,
3117    /// Always attempt a default boot
3118    pub default_boot_always_attempt: bool,
3119    /// Enable vPCI boot (for NVMe)
3120    pub enable_vpci_boot: bool,
3121    /// Force UEFI to bounce-buffer all DMA traffic
3122    pub force_dma_bounce: bool,
3123    /// EFI diagnostics log level filter
3124    pub efi_diagnostics_log_level: EfiDiagnosticsLogLevel,
3125    /// Per-period rate-limit override for EFI diagnostics emission.
3126    /// See [`PetriVmBuilder::with_efi_diagnostics_rate_limit()`] for more information.
3127    pub efi_diagnostics_rate_limit: Option<u32>,
3128}
3129
3130impl Default for UefiConfig {
3131    fn default() -> Self {
3132        Self {
3133            secure_boot_enabled: false,
3134            secure_boot_template: None,
3135            custom_uefi_json: None,
3136            disable_frontpage: true,
3137            default_boot_always_attempt: false,
3138            enable_vpci_boot: false,
3139            force_dma_bounce: false,
3140            efi_diagnostics_log_level: EfiDiagnosticsLogLevel::Default,
3141            efi_diagnostics_rate_limit: None,
3142        }
3143    }
3144}
3145
3146/// EFI diagnostics log level filter.
3147///
3148/// Controls which UEFI diagnostics log entries are forwarded to the host
3149/// tracing infrastructure (and thus visible via kmsg / test output).
3150#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
3151pub enum EfiDiagnosticsLogLevel {
3152    /// Default log level (ERROR and WARN only).
3153    #[default]
3154    Default,
3155    /// Include INFO logs (ERROR, WARN, and INFO).
3156    Info,
3157    /// All log levels.
3158    Full,
3159}
3160
3161/// Control the logging configuration of OpenVMM/OpenHCL.
3162#[derive(Debug, Clone)]
3163pub enum OpenvmmLogConfig {
3164    /// Use the default log levels used by petri tests. This will forward
3165    /// `OPENVMM_LOG` and `OPENVMM_SHOW_SPANS` from the environment if they are
3166    /// set, otherwise it will use `debug` and `false` respectively
3167    TestDefault,
3168    /// Use the built-in default log levels of OpenHCL/OpenVMM (e.g. don't pass
3169    /// OPENVMM_LOG or OPENVMM_SHOW_SPANS)
3170    BuiltInDefault,
3171    /// Use the provided custom log levels, specified as key/value pairs. At this time,
3172    /// simply uses the already-defined environment variables (e.g.
3173    /// `OPENVMM_LOG=info,disk_nvme=debug OPENVMM_SHOW_SPANS=true`)
3174    ///
3175    /// See the Guide and source code for configuring these logs.
3176    /// - For the host VMM: see `enable_tracing` in `tracing_init.rs` for details on
3177    ///   the accepted keys and values.
3178    /// - For OpenHCL, see `init_tracing_backend` in `openhcl/src/logging/mod.rs` for details on
3179    ///   the accepted keys and values.
3180    Custom(BTreeMap<String, String>),
3181}
3182
3183/// OpenHCL configuration
3184#[derive(Debug, Clone)]
3185pub struct OpenHclConfig {
3186    /// Whether to enable VMBus redirection
3187    pub vmbus_redirect: bool,
3188    /// Whether to enable MANA keepalive at boot.
3189    pub enable_mana_keepalive: bool,
3190    /// Test-specified command-line parameters to append to the petri generated
3191    /// command line and pass to OpenHCL. VM backends should use
3192    /// [`OpenHclConfig::command_line()`] rather than reading this directly.
3193    pub custom_command_line: Option<String>,
3194    /// Command line parameters that control OpenHCL logging behavior. Separate
3195    /// from `command_line` so that petri can decide to use default log
3196    /// levels.
3197    pub log_levels: OpenvmmLogConfig,
3198    /// How to place VTL2 in address space. If `None`, the backend VMM
3199    /// will decide on default behavior.
3200    pub vtl2_base_address_type: Option<Vtl2BaseAddressType>,
3201    /// VTL2 settings
3202    pub vtl2_settings: Option<Vtl2Settings>,
3203}
3204
3205impl OpenHclConfig {
3206    /// Returns the command line to pass to OpenHCL based on these parameters. Aggregates
3207    /// the command line and log levels.
3208    pub fn command_line(&self) -> String {
3209        let mut cmdline = self.custom_command_line.clone();
3210
3211        if self.enable_mana_keepalive {
3212            append_cmdline(&mut cmdline, "OPENHCL_MANA_KEEP_ALIVE=host,privatepool");
3213        }
3214
3215        match &self.log_levels {
3216            OpenvmmLogConfig::TestDefault => {
3217                let default_log_levels = {
3218                    // Forward OPENVMM_LOG and OPENVMM_SHOW_SPANS to OpenHCL if they're set.
3219                    let openhcl_tracing = if let Ok(x) =
3220                        std::env::var("OPENVMM_LOG").or_else(|_| std::env::var("HVLITE_LOG"))
3221                    {
3222                        format!("OPENVMM_LOG={x}")
3223                    } else {
3224                        "OPENVMM_LOG=debug".to_owned()
3225                    };
3226                    let openhcl_show_spans = if let Ok(x) = std::env::var("OPENVMM_SHOW_SPANS") {
3227                        format!("OPENVMM_SHOW_SPANS={x}")
3228                    } else {
3229                        "OPENVMM_SHOW_SPANS=false".to_owned()
3230                    };
3231                    format!("{openhcl_tracing} {openhcl_show_spans}")
3232                };
3233                append_cmdline(&mut cmdline, &default_log_levels);
3234            }
3235            OpenvmmLogConfig::BuiltInDefault => {
3236                // do nothing, use whatever the built-in default is
3237            }
3238            OpenvmmLogConfig::Custom(levels) => {
3239                levels.iter().for_each(|(key, value)| {
3240                    append_cmdline(&mut cmdline, format!("{key}={value}"));
3241                });
3242            }
3243        }
3244
3245        cmdline.unwrap_or_default()
3246    }
3247}
3248
3249impl Default for OpenHclConfig {
3250    fn default() -> Self {
3251        Self {
3252            vmbus_redirect: false,
3253            enable_mana_keepalive: true,
3254            custom_command_line: None,
3255            log_levels: OpenvmmLogConfig::TestDefault,
3256            vtl2_base_address_type: None,
3257            vtl2_settings: None,
3258        }
3259    }
3260}
3261
3262/// TPM configuration
3263#[derive(Debug, Clone)]
3264pub struct TpmConfig {
3265    /// Use ephemeral TPM state (do not persist to VMGS)
3266    pub no_persistent_secrets: bool,
3267    /// Hardware sealing policy for sealed secrets
3268    pub hardware_sealing_policy: PetriHardwareSealingPolicy,
3269    /// TPM reference implementation version
3270    pub version: PetriTpmVersion,
3271}
3272
3273impl Default for TpmConfig {
3274    fn default() -> Self {
3275        Self {
3276            no_persistent_secrets: true,
3277            hardware_sealing_policy: PetriHardwareSealingPolicy::Default,
3278            version: PetriTpmVersion::default(),
3279        }
3280    }
3281}
3282
3283/// TPM reference implementation version used by the test infrastructure.
3284#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
3285pub enum PetriTpmVersion {
3286    /// TPM reference implementation version 1.38
3287    V138,
3288    /// TPM reference implementation version 1.85
3289    #[default]
3290    V185,
3291}
3292
3293impl From<PetriTpmVersion> for tpm_resources::TpmVersion {
3294    fn from(version: PetriTpmVersion) -> Self {
3295        match version {
3296            PetriTpmVersion::V138 => tpm_resources::TpmVersion::V138,
3297            PetriTpmVersion::V185 => tpm_resources::TpmVersion::V185,
3298        }
3299    }
3300}
3301
3302impl From<PetriTpmVersion> for get_resources::ged::GedTpmVersion {
3303    fn from(version: PetriTpmVersion) -> Self {
3304        match version {
3305            PetriTpmVersion::V138 => get_resources::ged::GedTpmVersion::V138,
3306            PetriTpmVersion::V185 => get_resources::ged::GedTpmVersion::V185,
3307        }
3308    }
3309}
3310
3311/// Hardware sealing policy used by the test infrastructure.
3312///
3313/// Maps to Hyper-V `Set-GuestStateEncryptionPolicy` values and
3314/// underhill's `HardwareSealingPolicy`.
3315#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
3316pub enum PetriHardwareSealingPolicy {
3317    /// No explicit policy — the backend picks its default.
3318    #[default]
3319    Default,
3320    /// Derive the hardware sealing key from measurement hash.
3321    HashPolicy,
3322    /// Derive the hardware sealing key from signer information.
3323    SignerPolicy,
3324}
3325
3326/// Source for the IGVM firmware used to load OpenHCL.
3327#[derive(Debug, Clone)]
3328pub enum IgvmFirmwareSource {
3329    /// Load the IGVM from the specified file.
3330    File(ResolvedArtifact),
3331    /// Load the IGVM from VMGS, falling back to the in-box firmware.
3332    VmgsOrInBox,
3333}
3334
3335/// Firmware to load into the test VM.
3336// TODO: remove the guests from the firmware enum so that we don't pass them
3337// to the VMM backend after we have already used them generically.
3338#[derive(Debug, Clone)]
3339pub enum Firmware {
3340    /// Boot Linux directly, without any firmware.
3341    LinuxDirect {
3342        /// The kernel to boot.
3343        kernel: ResolvedArtifact,
3344        /// The initrd to use.
3345        initrd: ResolvedArtifact,
3346    },
3347    /// Boot an isolated Linux guest from an IGVM file with no paravisor.
3348    IgvmLinuxDirect {
3349        /// The IGVM file with the measured kernel, initrd, and bootshim.
3350        igvm_path: ResolvedArtifact,
3351        /// The isolation type of the guest.
3352        isolation: IsolationType,
3353    },
3354    /// Boot Linux directly, without any firmware, with OpenHCL in VTL2.
3355    OpenhclLinuxDirect {
3356        /// The source for the IGVM firmware.
3357        igvm_firmware: IgvmFirmwareSource,
3358        /// OpenHCL configuration
3359        openhcl_config: OpenHclConfig,
3360    },
3361    /// Boot a PCAT-based VM.
3362    Pcat {
3363        /// The guest OS the VM will boot into.
3364        guest: PcatGuest,
3365        /// The firmware to use.
3366        bios_firmware: ResolvedOptionalArtifact,
3367        /// The SVGA firmware to use.
3368        svga_firmware: ResolvedOptionalArtifact,
3369        /// IDE controllers and associated disks
3370        ide_controllers: [[Option<Drive>; 2]; 2],
3371    },
3372    /// Boot a PCAT-based VM with OpenHCL in VTL2.
3373    OpenhclPcat {
3374        /// The guest OS the VM will boot into.
3375        guest: PcatGuest,
3376        /// The source for the IGVM firmware.
3377        igvm_firmware: IgvmFirmwareSource,
3378        /// The firmware to use.
3379        bios_firmware: ResolvedOptionalArtifact,
3380        /// The SVGA firmware to use.
3381        svga_firmware: ResolvedOptionalArtifact,
3382        /// OpenHCL configuration
3383        openhcl_config: OpenHclConfig,
3384    },
3385    /// Boot a UEFI-based VM.
3386    Uefi {
3387        /// The guest OS the VM will boot into.
3388        guest: UefiGuest,
3389        /// The firmware to use.
3390        uefi_firmware: ResolvedArtifact,
3391        /// UEFI configuration
3392        uefi_config: UefiConfig,
3393    },
3394    /// Boot a UEFI-based VM with OpenHCL in VTL2.
3395    OpenhclUefi {
3396        /// The guest OS the VM will boot into.
3397        guest: UefiGuest,
3398        /// The isolation type of the VM.
3399        isolation: Option<IsolationType>,
3400        /// The source for the IGVM firmware.
3401        igvm_firmware: IgvmFirmwareSource,
3402        /// UEFI configuration
3403        uefi_config: UefiConfig,
3404        /// OpenHCL configuration
3405        openhcl_config: OpenHclConfig,
3406    },
3407}
3408
3409/// The boot device type.
3410#[derive(Debug, Copy, Clone, PartialEq, Eq)]
3411pub enum BootDeviceType {
3412    /// Don't initialize a boot device.
3413    None,
3414    /// Boot from IDE.
3415    Ide,
3416    /// Boot from IDE via SCSI to VTL2.
3417    IdeViaScsi,
3418    /// Boot from IDE via NVME to VTL2.
3419    IdeViaNvme,
3420    /// Boot from SCSI.
3421    Scsi,
3422    /// Boot from SCSI via SCSI to VTL2.
3423    ScsiViaScsi,
3424    /// Boot from SCSI via NVME to VTL2.
3425    ScsiViaNvme,
3426    /// Boot from NVMe.
3427    Nvme,
3428    /// Boot from NVMe via SCSI to VTL2.
3429    NvmeViaScsi,
3430    /// Boot from NVMe via NVMe to VTL2.
3431    NvmeViaNvme,
3432    /// Boot from NVMe attached to a PCIe root port.
3433    PcieNvme,
3434    /// Boot from virtio-blk attached to a PCIe root port.
3435    PcieVirtioBlk,
3436}
3437
3438impl BootDeviceType {
3439    fn requires_vtl2(&self) -> bool {
3440        match self {
3441            BootDeviceType::None
3442            | BootDeviceType::Ide
3443            | BootDeviceType::Scsi
3444            | BootDeviceType::Nvme
3445            | BootDeviceType::PcieNvme
3446            | BootDeviceType::PcieVirtioBlk => false,
3447            BootDeviceType::IdeViaScsi
3448            | BootDeviceType::IdeViaNvme
3449            | BootDeviceType::ScsiViaScsi
3450            | BootDeviceType::ScsiViaNvme
3451            | BootDeviceType::NvmeViaScsi
3452            | BootDeviceType::NvmeViaNvme => true,
3453        }
3454    }
3455
3456    fn requires_vpci_boot(&self) -> bool {
3457        matches!(
3458            self,
3459            BootDeviceType::Nvme | BootDeviceType::NvmeViaScsi | BootDeviceType::NvmeViaNvme
3460        )
3461    }
3462
3463    fn requires_vmbus(&self) -> bool {
3464        match self {
3465            BootDeviceType::None
3466            | BootDeviceType::Ide
3467            | BootDeviceType::PcieNvme
3468            | BootDeviceType::PcieVirtioBlk => false,
3469            BootDeviceType::IdeViaScsi
3470            | BootDeviceType::IdeViaNvme
3471            | BootDeviceType::Scsi
3472            | BootDeviceType::ScsiViaScsi
3473            | BootDeviceType::ScsiViaNvme
3474            | BootDeviceType::Nvme
3475            | BootDeviceType::NvmeViaScsi
3476            | BootDeviceType::NvmeViaNvme => true,
3477        }
3478    }
3479}
3480
3481impl Firmware {
3482    /// Constructs a standard [`Firmware::LinuxDirect`] configuration, or a
3483    /// [`Firmware::IgvmLinuxDirect`] configuration if `isolation` is set.
3484    pub fn linux_direct(
3485        resolver: &ArtifactResolver<'_>,
3486        arch: MachineArch,
3487        isolation: Option<IsolationType>,
3488    ) -> Self {
3489        use petri_artifacts_vmm_test::artifacts::loadable::*;
3490        use petri_artifacts_vmm_test::artifacts::snp_igvm::SNP_LINUX_DIRECT_IGVM_X64;
3491        match (arch, isolation) {
3492            (MachineArch::X86_64, None) => Firmware::LinuxDirect {
3493                kernel: resolver.require(LINUX_DIRECT_TEST_KERNEL_X64).erase(),
3494                initrd: resolver.require(LINUX_DIRECT_TEST_INITRD_X64).erase(),
3495            },
3496            (MachineArch::Aarch64, None) => Firmware::LinuxDirect {
3497                kernel: resolver.require(LINUX_DIRECT_TEST_KERNEL_AARCH64).erase(),
3498                initrd: resolver.require(LINUX_DIRECT_TEST_INITRD_AARCH64).erase(),
3499            },
3500            (MachineArch::X86_64, Some(IsolationType::Snp)) => Firmware::IgvmLinuxDirect {
3501                igvm_path: resolver.require(SNP_LINUX_DIRECT_IGVM_X64).erase(),
3502                isolation: IsolationType::Snp,
3503            },
3504            (arch, Some(isolation)) => {
3505                panic!("Linux direct does not support {isolation:?} isolation on {arch:?}")
3506            }
3507        }
3508    }
3509
3510    /// Constructs a [`Firmware::LinuxDirect`] configuration that uses a
3511    /// compressed bzImage kernel instead of an uncompressed ELF.
3512    ///
3513    /// This is x86_64-only, as bzImage is an x86-specific format.
3514    pub fn linux_direct_bzimage(resolver: &ArtifactResolver<'_>) -> Self {
3515        use petri_artifacts_vmm_test::artifacts::loadable::*;
3516        Firmware::LinuxDirect {
3517            kernel: resolver.require(LINUX_DIRECT_TEST_BZIMAGE_X64).erase(),
3518            initrd: resolver.require(LINUX_DIRECT_TEST_INITRD_X64).erase(),
3519        }
3520    }
3521
3522    /// Constructs a standard [`Firmware::OpenhclLinuxDirect`] configuration.
3523    pub fn openhcl_linux_direct(resolver: &ArtifactResolver<'_>, arch: MachineArch) -> Self {
3524        use petri_artifacts_vmm_test::artifacts::openhcl_igvm::*;
3525        match arch {
3526            MachineArch::X86_64 => Firmware::OpenhclLinuxDirect {
3527                igvm_firmware: IgvmFirmwareSource::File(
3528                    resolver.require(LATEST_LINUX_DIRECT_TEST_X64).erase(),
3529                ),
3530                openhcl_config: Default::default(),
3531            },
3532            MachineArch::Aarch64 => todo!("Linux direct not yet supported on aarch64"),
3533        }
3534    }
3535
3536    /// Constructs a standard [`Firmware::Pcat`] configuration.
3537    pub fn pcat(resolver: &ArtifactResolver<'_>, guest: PcatGuest) -> Self {
3538        use petri_artifacts_vmm_test::artifacts::loadable::*;
3539        Firmware::Pcat {
3540            guest,
3541            bios_firmware: resolver.try_require(PCAT_FIRMWARE_X64).erase(),
3542            svga_firmware: resolver.try_require(SVGA_FIRMWARE_X64).erase(),
3543            ide_controllers: [[None, None], [None, None]],
3544        }
3545    }
3546
3547    /// Constructs a standard [`Firmware::OpenhclPcat`] configuration.
3548    pub fn openhcl_pcat(resolver: &ArtifactResolver<'_>, guest: PcatGuest) -> Self {
3549        use petri_artifacts_vmm_test::artifacts::loadable::*;
3550        use petri_artifacts_vmm_test::artifacts::openhcl_igvm::*;
3551        Firmware::OpenhclPcat {
3552            guest,
3553            igvm_firmware: IgvmFirmwareSource::File(resolver.require(LATEST_STANDARD_X64).erase()),
3554            bios_firmware: resolver.try_require(PCAT_FIRMWARE_X64).erase(),
3555            svga_firmware: resolver.try_require(SVGA_FIRMWARE_X64).erase(),
3556            openhcl_config: OpenHclConfig {
3557                // VMBUS redirect is necessary for IDE to be provided by VTL2
3558                vmbus_redirect: true,
3559                ..Default::default()
3560            },
3561        }
3562    }
3563
3564    /// Constructs a standard [`Firmware::Uefi`] configuration.
3565    pub fn uefi(resolver: &ArtifactResolver<'_>, arch: MachineArch, guest: UefiGuest) -> Self {
3566        use petri_artifacts_vmm_test::artifacts::loadable::*;
3567        let uefi_firmware = match arch {
3568            MachineArch::X86_64 => resolver.require(UEFI_FIRMWARE_X64).erase(),
3569            MachineArch::Aarch64 => resolver.require(UEFI_FIRMWARE_AARCH64).erase(),
3570        };
3571        Firmware::Uefi {
3572            guest,
3573            uefi_firmware,
3574            uefi_config: Default::default(),
3575        }
3576    }
3577
3578    /// Constructs a standard [`Firmware::OpenhclUefi`] configuration.
3579    pub fn openhcl_uefi(
3580        resolver: &ArtifactResolver<'_>,
3581        arch: MachineArch,
3582        guest: UefiGuest,
3583        isolation: Option<IsolationType>,
3584    ) -> Self {
3585        use petri_artifacts_vmm_test::artifacts::openhcl_igvm::*;
3586        let igvm_firmware = IgvmFirmwareSource::File(match arch {
3587            MachineArch::X86_64 if isolation.is_some() => resolver.require(LATEST_CVM_X64).erase(),
3588            MachineArch::X86_64 => resolver.require(LATEST_STANDARD_X64).erase(),
3589            MachineArch::Aarch64 => resolver.require(LATEST_STANDARD_AARCH64).erase(),
3590        });
3591        Firmware::OpenhclUefi {
3592            guest,
3593            isolation,
3594            igvm_firmware,
3595            uefi_config: Default::default(),
3596            openhcl_config: Default::default(),
3597        }
3598    }
3599
3600    fn is_openhcl(&self) -> bool {
3601        match self {
3602            Firmware::OpenhclLinuxDirect { .. }
3603            | Firmware::OpenhclUefi { .. }
3604            | Firmware::OpenhclPcat { .. } => true,
3605            Firmware::LinuxDirect { .. }
3606            | Firmware::IgvmLinuxDirect { .. }
3607            | Firmware::Pcat { .. }
3608            | Firmware::Uefi { .. } => false,
3609        }
3610    }
3611
3612    fn isolation(&self) -> Option<IsolationType> {
3613        match self {
3614            Firmware::IgvmLinuxDirect { isolation, .. } => Some(*isolation),
3615            Firmware::OpenhclUefi { isolation, .. } => *isolation,
3616            Firmware::LinuxDirect { .. }
3617            | Firmware::Pcat { .. }
3618            | Firmware::Uefi { .. }
3619            | Firmware::OpenhclLinuxDirect { .. }
3620            | Firmware::OpenhclPcat { .. } => None,
3621        }
3622    }
3623
3624    /// Isolated guest with no paravisor
3625    fn is_isolated_without_paravisor(&self) -> bool {
3626        self.isolation().is_some() && !self.is_openhcl()
3627    }
3628
3629    fn is_linux_direct(&self) -> bool {
3630        match self {
3631            Firmware::LinuxDirect { .. }
3632            | Firmware::IgvmLinuxDirect { .. }
3633            | Firmware::OpenhclLinuxDirect { .. } => true,
3634            Firmware::Pcat { .. }
3635            | Firmware::Uefi { .. }
3636            | Firmware::OpenhclUefi { .. }
3637            | Firmware::OpenhclPcat { .. } => false,
3638        }
3639    }
3640
3641    /// Get the initrd path for Linux direct boot firmware.
3642    pub fn linux_direct_initrd(&self) -> Option<&Path> {
3643        match self {
3644            Firmware::LinuxDirect { initrd, .. } => Some(initrd.get()),
3645            _ => None,
3646        }
3647    }
3648
3649    fn is_pcat(&self) -> bool {
3650        match self {
3651            Firmware::Pcat { .. } | Firmware::OpenhclPcat { .. } => true,
3652            Firmware::Uefi { .. }
3653            | Firmware::OpenhclUefi { .. }
3654            | Firmware::LinuxDirect { .. }
3655            | Firmware::IgvmLinuxDirect { .. }
3656            | Firmware::OpenhclLinuxDirect { .. } => false,
3657        }
3658    }
3659
3660    fn os_flavor(&self) -> OsFlavor {
3661        match self {
3662            Firmware::LinuxDirect { .. }
3663            | Firmware::OpenhclLinuxDirect { .. }
3664            | Firmware::Uefi {
3665                guest: UefiGuest::Mshv(_),
3666                ..
3667            }
3668            | Firmware::OpenhclUefi {
3669                guest: UefiGuest::Mshv(_),
3670                ..
3671            }
3672            | Firmware::IgvmLinuxDirect { .. } => OsFlavor::Linux,
3673            Firmware::Uefi {
3674                guest: UefiGuest::GuestTestUefi { .. } | UefiGuest::None,
3675                ..
3676            }
3677            | Firmware::OpenhclUefi {
3678                guest: UefiGuest::GuestTestUefi { .. } | UefiGuest::None,
3679                ..
3680            } => OsFlavor::Uefi,
3681            Firmware::Pcat {
3682                guest: PcatGuest::Vhd(cfg),
3683                ..
3684            }
3685            | Firmware::OpenhclPcat {
3686                guest: PcatGuest::Vhd(cfg),
3687                ..
3688            }
3689            | Firmware::Uefi {
3690                guest: UefiGuest::Vhd(cfg),
3691                ..
3692            }
3693            | Firmware::OpenhclUefi {
3694                guest: UefiGuest::Vhd(cfg),
3695                ..
3696            } => cfg.os_flavor,
3697            Firmware::Pcat {
3698                guest: PcatGuest::Iso(cfg),
3699                ..
3700            }
3701            | Firmware::OpenhclPcat {
3702                guest: PcatGuest::Iso(cfg),
3703                ..
3704            } => cfg.os_flavor,
3705        }
3706    }
3707
3708    fn quirks(&self) -> GuestQuirks {
3709        match self {
3710            Firmware::Pcat {
3711                guest: PcatGuest::Vhd(cfg),
3712                ..
3713            }
3714            | Firmware::Uefi {
3715                guest: UefiGuest::Vhd(cfg),
3716                ..
3717            }
3718            | Firmware::OpenhclUefi {
3719                guest: UefiGuest::Vhd(cfg),
3720                ..
3721            } => cfg.quirks.clone(),
3722            Firmware::Pcat {
3723                guest: PcatGuest::Iso(cfg),
3724                ..
3725            } => cfg.quirks.clone(),
3726            _ => Default::default(),
3727        }
3728    }
3729
3730    fn expected_boot_event(&self) -> Option<FirmwareEvent> {
3731        match self {
3732            Firmware::LinuxDirect { .. }
3733            | Firmware::IgvmLinuxDirect { .. }
3734            | Firmware::OpenhclLinuxDirect { .. }
3735            | Firmware::Uefi {
3736                guest: UefiGuest::GuestTestUefi(_),
3737                ..
3738            }
3739            | Firmware::OpenhclUefi {
3740                guest: UefiGuest::GuestTestUefi(_),
3741                ..
3742            } => None,
3743            Firmware::Pcat { .. } | Firmware::OpenhclPcat { .. } => {
3744                // TODO: Handle older PCAT versions that don't fire the event
3745                Some(FirmwareEvent::BootAttempt)
3746            }
3747            Firmware::Uefi {
3748                guest: UefiGuest::None,
3749                ..
3750            }
3751            | Firmware::OpenhclUefi {
3752                guest: UefiGuest::None,
3753                ..
3754            } => Some(FirmwareEvent::NoBootDevice),
3755            Firmware::Uefi { .. } | Firmware::OpenhclUefi { .. } => {
3756                Some(FirmwareEvent::BootSuccess)
3757            }
3758        }
3759    }
3760
3761    fn openhcl_config(&self) -> Option<&OpenHclConfig> {
3762        match self {
3763            Firmware::OpenhclLinuxDirect { openhcl_config, .. }
3764            | Firmware::OpenhclUefi { openhcl_config, .. }
3765            | Firmware::OpenhclPcat { openhcl_config, .. } => Some(openhcl_config),
3766            Firmware::LinuxDirect { .. }
3767            | Firmware::IgvmLinuxDirect { .. }
3768            | Firmware::Pcat { .. }
3769            | Firmware::Uefi { .. } => None,
3770        }
3771    }
3772
3773    fn openhcl_config_mut(&mut self) -> Option<&mut OpenHclConfig> {
3774        match self {
3775            Firmware::OpenhclLinuxDirect { openhcl_config, .. }
3776            | Firmware::OpenhclUefi { openhcl_config, .. }
3777            | Firmware::OpenhclPcat { openhcl_config, .. } => Some(openhcl_config),
3778            Firmware::LinuxDirect { .. }
3779            | Firmware::IgvmLinuxDirect { .. }
3780            | Firmware::Pcat { .. }
3781            | Firmware::Uefi { .. } => None,
3782        }
3783    }
3784
3785    fn openhcl_firmware(&self) -> Option<&IgvmFirmwareSource> {
3786        match self {
3787            Firmware::OpenhclLinuxDirect { igvm_firmware, .. }
3788            | Firmware::OpenhclUefi { igvm_firmware, .. }
3789            | Firmware::OpenhclPcat { igvm_firmware, .. } => Some(igvm_firmware),
3790            Firmware::LinuxDirect { .. }
3791            | Firmware::IgvmLinuxDirect { .. }
3792            | Firmware::Pcat { .. }
3793            | Firmware::Uefi { .. } => None,
3794        }
3795    }
3796
3797    fn into_runtime_config(
3798        self,
3799        vmbus_storage_controllers: HashMap<Guid, VmbusStorageController>,
3800    ) -> PetriVmRuntimeConfig {
3801        match self {
3802            Firmware::OpenhclLinuxDirect { openhcl_config, .. }
3803            | Firmware::OpenhclUefi { openhcl_config, .. }
3804            | Firmware::OpenhclPcat { openhcl_config, .. } => PetriVmRuntimeConfig {
3805                vtl2_settings: Some(
3806                    openhcl_config
3807                        .vtl2_settings
3808                        .unwrap_or_else(default_vtl2_settings),
3809                ),
3810                ide_controllers: None,
3811                vmbus_storage_controllers,
3812            },
3813            Firmware::Pcat {
3814                ide_controllers, ..
3815            } => PetriVmRuntimeConfig {
3816                vtl2_settings: None,
3817                ide_controllers: Some(ide_controllers),
3818                vmbus_storage_controllers,
3819            },
3820            Firmware::LinuxDirect { .. }
3821            | Firmware::IgvmLinuxDirect { .. }
3822            | Firmware::Uefi { .. } => PetriVmRuntimeConfig {
3823                vtl2_settings: None,
3824                ide_controllers: None,
3825                vmbus_storage_controllers,
3826            },
3827        }
3828    }
3829
3830    fn uefi_config(&self) -> Option<&UefiConfig> {
3831        match self {
3832            Firmware::Uefi { uefi_config, .. } | Firmware::OpenhclUefi { uefi_config, .. } => {
3833                Some(uefi_config)
3834            }
3835            Firmware::LinuxDirect { .. }
3836            | Firmware::IgvmLinuxDirect { .. }
3837            | Firmware::OpenhclLinuxDirect { .. }
3838            | Firmware::Pcat { .. }
3839            | Firmware::OpenhclPcat { .. } => None,
3840        }
3841    }
3842
3843    fn uefi_config_mut(&mut self) -> Option<&mut UefiConfig> {
3844        match self {
3845            Firmware::Uefi { uefi_config, .. } | Firmware::OpenhclUefi { uefi_config, .. } => {
3846                Some(uefi_config)
3847            }
3848            Firmware::LinuxDirect { .. }
3849            | Firmware::IgvmLinuxDirect { .. }
3850            | Firmware::OpenhclLinuxDirect { .. }
3851            | Firmware::Pcat { .. }
3852            | Firmware::OpenhclPcat { .. } => None,
3853        }
3854    }
3855
3856    fn mshv_boot(&self) -> Option<&MshvBoot> {
3857        match self {
3858            Firmware::Uefi {
3859                guest: UefiGuest::Mshv(boot),
3860                ..
3861            } => Some(boot),
3862            _ => None,
3863        }
3864    }
3865
3866    fn boot_drive(
3867        &self,
3868        use_virtio_vsock: bool,
3869        prepared: Option<&PetriInitrd>,
3870    ) -> anyhow::Result<Option<Drive>> {
3871        if let Firmware::Uefi {
3872            guest: UefiGuest::Mshv(boot),
3873            ..
3874        }
3875        | Firmware::OpenhclUefi {
3876            guest: UefiGuest::Mshv(boot),
3877            ..
3878        } = self
3879        {
3880            return Ok(Some(Drive::new(
3881                Some(
3882                    boot.build(use_virtio_vsock, prepared)
3883                        .context("composing mshv boot disk")?,
3884                ),
3885                false,
3886            )));
3887        }
3888        Ok(match self {
3889            Firmware::LinuxDirect { .. }
3890            | Firmware::IgvmLinuxDirect { .. }
3891            | Firmware::OpenhclLinuxDirect { .. } => None,
3892            Firmware::Pcat { guest, .. } | Firmware::OpenhclPcat { guest, .. } => {
3893                Some((guest.disk_path(), guest.is_dvd()))
3894            }
3895            Firmware::Uefi { guest, .. } | Firmware::OpenhclUefi { guest, .. } => {
3896                guest.disk_path().map(|dp| (dp, false))
3897            }
3898        }
3899        .map(|(disk_path, is_dvd)| Drive::new(Some(Disk::Differencing(disk_path)), is_dvd)))
3900    }
3901
3902    fn vtl2_settings(&mut self) -> Option<&mut Vtl2Settings> {
3903        self.openhcl_config_mut()
3904            .map(|c| c.vtl2_settings.get_or_insert_with(default_vtl2_settings))
3905    }
3906
3907    fn ide_controllers(&self) -> Option<&[[Option<Drive>; 2]; 2]> {
3908        match self {
3909            Firmware::Pcat {
3910                ide_controllers, ..
3911            } => Some(ide_controllers),
3912            _ => None,
3913        }
3914    }
3915
3916    fn ide_controllers_mut(&mut self) -> Option<&mut [[Option<Drive>; 2]; 2]> {
3917        match self {
3918            Firmware::Pcat {
3919                ide_controllers, ..
3920            } => Some(ide_controllers),
3921            _ => None,
3922        }
3923    }
3924}
3925
3926/// The guest the VM will boot into. A boot drive with the chosen setup
3927/// will be automatically configured.
3928#[derive(Debug, Clone)]
3929pub enum PcatGuest {
3930    /// Mount a VHD as the boot drive.
3931    Vhd(BootImageConfig<boot_image_type::Vhd>),
3932    /// Mount an ISO as the CD/DVD drive.
3933    Iso(BootImageConfig<boot_image_type::Iso>),
3934}
3935
3936impl PcatGuest {
3937    fn disk_path(&self) -> DiskPath {
3938        match self {
3939            PcatGuest::Vhd(disk) => disk.disk_path(),
3940            PcatGuest::Iso(disk) => disk.disk_path(),
3941        }
3942    }
3943
3944    fn is_dvd(&self) -> bool {
3945        matches!(self, Self::Iso(_))
3946    }
3947}
3948
3949/// The guest the VM will boot into. A boot drive with the chosen setup
3950/// will be automatically configured.
3951#[derive(Debug, Clone)]
3952pub enum UefiGuest {
3953    /// Compose an mshv root-partition boot disk from resolved artifacts and a
3954    /// prepared initrd. Requires x86-64 UEFI without OpenHCL.
3955    Mshv(MshvBoot),
3956    /// Mount a VHD as the boot drive.
3957    Vhd(BootImageConfig<boot_image_type::Vhd>),
3958    /// The UEFI test image produced by our guest-test infrastructure.
3959    GuestTestUefi(ResolvedArtifact),
3960    /// No guest, just the firmware.
3961    None,
3962}
3963
3964impl UefiGuest {
3965    /// Construct a standard [`UefiGuest::GuestTestUefi`] configuration.
3966    pub fn guest_test_uefi(resolver: &ArtifactResolver<'_>, arch: MachineArch) -> Self {
3967        use petri_artifacts_vmm_test::artifacts::test_vhd::*;
3968        let artifact = match arch {
3969            MachineArch::X86_64 => resolver.require(GUEST_TEST_UEFI_X64).erase(),
3970            MachineArch::Aarch64 => resolver.require(GUEST_TEST_UEFI_AARCH64).erase(),
3971        };
3972        UefiGuest::GuestTestUefi(artifact)
3973    }
3974
3975    fn disk_path(&self) -> Option<DiskPath> {
3976        match self {
3977            UefiGuest::Vhd(vhd) => Some(vhd.disk_path()),
3978            UefiGuest::GuestTestUefi(p) => Some(DiskPath::Local(p.get().to_path_buf())),
3979            UefiGuest::None => None,
3980            UefiGuest::Mshv(_) => None,
3981        }
3982    }
3983}
3984
3985/// Type-tags for [`BootImageConfig`](super::BootImageConfig)
3986pub mod boot_image_type {
3987    mod private {
3988        pub trait Sealed {}
3989        impl Sealed for super::Vhd {}
3990        impl Sealed for super::Iso {}
3991    }
3992
3993    /// Private trait use to seal the set of artifact types BootImageType
3994    /// supports.
3995    pub trait BootImageType: private::Sealed {}
3996
3997    /// BootImageConfig for a VHD file
3998    #[derive(Debug, Clone)]
3999    pub enum Vhd {}
4000
4001    /// BootImageConfig for an ISO file
4002    #[derive(Debug, Clone)]
4003    pub enum Iso {}
4004
4005    impl BootImageType for Vhd {}
4006    impl BootImageType for Iso {}
4007}
4008
4009/// Configuration information for the boot drive of the VM.
4010#[derive(Debug, Clone)]
4011pub struct BootImageConfig<T: boot_image_type::BootImageType> {
4012    /// Artifact source corresponding to the boot media (local or remote).
4013    artifact: ResolvedArtifactSource,
4014    /// The OS flavor.
4015    os_flavor: OsFlavor,
4016    /// Any quirks needed to boot the guest.
4017    ///
4018    /// Most guests should not need any quirks, and can use `Default`.
4019    quirks: GuestQuirks,
4020    /// Marker denoting what type of media `artifact` corresponds to
4021    _type: core::marker::PhantomData<T>,
4022}
4023
4024impl<T: boot_image_type::BootImageType> BootImageConfig<T> {
4025    /// Get a [`DiskPath`] from the artifact source.
4026    fn disk_path(&self) -> DiskPath {
4027        match self.artifact.get() {
4028            ArtifactSource::Local(p) => DiskPath::Local(p.clone()),
4029            ArtifactSource::Remote { url } => DiskPath::Remote { url: url.clone() },
4030        }
4031    }
4032}
4033
4034impl BootImageConfig<boot_image_type::Vhd> {
4035    /// Create a new BootImageConfig from a VHD artifact source
4036    pub fn from_vhd<A>(artifact: ResolvedArtifactSource<A>) -> Self
4037    where
4038        A: petri_artifacts_common::tags::IsTestVhd,
4039    {
4040        BootImageConfig {
4041            artifact: artifact.erase(),
4042            os_flavor: A::OS_FLAVOR,
4043            quirks: A::quirks(),
4044            _type: std::marker::PhantomData,
4045        }
4046    }
4047}
4048
4049impl BootImageConfig<boot_image_type::Iso> {
4050    /// Create a new BootImageConfig from an ISO artifact source
4051    pub fn from_iso<A>(artifact: ResolvedArtifactSource<A>) -> Self
4052    where
4053        A: petri_artifacts_common::tags::IsTestIso,
4054    {
4055        BootImageConfig {
4056            artifact: artifact.erase(),
4057            os_flavor: A::OS_FLAVOR,
4058            quirks: A::quirks(),
4059            _type: std::marker::PhantomData,
4060        }
4061    }
4062}
4063
4064/// Isolation type
4065#[derive(Debug, Clone, Copy)]
4066pub enum IsolationType {
4067    /// VBS
4068    Vbs,
4069    /// SNP
4070    Snp,
4071    /// TDX
4072    Tdx,
4073}
4074
4075/// Flags controlling servicing behavior.
4076#[derive(Debug, Clone, Copy)]
4077pub struct OpenHclServicingFlags {
4078    /// Preserve DMA memory for NVMe devices if supported.
4079    /// Defaults to `true`.
4080    pub enable_nvme_keepalive: bool,
4081    /// Preserve DMA memory for MANA devices if supported.
4082    pub enable_mana_keepalive: bool,
4083    /// Skip any logic that the vmm may have to ignore servicing updates if the supplied igvm file version is not different than the one currently running.
4084    pub override_version_checks: bool,
4085    /// Hint to the OpenHCL runtime how much time to wait when stopping / saving the OpenHCL.
4086    pub stop_timeout_hint_secs: Option<u16>,
4087}
4088
4089/// Where a disk image is located.
4090#[derive(Debug, Clone)]
4091pub enum DiskPath {
4092    /// A local file path.
4093    Local(PathBuf),
4094    /// A remote URL (fetched on demand via HTTP Range requests).
4095    Remote {
4096        /// The URL where the disk can be fetched.
4097        url: String,
4098    },
4099}
4100
4101impl From<PathBuf> for DiskPath {
4102    fn from(path: PathBuf) -> Self {
4103        DiskPath::Local(path)
4104    }
4105}
4106
4107/// Petri disk
4108#[derive(Debug, Clone)]
4109pub enum Disk {
4110    /// Memory backed with specified size
4111    Memory(u64),
4112    /// Memory differencing disk backed by a VHD (local or remote)
4113    Differencing(DiskPath),
4114    /// Differencing disk backed by a VHD (local or remote) that stores writes
4115    /// in a SQLite file, so they persist across VM worker processes. The file
4116    /// is created on first use.
4117    SqliteDifferencing {
4118        /// The base disk.
4119        base: DiskPath,
4120        /// The SQLite file that stores the writes.
4121        dbhd_path: PathBuf,
4122    },
4123    /// Persistent VHD
4124    Persistent(PathBuf),
4125    /// Disk backed by a temporary VHD
4126    Temporary(Arc<TempPath>),
4127}
4128
4129/// A path that can be either temporary or persistent
4130#[derive(Debug, Clone)]
4131pub enum TempOrPersistentPath {
4132    /// Temporary path
4133    Temp(Arc<TempPath>),
4134    /// Persistent path
4135    Persistent(PathBuf),
4136}
4137
4138impl AsRef<Path> for TempOrPersistentPath {
4139    fn as_ref(&self) -> &Path {
4140        match self {
4141            TempOrPersistentPath::Temp(temp_path) => temp_path.as_ref(),
4142            TempOrPersistentPath::Persistent(path_buf) => path_buf.as_ref(),
4143        }
4144    }
4145}
4146
4147/// Petri initrd
4148#[derive(Debug, Clone)]
4149pub struct PetriInitrd {
4150    /// Where the initrd is located on the host system.
4151    pub path: TempOrPersistentPath,
4152    /// Path to use with `rdinit=` kernel command line parameter.
4153    pub rdinit_param: String,
4154}
4155
4156/// Petri VMGS disk
4157#[derive(Debug, Clone)]
4158pub struct PetriVmgsDisk {
4159    /// Backing disk
4160    pub disk: Disk,
4161    /// Guest state encryption policy
4162    pub encryption_policy: GuestStateEncryptionPolicy,
4163}
4164
4165impl Default for PetriVmgsDisk {
4166    fn default() -> Self {
4167        PetriVmgsDisk {
4168            disk: Disk::Memory(vmgs_format::VMGS_DEFAULT_CAPACITY),
4169            // TODO: make this strict once we can set it in OpenHCL on Hyper-V
4170            encryption_policy: GuestStateEncryptionPolicy::None(false),
4171        }
4172    }
4173}
4174
4175/// Petri VM guest state resource
4176#[derive(Debug, Clone)]
4177pub enum PetriVmgsResource {
4178    /// Use disk to store guest state
4179    Disk(PetriVmgsDisk),
4180    /// Use disk to store guest state, reformatting if corrupted.
4181    ReprovisionOnFailure(PetriVmgsDisk),
4182    /// Format and use disk to store guest state
4183    ReprovisionSingle(PetriVmgsDisk),
4184    /// Store guest state in memory
4185    Ephemeral,
4186}
4187
4188impl PetriVmgsResource {
4189    /// get the inner vmgs disk if one exists
4190    pub fn vmgs(&self) -> Option<&PetriVmgsDisk> {
4191        match self {
4192            PetriVmgsResource::Disk(vmgs)
4193            | PetriVmgsResource::ReprovisionOnFailure(vmgs)
4194            | PetriVmgsResource::ReprovisionSingle(vmgs) => Some(vmgs),
4195            PetriVmgsResource::Ephemeral => None,
4196        }
4197    }
4198
4199    /// get the inner disk if one exists
4200    pub fn disk(&self) -> Option<&Disk> {
4201        self.vmgs().map(|vmgs| &vmgs.disk)
4202    }
4203
4204    /// get the encryption policy of the vmgs
4205    pub fn encryption_policy(&self) -> Option<GuestStateEncryptionPolicy> {
4206        self.vmgs().map(|vmgs| vmgs.encryption_policy)
4207    }
4208}
4209
4210/// Petri VM guest state lifetime
4211#[derive(Debug, Clone, Copy)]
4212pub enum PetriGuestStateLifetime {
4213    /// Use a differencing disk backed by a blank, tempory VMGS file
4214    /// or other artifact if one is provided
4215    Disk,
4216    /// Same as default, except reformat the backing disk if corrupted
4217    ReprovisionOnFailure,
4218    /// Same as default, except reformat the backing disk
4219    ReprovisionSingle,
4220    /// Store guest state in memory (no backing disk)
4221    Ephemeral,
4222}
4223
4224/// UEFI secure boot template
4225#[derive(Debug, Clone, Copy)]
4226pub enum SecureBootTemplate {
4227    /// The Microsoft Windows template.
4228    MicrosoftWindows,
4229    /// The Microsoft UEFI certificate authority template.
4230    MicrosoftUefiCertificateAuthority,
4231}
4232
4233/// Quirks to workaround certain bugs that only manifest when using a
4234/// particular VMM, and do not depend on which guest is running.
4235#[derive(Default, Debug, Clone)]
4236pub struct VmmQuirks {
4237    /// Automatically reset the VM if we did not recieve a boot event in the
4238    /// specified amount of time.
4239    pub flaky_boot: Option<Duration>,
4240}
4241
4242/// The reason that the VM halted
4243#[derive(Debug, Clone, Copy, Eq, PartialEq)]
4244pub enum PetriHaltReason {
4245    /// The vm powered off
4246    PowerOff,
4247    /// The vm reset
4248    Reset,
4249    /// The vm hibernated
4250    Hibernate,
4251    /// The vm triple faulted
4252    TripleFault,
4253    /// The vm halted for some other reason
4254    Other,
4255}
4256
4257impl PetriHaltReason {
4258    /// Construct a halt reason with detailed debug info
4259    pub fn with_detail(self, detail: String) -> PetriHaltReasonDetail {
4260        PetriHaltReasonDetail {
4261            reason: self,
4262            detail,
4263        }
4264    }
4265}
4266
4267/// The reason that the VM halted, with optional addition debug details
4268#[derive(Debug, Clone)]
4269pub struct PetriHaltReasonDetail {
4270    /// The reason for the halt
4271    pub reason: PetriHaltReason,
4272    /// More details about the halt
4273    pub detail: String,
4274}
4275
4276pub(crate) fn linux_vsock_blacklist(use_virtio_vsock: bool) -> &'static str {
4277    if use_virtio_vsock {
4278        "initcall_blacklist=hv_sock_init"
4279    } else {
4280        "initcall_blacklist=virtio_vsock_init"
4281    }
4282}
4283
4284fn append_cmdline(cmd: &mut Option<String>, add_cmd: impl AsRef<str>) {
4285    if let Some(cmd) = cmd.as_mut() {
4286        cmd.push(' ');
4287        cmd.push_str(add_cmd.as_ref());
4288    } else {
4289        *cmd = Some(add_cmd.as_ref().to_string());
4290    }
4291}
4292
4293async fn collect_inspect(
4294    name: &'static str,
4295    inspect: impl Future<Output = anyhow::Result<inspect::Node>>,
4296    log_source: &PetriLogSource,
4297    prefix: &str,
4298) {
4299    let node = match CancelContext::new()
4300        .with_timeout(INSPECT_TIMEOUT)
4301        .until_cancelled(inspect)
4302        .await
4303    {
4304        Ok(Ok(node)) => node,
4305        Ok(Err(e)) => {
4306            tracing::warn!(name, ?e, "failed to collect inspect state");
4307            return;
4308        }
4309        Err(_) => {
4310            tracing::warn!(name, "timed out collecting inspect state");
4311            return;
4312        }
4313    };
4314
4315    if let Err(e) = log_source.write_attachment(
4316        &format!("{prefix}_inspect_{name}.log"),
4317        format!("{node:#}").as_bytes(),
4318    ) {
4319        tracing::error!(name, ?e, "failed to save inspect log");
4320    }
4321}
4322
4323/// Wrapper for modification functions with stubbed out debug impl
4324pub struct ModifyFn<T>(pub Box<dyn FnOnce(T) -> T + Send>);
4325
4326impl<T> Debug for ModifyFn<T> {
4327    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4328        f.debug_tuple("ModifyFn").finish_non_exhaustive()
4329    }
4330}
4331
4332/// Default VTL 2 settings used by petri
4333fn default_vtl2_settings() -> Vtl2Settings {
4334    Vtl2Settings {
4335        version: vtl2_settings_proto::vtl2_settings_base::Version::V1.into(),
4336        fixed: None,
4337        dynamic: Some(Default::default()),
4338        namespace_settings: Default::default(),
4339    }
4340}
4341
4342/// Virtual trust level
4343#[derive(Debug, Copy, Clone, PartialEq, Eq)]
4344pub enum Vtl {
4345    /// VTL 0
4346    Vtl0 = 0,
4347    /// VTL 1
4348    Vtl1 = 1,
4349    /// VTL 2
4350    Vtl2 = 2,
4351}
4352
4353/// The VMBus storage device type.
4354#[derive(Debug, Copy, Clone, PartialEq, Eq)]
4355pub enum VmbusStorageType {
4356    /// SCSI
4357    Scsi,
4358    /// NVMe
4359    Nvme,
4360    /// Virtio block device
4361    VirtioBlk,
4362}
4363
4364/// VM disk drive
4365#[derive(Debug, Clone)]
4366pub struct Drive {
4367    /// Backing disk
4368    pub disk: Option<Disk>,
4369    /// Whether this is a DVD
4370    pub is_dvd: bool,
4371}
4372
4373impl Drive {
4374    /// Create a new disk
4375    pub fn new(disk: Option<Disk>, is_dvd: bool) -> Self {
4376        Self { disk, is_dvd }
4377    }
4378}
4379
4380/// VMBus storage controller
4381#[derive(Debug, Clone)]
4382pub struct VmbusStorageController {
4383    /// The VTL to assign the storage controller to
4384    pub target_vtl: Vtl,
4385    /// The storage device type
4386    pub controller_type: VmbusStorageType,
4387    /// Drives (with any inserted disks) attached to this storage controller
4388    pub drives: HashMap<u32, Drive>,
4389}
4390
4391impl VmbusStorageController {
4392    /// Create a new storage controller
4393    pub fn new(target_vtl: Vtl, controller_type: VmbusStorageType) -> Self {
4394        Self {
4395            target_vtl,
4396            controller_type,
4397            drives: HashMap::new(),
4398        }
4399    }
4400
4401    /// Add a disk to the storage controller
4402    pub fn set_drive(
4403        &mut self,
4404        lun: Option<u32>,
4405        drive: Drive,
4406        allow_modify_existing: bool,
4407    ) -> u32 {
4408        let lun = lun.unwrap_or_else(|| {
4409            // find the first available lun
4410            let mut lun = None;
4411            for x in 0..u8::MAX as u32 {
4412                if !self.drives.contains_key(&x) {
4413                    lun = Some(x);
4414                    break;
4415                }
4416            }
4417            lun.expect("all locations on this controller are in use")
4418        });
4419
4420        if self.drives.insert(lun, drive).is_some() && !allow_modify_existing {
4421            panic!("a disk with lun {lun} already existed on this controller");
4422        }
4423
4424        lun
4425    }
4426}
4427
4428/// Returns the cache directory for lazy-fetched disk artifacts.
4429pub(crate) fn petri_disk_cache_dir() -> String {
4430    if let Ok(dir) = std::env::var("PETRI_CACHE_DIR") {
4431        return dir;
4432    }
4433
4434    #[cfg(target_os = "macos")]
4435    {
4436        if let Some(home) = std::env::home_dir() {
4437            return home.join("Library/Caches/petri").display().to_string();
4438        }
4439    }
4440
4441    #[cfg(windows)]
4442    {
4443        if let Ok(local) = std::env::var("LOCALAPPDATA") {
4444            return format!("{local}\\petri\\cache");
4445        }
4446    }
4447
4448    // Linux / fallback: XDG
4449    if let Ok(xdg) = std::env::var("XDG_CACHE_HOME") {
4450        return format!("{xdg}/petri");
4451    }
4452    if let Some(home) = std::env::home_dir() {
4453        return home.join(".cache/petri").display().to_string();
4454    }
4455
4456    ".cache/petri".to_string()
4457}
4458
4459/// All the information needed to locate and run a particular Nextest test
4460pub struct NestedTestDeps {
4461    /// Nextest archive artifact
4462    pub archive: ErasedArtifactHandle,
4463    /// Binary name within the nextest artifact
4464    pub binary: String,
4465    /// Test name within the binary
4466    pub test_name: String,
4467}
4468
4469impl NestedTestDeps {
4470    /// Create a new set of nested test dep arguments
4471    pub fn new<A: IsNextestArchive>(
4472        archive: ArtifactHandle<A>,
4473        binary: &str,
4474        test_name: &str,
4475    ) -> Self {
4476        Self {
4477            archive: archive.erase(),
4478            binary: binary.into(),
4479            test_name: test_name.into(),
4480        }
4481    }
4482}
4483
4484/// All the information needed to locate and run a particular Nextest test
4485#[derive(Debug)]
4486pub struct ResolvedNestedTestDeps {
4487    /// Extracted test binary
4488    pub test_binary: TempPath,
4489    /// Test name within the binary
4490    pub test_name: String,
4491    /// Artifacts required by the test
4492    pub artifacts: Vec<(ErasedArtifactHandle, PathBuf)>,
4493}
4494
4495mod nextest_binaries_metadata_schema {
4496    use serde::Deserialize;
4497    use serde::Serialize;
4498    use std::collections::HashMap;
4499    use std::path::PathBuf;
4500
4501    #[derive(Serialize, Deserialize)]
4502    #[serde(rename_all = "kebab-case")]
4503    pub struct RustBuildMeta {
4504        pub target_directory: PathBuf,
4505    }
4506
4507    #[derive(Serialize, Deserialize)]
4508    #[serde(rename_all = "kebab-case")]
4509    pub struct Binary {
4510        pub binary_name: String,
4511        pub binary_path: PathBuf,
4512    }
4513
4514    #[derive(Serialize, Deserialize)]
4515    #[serde(rename_all = "kebab-case")]
4516    pub struct BinariesMetadata {
4517        pub rust_build_meta: RustBuildMeta,
4518        pub rust_binaries: HashMap<String, Binary>,
4519    }
4520}
4521
4522impl NestedTestDeps {
4523    /// Extract the binary from the archive by parsing the json metadata
4524    fn extract_binary(&self) -> anyhow::Result<TempPath> {
4525        let temp_dir = tempfile::tempdir()?;
4526
4527        // We need to resolve this manually since we need to get the nested test
4528        // artifacts and to do that we need the archive first.
4529        let archive = resolve_artifact(self.archive)?;
4530
4531        let mut cmd = std::process::Command::new("tar");
4532        cmd.arg("--zstd")
4533            .arg("-xvf")
4534            .arg(archive)
4535            .current_dir(&temp_dir);
4536        futures::executor::block_on(crate::run_host_cmd(cmd))?;
4537
4538        let meta_file = fs_err::File::open(
4539            temp_dir
4540                .path()
4541                .join("target")
4542                .join("nextest")
4543                .join("binaries-metadata.json"),
4544        )?;
4545        let meta: nextest_binaries_metadata_schema::BinariesMetadata =
4546            serde_json::from_reader(meta_file)?;
4547
4548        let build_binary_path = meta
4549            .rust_binaries
4550            .iter()
4551            .find(|(_, b)| b.binary_name == self.binary)
4552            .context("binary missing")?
4553            .1
4554            .binary_path
4555            .clone();
4556
4557        let local_binary_path = temp_dir.path().join(
4558            build_binary_path
4559                .strip_prefix(meta.rust_build_meta.target_directory.parent().unwrap())?,
4560        );
4561
4562        // copy the binary under the test content dir so it can be shared with the guest
4563        let test_content_temp_dir =
4564            PathBuf::from(std::env::var(VMM_TESTS_CONTENT_DIR)?).join(NESTED_TEMP_DIR);
4565        fs_err::create_dir_all(&test_content_temp_dir)?;
4566        let temp_path = tempfile::NamedTempFile::new_in(&test_content_temp_dir)
4567            .context("failed to create temp nested test")?
4568            .into_temp_path();
4569
4570        fs_err::copy(&local_binary_path, &temp_path)?;
4571
4572        Ok(temp_path)
4573    }
4574
4575    fn resolve(&self, discover_artifacts: bool) -> anyhow::Result<ResolvedNestedTestDeps> {
4576        let test_binary = self
4577            .extract_binary()
4578            .context("failed to extract nextest binary")?;
4579
4580        let artifacts = if discover_artifacts {
4581            petri_artifacts_core::query_test_binary_artifacts(&test_binary, &[&self.test_name])
4582                .context("failed to query test binary for artifacts")?
4583                .into_artifacts_list()
4584                .into_iter()
4585                .filter(|id| {
4586                    id != petri_artifacts_common::artifacts::TEST_LOG_DIRECTORY::GLOBAL_UNIQUE_ID
4587                })
4588                .map(|id| {
4589                    let handle = petri_artifacts_core::artifact_from_id(&id)
4590                        .with_context(|| format!("unknown artifact handle: {id}"))?;
4591                    Ok((handle, resolve_artifact(handle)?))
4592                })
4593                .collect::<anyhow::Result<Vec<_>>>()?
4594        } else {
4595            Vec::new()
4596        };
4597
4598        Ok(ResolvedNestedTestDeps {
4599            test_binary,
4600            test_name: self.test_name.clone(),
4601            artifacts,
4602        })
4603    }
4604}
4605
4606trait PetriGuestPaths {
4607    /// Get the OS flavor
4608    fn os_flavor(&self) -> OsFlavor;
4609
4610    /// Get the path separator
4611    fn path_separator(&self) -> &'static str {
4612        match self.os_flavor() {
4613            OsFlavor::Windows => "\\",
4614            _ => "/",
4615        }
4616    }
4617
4618    /// Get the path to the agent disk, if it exists
4619    ///
4620    /// Does not include any subsequent path separators.
4621    fn agent_disk_root(&self) -> &'static str {
4622        match self.os_flavor() {
4623            OsFlavor::Windows => "D:",
4624            _ => "/cidata",
4625        }
4626    }
4627
4628    /// Construct a path with the appropriate path component separators for
4629    /// the guest.
4630    fn build_guest_path(&self, components: &[String]) -> String {
4631        components.join(self.path_separator())
4632    }
4633
4634    /// Construct a path with the appropriate path component separators for
4635    /// the guest from an existing host path.
4636    fn convert_guest_path(&self, path: &Path) -> String {
4637        self.build_guest_path(
4638            &path
4639                .iter()
4640                .map(|c| c.to_str().expect("path not utf8").to_string())
4641                .collect::<Vec<_>>(),
4642        )
4643    }
4644
4645    /// Returns the paths to each of the parent directories.
4646    fn parents<'a>(&self, path: &'a str) -> Vec<&'a str> {
4647        path.match_indices(self.path_separator())
4648            .map(|(x, _)| &path[0..x])
4649            .collect()
4650    }
4651
4652    /// Construct the path to a file in the agent disk.
4653    ///
4654    /// Panics if no agent disk exists.
4655    fn agent_disk_path(&self, components: &[String]) -> String {
4656        self.build_guest_path(&[&[self.agent_disk_root().into()], components].concat())
4657    }
4658
4659    /// Construct a binary name with the appropriate extension for the guest.
4660    fn binary_with_extension(&self, name: &str) -> String {
4661        match self.os_flavor() {
4662            OsFlavor::Windows => format!("{name}.exe"),
4663            _ => name.into(),
4664        }
4665    }
4666}
4667
4668struct FatFsPathBuilder(OsFlavor);
4669
4670impl PetriGuestPaths for FatFsPathBuilder {
4671    fn os_flavor(&self) -> OsFlavor {
4672        self.0
4673    }
4674
4675    fn path_separator(&self) -> &'static str {
4676        "/"
4677    }
4678}
4679
4680impl<T: PetriVmmBackend> PetriGuestPaths for PetriVm<T> {
4681    fn os_flavor(&self) -> OsFlavor {
4682        self.properties.os_flavor
4683    }
4684}
4685
4686impl<T: PetriVmmBackend> PetriGuestPaths for PetriVmBuilder<T> {
4687    fn os_flavor(&self) -> OsFlavor {
4688        self.os_flavor()
4689    }
4690}
4691
4692#[cfg(test)]
4693mod tests {
4694    use super::*;
4695    use crate::Drive;
4696    use crate::VmbusStorageController;
4697    use crate::VmbusStorageType;
4698    use crate::Vtl;
4699
4700    #[derive(Clone, Copy)]
4701    enum TestInspectBehavior {
4702        Success,
4703        Error,
4704        Panic,
4705    }
4706
4707    #[derive(Clone)]
4708    struct TestInspector(TestInspectBehavior);
4709
4710    #[async_trait::async_trait]
4711    impl PetriVmInspector for TestInspector {
4712        async fn inspect(&self, _path: &str) -> anyhow::Result<inspect::Node> {
4713            match self.0 {
4714                TestInspectBehavior::Success => Ok(inspect::Node::Unevaluated),
4715                TestInspectBehavior::Error => anyhow::bail!("inspect failed"),
4716                TestInspectBehavior::Panic => panic!("inspect panicked"),
4717            }
4718        }
4719    }
4720
4721    struct TestFramebuffer;
4722
4723    #[async_trait::async_trait]
4724    impl PetriVmFramebufferAccess for TestFramebuffer {
4725        async fn screenshot(
4726            &mut self,
4727            _image: &mut Vec<u8>,
4728        ) -> anyhow::Result<Option<VmScreenshotMeta>> {
4729            unreachable!()
4730        }
4731    }
4732
4733    struct TestRuntime(TestInspectBehavior);
4734
4735    #[async_trait::async_trait]
4736    impl PetriVmRuntime for TestRuntime {
4737        type VmInspector = TestInspector;
4738        type VmFramebufferAccess = TestFramebuffer;
4739
4740        async fn teardown(self) -> anyhow::Result<()> {
4741            Ok(())
4742        }
4743
4744        async fn wait_for_halt(
4745            &mut self,
4746            _allow_reset: bool,
4747        ) -> anyhow::Result<PetriHaltReasonDetail> {
4748            unreachable!()
4749        }
4750
4751        async fn wait_for_agent(&mut self, _set_high_vtl: bool) -> anyhow::Result<PipetteClient> {
4752            unreachable!()
4753        }
4754
4755        fn openhcl_diag(&self) -> Option<OpenHclDiagHandler> {
4756            None
4757        }
4758
4759        async fn wait_for_boot_event(
4760            &mut self,
4761            _timeout: Option<Duration>,
4762        ) -> anyhow::Result<Option<FirmwareEvent>> {
4763            unreachable!()
4764        }
4765
4766        async fn wait_for_enlightened_shutdown_ready(&mut self) -> anyhow::Result<()> {
4767            unreachable!()
4768        }
4769
4770        async fn send_enlightened_shutdown(&mut self, _kind: ShutdownKind) -> anyhow::Result<()> {
4771            unreachable!()
4772        }
4773
4774        async fn restart_openhcl(
4775            &mut self,
4776            _new_openhcl: &ResolvedArtifact,
4777            _flags: OpenHclServicingFlags,
4778        ) -> anyhow::Result<()> {
4779            unreachable!()
4780        }
4781
4782        async fn save_openhcl(
4783            &mut self,
4784            _new_openhcl: &ResolvedArtifact,
4785            _flags: OpenHclServicingFlags,
4786        ) -> anyhow::Result<()> {
4787            unreachable!()
4788        }
4789
4790        async fn restore_openhcl(&mut self) -> anyhow::Result<()> {
4791            unreachable!()
4792        }
4793
4794        async fn update_command_line(&mut self, _command_line: &str) -> anyhow::Result<()> {
4795            unreachable!()
4796        }
4797
4798        fn inspector(&self) -> Option<Self::VmInspector> {
4799            Some(TestInspector(self.0))
4800        }
4801
4802        async fn reset(&mut self) -> anyhow::Result<()> {
4803            unreachable!()
4804        }
4805
4806        async fn set_vtl2_settings(&mut self, _settings: &Vtl2Settings) -> anyhow::Result<()> {
4807            unreachable!()
4808        }
4809
4810        async fn set_vmbus_drive(
4811            &mut self,
4812            _disk: &Drive,
4813            _controller_id: &Guid,
4814            _controller_location: u32,
4815        ) -> anyhow::Result<()> {
4816            unreachable!()
4817        }
4818    }
4819
4820    fn test_runtime_guard(
4821        driver: DefaultDriver,
4822        log_source: &PetriLogSource,
4823        behavior: TestInspectBehavior,
4824    ) -> PetriVmRuntimeGuard<TestRuntime> {
4825        PetriVmRuntimeGuard {
4826            runtime: Some(TestRuntime(behavior)),
4827            driver,
4828            log_source: log_source.clone(),
4829            capture_inspect_on_drop: true,
4830        }
4831    }
4832
4833    fn run_failed_test(
4834        log_source: &PetriLogSource,
4835        behavior: TestInspectBehavior,
4836    ) -> anyhow::Result<()> {
4837        let pool = pal_async::DefaultPool::new();
4838        let driver = pool.driver();
4839        drop(test_runtime_guard(driver.clone(), log_source, behavior));
4840        drop(driver);
4841        pool.run();
4842        anyhow::bail!("original test failure")
4843    }
4844
4845    fn inspect_attachment_count(log_source: &PetriLogSource) -> usize {
4846        fs_err::read_dir(log_source.output_dir())
4847            .unwrap()
4848            .filter_map(Result::ok)
4849            .filter(|entry| {
4850                entry
4851                    .file_name()
4852                    .to_string_lossy()
4853                    .starts_with("failure_inspect_vmm")
4854            })
4855            .count()
4856    }
4857
4858    #[test]
4859    fn test_runtime_guard_failure_capture() {
4860        let temp_dir = tempfile::tempdir().unwrap();
4861        let log_source = crate::tracing::try_init_tracing(
4862            temp_dir.path(),
4863            tracing::level_filters::LevelFilter::DEBUG,
4864            None,
4865        )
4866        .unwrap();
4867
4868        let error = run_failed_test(&log_source, TestInspectBehavior::Success).unwrap_err();
4869        assert_eq!(error.to_string(), "original test failure");
4870        assert_eq!(inspect_attachment_count(&log_source), 1);
4871
4872        let pool = pal_async::DefaultPool::new();
4873        let driver = pool.driver();
4874        let mut guard =
4875            test_runtime_guard(driver.clone(), &log_source, TestInspectBehavior::Success);
4876        let _runtime = guard.take_for_teardown();
4877        drop(guard);
4878        drop(driver);
4879        pool.run();
4880        assert_eq!(inspect_attachment_count(&log_source), 1);
4881
4882        for behavior in [TestInspectBehavior::Error, TestInspectBehavior::Panic] {
4883            let error = run_failed_test(&log_source, behavior).unwrap_err();
4884            assert_eq!(error.to_string(), "original test failure");
4885            assert_eq!(inspect_attachment_count(&log_source), 1);
4886        }
4887    }
4888
4889    #[test]
4890    fn test_vmbus_storage_controller() {
4891        let mut controller = VmbusStorageController::new(Vtl::Vtl0, VmbusStorageType::Scsi);
4892        assert_eq!(
4893            controller.set_drive(Some(1), Drive::new(None, false), false),
4894            1
4895        );
4896        assert!(controller.drives.contains_key(&1));
4897        assert_eq!(
4898            controller.set_drive(None, Drive::new(None, false), false),
4899            0
4900        );
4901        assert!(controller.drives.contains_key(&0));
4902        assert_eq!(
4903            controller.set_drive(None, Drive::new(None, false), false),
4904            2
4905        );
4906        assert!(controller.drives.contains_key(&2));
4907        assert_eq!(
4908            controller.set_drive(Some(0), Drive::new(None, false), true),
4909            0
4910        );
4911        assert!(controller.drives.contains_key(&0));
4912    }
4913}