Skip to main content

openvmm_entry/
lib.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! This module implements the interactive control process and the entry point
5//! for the worker process.
6
7#![expect(missing_docs)]
8#![forbid(unsafe_code)]
9
10mod cli_args;
11mod crash_dump;
12mod kvp;
13mod meshworker;
14mod pidfile;
15mod repl;
16mod serial_io;
17mod storage_builder;
18mod tracing_init;
19mod ttrpc;
20mod usb;
21mod vm_controller;
22
23// `pub` so that the missing_docs warning fires for options without
24// documentation.
25pub use cli_args::Options;
26use console_relay::ConsoleLaunchOptions;
27
28use crate::cli_args::SecureBootTemplateCli;
29use anyhow::Context;
30use anyhow::bail;
31use chipset_resources::acpi_power_button::PowerButtonRpc;
32use chipset_resources::battery::HostBatteryUpdate;
33use cli_args::DiskCliKind;
34use cli_args::EfiDiagnosticsLogLevelCli;
35use cli_args::EndpointConfigCli;
36use cli_args::IgvmPersonalityCli;
37use cli_args::NicConfigCli;
38use cli_args::ProvisionCondition;
39use cli_args::SerialConfigCli;
40use cli_args::TpmVersionCli;
41use cli_args::UefiConsoleModeCli;
42use cli_args::VirtioBusCli;
43use crash_dump::spawn_dump_handler;
44use cxl::test::CxlTestDeviceHandle;
45use disk_backend_resources::DelayDiskHandle;
46use disk_backend_resources::DiskLayerDescription;
47use disk_backend_resources::layer::DiskLayerHandle;
48use disk_backend_resources::layer::RamDiskLayerHandle;
49use disk_backend_resources::layer::SqliteAutoCacheDiskLayerHandle;
50use disk_backend_resources::layer::SqliteDiskLayerHandle;
51use floppy_resources::FloppyDiskConfig;
52use framebuffer::FRAMEBUFFER_SIZE;
53use framebuffer::FramebufferAccess;
54use futures::AsyncReadExt;
55use futures::AsyncWrite;
56use futures::StreamExt;
57use futures::executor::block_on;
58use futures::io::AllowStdIo;
59use gdma_resources::GdmaDeviceHandle;
60use gdma_resources::VportDefinition;
61use guid::Guid;
62use input_core::MultiplexedInputHandle;
63use inspect::InspectMut;
64use mesh::CancelContext;
65use mesh::CellUpdater;
66use mesh::rpc::RpcSend;
67use meshworker::VmmMesh;
68use net_backend_resources::mac_address::MacAddress;
69use nvme_resources::NvmeControllerRequest;
70use openvmm_defs::config::Config;
71use openvmm_defs::config::DEFAULT_ACPI_POWER_BUTTON_IRQ_X64;
72use openvmm_defs::config::DEFAULT_ACPI_POWER_BUTTON_SPI_AARCH64;
73use openvmm_defs::config::DEFAULT_PCAT_BOOT_ORDER;
74use openvmm_defs::config::DeviceVtl;
75use openvmm_defs::config::HypervisorConfig;
76use openvmm_defs::config::IgvmPersonality;
77use openvmm_defs::config::LateMapVtl0MemoryPolicy;
78use openvmm_defs::config::LoadMode;
79use openvmm_defs::config::MemoryConfig;
80use openvmm_defs::config::NumaDistance;
81use openvmm_defs::config::NumaNode;
82use openvmm_defs::config::NumaTopology;
83use openvmm_defs::config::PcieDeviceConfig;
84use openvmm_defs::config::PcieMmioRangeConfig;
85use openvmm_defs::config::PciePortConfig;
86use openvmm_defs::config::PcieRootComplexConfig;
87use openvmm_defs::config::PcieSwitchConfig;
88use openvmm_defs::config::ProcessorTopologyConfig;
89use openvmm_defs::config::RootComplexCxlConfig;
90use openvmm_defs::config::UartId;
91use openvmm_defs::config::VirtioBus;
92use openvmm_defs::config::VmbusConfig;
93use openvmm_defs::config::VpAssignment;
94use openvmm_defs::config::VpciDeviceConfig;
95use openvmm_defs::config::Vtl2BaseAddressType;
96use openvmm_defs::config::Vtl2Config;
97use openvmm_defs::rpc::VmRpc;
98use openvmm_defs::worker::GuestRamSource;
99use openvmm_defs::worker::VM_WORKER;
100use openvmm_defs::worker::VmWorkerParameters;
101use openvmm_helpers::config::supports_acpi_power_button;
102use openvmm_helpers::disk::OpenDiskOptions;
103use openvmm_helpers::disk::create_disk_type;
104use openvmm_helpers::disk::open_disk_type;
105use pal_async::DefaultDriver;
106use pal_async::DefaultPool;
107use pal_async::socket::PolledSocket;
108use pal_async::task::Spawn;
109use pal_async::task::Task;
110use serial_16550_resources::ComPort;
111use serial_core::resources::DisconnectedSerialBackendHandle;
112use serial_core::resources::NullSerialBackendHandle;
113use sparse_mmap::alloc_shared_memory;
114use std::cell::RefCell;
115use std::collections::BTreeMap;
116use std::collections::HashSet;
117use std::fmt::Write as _;
118use std::io;
119#[cfg(unix)]
120use std::io::IsTerminal;
121use std::io::Write;
122use std::net::TcpListener;
123use std::path::Path;
124use std::path::PathBuf;
125use std::sync::Arc;
126use std::thread;
127use std::time::Duration;
128use storvsp_resources::ScsiControllerRequest;
129use tpm_resources::TpmDeviceHandle;
130use tpm_resources::TpmRegisterLayout;
131use tpm_resources::TpmVersion;
132use uidevices_resources::SynthKeyboardHandle;
133use uidevices_resources::SynthMouseHandle;
134use uidevices_resources::SynthVideoHandle;
135use video_core::SharedFramebufferHandle;
136use virtio_resources::VirtioPciDeviceHandle;
137use vm_manifest_builder::BaseChipsetType;
138use vm_manifest_builder::MachineArch;
139use vm_manifest_builder::VmChipsetResult;
140use vm_manifest_builder::VmManifestBuilder;
141use vm_resource::IntoResource;
142use vm_resource::Resource;
143use vm_resource::kind::DiskHandleKind;
144use vm_resource::kind::DiskLayerHandleKind;
145use vm_resource::kind::NetEndpointHandleKind;
146use vm_resource::kind::NonVolatileStoreKind;
147use vm_resource::kind::VirtioDeviceHandle;
148use vm_resource::kind::VmbusDeviceHandleKind;
149use vmbus_serial_resources::VmbusSerialDeviceHandle;
150use vmbus_serial_resources::VmbusSerialPort;
151use vmcore::non_volatile_store::resources::EphemeralNonVolatileStoreHandle;
152use vmgs_resources::GuestStateEncryptionPolicy;
153use vmgs_resources::VmgsDisk;
154use vmgs_resources::VmgsFileHandle;
155use vmgs_resources::VmgsResource;
156use vmotherboard::ChipsetDeviceHandle;
157use vnc_worker_defs::VncParameters;
158
159pub fn openvmm_main() {
160    // Save the current state of the terminal so we can restore it back to
161    // normal before exiting.
162    #[cfg(unix)]
163    let orig_termios = io::stderr().is_terminal().then(term::get_termios);
164
165    let mut pidfile_guard: Option<pidfile::Pidfile> = None;
166    let exit_code = match do_main(&mut pidfile_guard) {
167        Ok(code) => code,
168        Err(err) => {
169            eprintln!("fatal error: {:?}", err);
170            1
171        }
172    };
173
174    // Restore the terminal to its initial state.
175    #[cfg(unix)]
176    if let Some(orig_termios) = orig_termios {
177        term::set_termios(orig_termios);
178    }
179
180    // Clean up the pidfile before terminating, since
181    // pal::process::terminate skips destructors.
182    drop(pidfile_guard);
183
184    // Terminate the process immediately without graceful shutdown of DLLs or
185    // C++ destructors or anything like that. This is all unnecessary and saves
186    // time on Windows.
187    //
188    // Do flush stdout, though, since there may be buffered data.
189    let _ = io::stdout().flush();
190    pal::process::terminate(exit_code);
191}
192
193#[derive(Default)]
194struct VmResources {
195    console_in: Option<Box<dyn AsyncWrite + Send + Unpin>>,
196    /// Keeps the dedicated serial reactor alive while serial I/O objects exist.
197    serial_driver: Option<DefaultDriver>,
198    framebuffer_access: Option<FramebufferAccess>,
199    shutdown_ic: Option<mesh::Sender<hyperv_ic_resources::shutdown::ShutdownRpc>>,
200    acpi_power_button: Option<mesh::Sender<PowerButtonRpc>>,
201    kvp_ic: Option<mesh::Sender<hyperv_ic_resources::kvp::KvpConnectRpc>>,
202    scsi_rpc: Option<mesh::Sender<ScsiControllerRequest>>,
203    nvme_vtl2_rpc: Option<mesh::Sender<NvmeControllerRequest>>,
204    consomme_rpc: Option<mesh::Sender<net_backend_resources::consomme::ConsommeRequest>>,
205    ged_rpc: Option<mesh::Sender<get_resources::ged::GuestEmulationRequest>>,
206    vtl2_settings: Option<vtl2_settings_proto::Vtl2Settings>,
207    /// Receives dirty rectangles from the synthetic video device for the VNC worker.
208    dirty_rect_recv: Option<mesh::Receiver<Vec<video_core::DirtyRect>>>,
209    #[cfg(windows)]
210    switch_ports: Vec<vmswitch::kernel::SwitchPort>,
211}
212
213struct ConsoleState<'a> {
214    device: &'a str,
215    input: Box<dyn AsyncWrite + Unpin + Send>,
216}
217
218/// Builds controller configurations from the USB command-line options. The
219/// controller resolver assigns omitted connectors and validates connectors.
220fn usb_controller_configs(
221    pcie_ports: &[cli_args::UsbXhciCli],
222    devices: &[cli_args::UsbDeviceCli],
223) -> anyhow::Result<Vec<(String, usb_config_resources::UsbControllerConfig)>> {
224    let mut controllers: Vec<_> = pcie_ports
225        .iter()
226        .map(|pcie_port| usb::UsbControllerSpec {
227            port_name: pcie_port.port_name.clone(),
228            devices: Vec::new(),
229            winusb_all: false,
230        })
231        .collect();
232    let default_pcie_port = if let [pcie_port] = pcie_ports {
233        Some(pcie_port.port_name.as_str())
234    } else {
235        None
236    };
237    for device in devices {
238        let pcie_port_name = device
239            .controller_pcie_port()
240            .or(default_pcie_port)
241            .context("on=PCIE_PORT is required unless exactly one xHCI controller is declared")?;
242        let controller = controllers
243            .iter_mut()
244            .find(|controller| controller.port_name == pcie_port_name)
245            .with_context(|| {
246                format!(
247                    "USB device references undeclared controller on PCIe port {pcie_port_name:?}"
248                )
249            })?;
250        match device {
251            cli_args::UsbDeviceCli::Device { location, backend } => controller.devices.push((
252                location.connector.map(cli_args::UsbConnectorCli::number),
253                backend.clone(),
254            )),
255            cli_args::UsbDeviceCli::WinUsbAll { .. } => {
256                anyhow::ensure!(
257                    !controller.winusb_all,
258                    "winusb-all may be selected only once per VM"
259                );
260                controller.winusb_all = true;
261            }
262        }
263    }
264    usb::controller_configs(controllers)
265}
266
267/// Build a flat list of switches with their parent port assignments.
268///
269/// This function converts hierarchical CLI switch definitions into a flat list
270/// where each switch specifies its parent port directly.
271fn build_switch_list(all_switches: &[cli_args::GenericPcieSwitchCli]) -> Vec<PcieSwitchConfig> {
272    all_switches
273        .iter()
274        .map(|switch_cli| PcieSwitchConfig {
275            name: switch_cli.name.clone(),
276            parent_port: switch_cli.port_name.clone(),
277            ports: (0..switch_cli.num_downstream_ports)
278                .map(|i| PciePortConfig {
279                    name: format!("{}-downstream-{}", switch_cli.name, i),
280                    devfn: None,
281                    hotplug: switch_cli.hotplug,
282                    acpi_hotplug: false,
283                    acs_capabilities_supported: switch_cli.acs_capabilities_supported,
284                    cxl: false,
285                    pasid: switch_cli.pasid,
286                })
287                .collect(),
288        })
289        .collect()
290}
291
292fn base_chipset_type(opt: &Options) -> BaseChipsetType {
293    if let Some(igvm) = &opt.igvm {
294        match igvm.personality {
295            IgvmPersonalityCli::Openhcl => BaseChipsetType::HclHost,
296            IgvmPersonalityCli::Uefi => BaseChipsetType::HypervGen2Uefi,
297            IgvmPersonalityCli::LinuxDirect if opt.isolation.is_some() => {
298                BaseChipsetType::EnlightenedLinuxDirect
299            }
300            IgvmPersonalityCli::LinuxDirect if opt.hv => BaseChipsetType::HyperVGen2LinuxDirect,
301            IgvmPersonalityCli::LinuxDirect => BaseChipsetType::UnenlightenedLinuxDirect,
302        }
303    } else if matches!(opt.isolation, Some(cli_args::IsolationCli::Snp)) {
304        BaseChipsetType::EnlightenedLinuxDirect
305    } else if opt.pcat {
306        BaseChipsetType::HypervGen1
307    } else if opt.uefi.is_some() {
308        BaseChipsetType::HypervGen2Uefi
309    } else if opt.hv {
310        BaseChipsetType::HyperVGen2LinuxDirect
311    } else {
312        BaseChipsetType::UnenlightenedLinuxDirect
313    }
314}
315
316/// Build the loader's [`SmbiosConfig`](openvmm_defs::config::SmbiosConfig) from
317/// the parsed `--smbios` arguments.
318///
319/// Multiple `--smbios` arguments are merged (erroring on a field set twice).
320/// String overrides left unset fall through to the loader's default identity.
321/// The system UUID defaults to the all-zero GUID unless overridden with
322/// `uuid=GUID`; `uuid=random` requests a freshly generated per-VM GUID.
323fn smbios_config_from_cli(
324    args: &[cli_args::SmbiosCli],
325) -> anyhow::Result<openvmm_defs::config::SmbiosConfig> {
326    let mut merged = cli_args::SmbiosCli::default();
327    for arg in args {
328        merged.merge(arg.clone())?;
329    }
330    let cli_args::SmbiosCli {
331        bios:
332            cli_args::SmbiosBiosCli {
333                vendor: bios_vendor,
334                version: bios_version,
335                release_date: bios_release_date,
336                release: bios_release,
337            },
338        system:
339            cli_args::SmbiosSystemCli {
340                manufacturer: system_manufacturer,
341                product_name: system_product,
342                version: system_version,
343                serial_number: system_serial,
344                sku_number: system_sku,
345                family: system_family,
346                uuid: system_uuid,
347            },
348    } = merged;
349    Ok(openvmm_defs::config::SmbiosConfig {
350        bios: openvmm_defs::config::SmbiosBiosOverrides {
351            vendor: bios_vendor,
352            version: bios_version,
353            release_date: bios_release_date,
354            release: bios_release.map(|r| (r.0, r.1)),
355        },
356        system: openvmm_defs::config::SmbiosSystemOverrides {
357            manufacturer: system_manufacturer,
358            product_name: system_product,
359            version: system_version,
360            serial_number: system_serial,
361            sku_number: system_sku,
362            family: system_family,
363            uuid: match system_uuid {
364                None => Guid::ZERO,
365                Some(cli_args::SmbiosUuid::Random) => Guid::new_random(),
366                Some(cli_args::SmbiosUuid::Fixed(guid)) => guid,
367            },
368        },
369    })
370}
371
372async fn vm_config_from_command_line(
373    spawner: impl Spawn,
374    mesh: &VmmMesh,
375    opt: &Options,
376) -> anyhow::Result<(Config, VmResources)> {
377    opt.validate_vm_options()?;
378
379    let (_, serial_driver) = DefaultPool::spawn_on_thread("serial");
380    let uefi = opt.effective_uefi()?;
381    let default_uefi = cli_args::UefiCli::default();
382    let uefi_options = uefi.as_ref().unwrap_or(&default_uefi);
383
384    let openhcl_vtl = if opt.vtl2 {
385        DeviceVtl::Vtl2
386    } else {
387        DeviceVtl::Vtl0
388    };
389
390    let console_state: RefCell<Option<ConsoleState<'_>>> = RefCell::new(None);
391    let setup_serial = |name: &str, cli_cfg, device| -> anyhow::Result<_> {
392        Ok(match cli_cfg {
393            SerialConfigCli::Console => {
394                if let Some(console_state) = console_state.borrow().as_ref() {
395                    bail!("console already set by {}", console_state.device);
396                }
397                let (config, serial) = serial_io::anonymous_serial_pair(&serial_driver)?;
398                let (serial_read, serial_write) = AsyncReadExt::split(serial);
399                *console_state.borrow_mut() = Some(ConsoleState {
400                    device,
401                    input: Box::new(serial_write),
402                });
403                thread::Builder::new()
404                    .name(name.to_owned())
405                    .spawn(move || {
406                        let _ = block_on(futures::io::copy(
407                            serial_read,
408                            &mut AllowStdIo::new(term::raw_stdout()),
409                        ));
410                    })
411                    .unwrap();
412                Some(config)
413            }
414            SerialConfigCli::Stderr => {
415                let (config, serial) = serial_io::anonymous_serial_pair(&serial_driver)?;
416                thread::Builder::new()
417                    .name(name.to_owned())
418                    .spawn(move || {
419                        let _ = block_on(futures::io::copy(
420                            serial,
421                            &mut AllowStdIo::new(term::raw_stderr()),
422                        ));
423                    })
424                    .unwrap();
425                Some(config)
426            }
427            SerialConfigCli::File(path) => Some(serial_io::file_serial(&path, false)?),
428            SerialConfigCli::None => None,
429            SerialConfigCli::Null => Some(NullSerialBackendHandle.into_resource()),
430            SerialConfigCli::Pipe(path) => {
431                Some(serial_io::bind_serial(&path).context("failed to bind serial")?)
432            }
433            SerialConfigCli::Tcp(addr) => {
434                Some(serial_io::bind_tcp_serial(&addr).context("failed to bind serial")?)
435            }
436            SerialConfigCli::NewConsole(app, window_title) => {
437                let path = console_relay::random_console_path();
438                let config =
439                    serial_io::bind_serial(&path).context("failed to bind console serial")?;
440                let window_title =
441                    window_title.unwrap_or_else(|| name.to_uppercase() + " [OpenVMM]");
442
443                console_relay::launch_console(
444                    app.or_else(openvmm_terminal_app).as_deref(),
445                    &path,
446                    ConsoleLaunchOptions {
447                        window_title: Some(window_title),
448                    },
449                )
450                .context("failed to launch console")?;
451
452                Some(config)
453            }
454        })
455    };
456
457    let mut vmbus_devices = Vec::new();
458
459    let com_debugger_mode = [
460        opt.com1.as_ref().is_some_and(|c| c.debugger_mode),
461        opt.com2.as_ref().is_some_and(|c| c.debugger_mode),
462        opt.com3.as_ref().is_some_and(|c| c.debugger_mode),
463        opt.com4.as_ref().is_some_and(|c| c.debugger_mode),
464    ];
465
466    let [serial0_name, serial1_name, serial2_name, serial3_name] = cfg_select! {
467        guest_arch = "x86_64" => ["ttyS0", "ttyS1", "ttyS2", "ttyS3"],
468        guest_arch = "aarch64" => ["ttyAMA0", "ttyAMA1", "ttyAMA2", "ttyAMA3"],
469    };
470    let serial0_cfg = setup_serial(
471        "com1",
472        opt.com1
473            .clone()
474            .map_or(SerialConfigCli::Console, |c| c.backend),
475        serial0_name,
476    )?;
477    let serial1_cfg = setup_serial(
478        "com2",
479        opt.com2
480            .clone()
481            .map_or(SerialConfigCli::None, |c| c.backend),
482        serial1_name,
483    )?;
484    let serial2_cfg = setup_serial(
485        "com3",
486        opt.com3
487            .clone()
488            .map_or(SerialConfigCli::None, |c| c.backend),
489        serial2_name,
490    )?;
491    let serial3_cfg = setup_serial(
492        "com4",
493        opt.com4
494            .clone()
495            .map_or(SerialConfigCli::None, |c| c.backend),
496        serial3_name,
497    )?;
498    let with_vmbus_com1_serial = if let Some(vmbus_com1_cfg) = setup_serial(
499        "vmbus_com1",
500        opt.vmbus_com1_serial
501            .clone()
502            .unwrap_or(SerialConfigCli::None),
503        "vmbus_com1",
504    )? {
505        vmbus_devices.push((
506            openhcl_vtl,
507            VmbusSerialDeviceHandle {
508                port: VmbusSerialPort::Com1,
509                backend: vmbus_com1_cfg,
510            }
511            .into_resource(),
512        ));
513        true
514    } else {
515        false
516    };
517    let with_vmbus_com2_serial = if let Some(vmbus_com2_cfg) = setup_serial(
518        "vmbus_com2",
519        opt.vmbus_com2_serial
520            .clone()
521            .unwrap_or(SerialConfigCli::None),
522        "vmbus_com2",
523    )? {
524        vmbus_devices.push((
525            openhcl_vtl,
526            VmbusSerialDeviceHandle {
527                port: VmbusSerialPort::Com2,
528                backend: vmbus_com2_cfg,
529            }
530            .into_resource(),
531        ));
532        true
533    } else {
534        false
535    };
536    let debugcon_cfg = setup_serial(
537        "debugcon",
538        opt.debugcon
539            .clone()
540            .map(|cfg| cfg.serial)
541            .unwrap_or(SerialConfigCli::None),
542        "debugcon",
543    )?;
544
545    let virtio_console_backend = if let Some(serial_cfg) = opt.virtio_console.clone() {
546        setup_serial("virtio-console", serial_cfg, "hvc0")?
547    } else {
548        None
549    };
550
551    let mut resources = VmResources::default();
552    let mut console_str = "";
553    if let Some(ConsoleState { device, input }) = console_state.into_inner() {
554        resources.console_in = Some(input);
555        console_str = device;
556    }
557
558    if opt.shared_memory {
559        tracing::warn!("--shared-memory/-M flag has no effect and will be removed");
560    }
561    if opt.deprecated_prefetch {
562        tracing::warn!("--prefetch is deprecated; use --memory prefetch=on");
563    }
564    if opt.deprecated_private_memory {
565        tracing::warn!("--private-memory is deprecated; use --memory shared=off");
566    }
567    if opt.deprecated_thp {
568        tracing::warn!("--thp is deprecated; use --memory shared=off,thp=on");
569    }
570    if opt.deprecated_memory_backing_file.is_some() {
571        tracing::warn!("--memory-backing-file is deprecated; use --memory file=<path>");
572    }
573
574    opt.validate_memory_options()?;
575
576    const MAX_PROCESSOR_COUNT: u32 = 1024;
577
578    if opt.processors == 0 || opt.processors > MAX_PROCESSOR_COUNT {
579        bail!("invalid proc count: {}", opt.processors);
580    }
581
582    // Total SCSI channel count should not exceed the processor count
583    // (at most, one channel per VP).
584    if opt.scsi_sub_channels > (MAX_PROCESSOR_COUNT - 1) as u16 {
585        bail!(
586            "invalid SCSI sub-channel count: requested {}, max {}",
587            opt.scsi_sub_channels,
588            MAX_PROCESSOR_COUNT - 1
589        );
590    }
591
592    let with_get = opt.get || (opt.vtl2 && !opt.no_get);
593
594    let mut storage = storage_builder::StorageBuilder::new(with_get.then_some(openhcl_vtl));
595
596    // Register named controllers first, so that --disk on=<name>
597    // references can be resolved.
598    for ctrl in &opt.nvme_pci {
599        let transport = match &ctrl.transport {
600            cli_args::NvmeControllerTransport::Pcie(port) => {
601                storage_builder::NvmeControllerTransport::Pcie(port.clone())
602            }
603            cli_args::NvmeControllerTransport::Vpci(guid) => {
604                let guid = guid.unwrap_or_else(|| storage_builder::deterministic_guid(&ctrl.id));
605                storage_builder::NvmeControllerTransport::Vpci(guid)
606            }
607        };
608        storage.add_nvme_controller(ctrl.id.clone(), ctrl.vtl, transport, None)?;
609    }
610
611    for ctrl in &opt.vmbus_scsi {
612        let instance_id = storage_builder::deterministic_guid(&ctrl.id);
613        storage.add_scsi_controller(ctrl.id.clone(), ctrl.vtl, instance_id, ctrl.sub_channels)?;
614    }
615
616    for ctrl in &opt.openhcl_controller {
617        let controller_type = match ctrl.controller_type {
618            cli_args::OpenhclControllerType::Scsi => storage_builder::OpenhclControllerType::Scsi,
619            cli_args::OpenhclControllerType::Nvme => storage_builder::OpenhclControllerType::Nvme,
620        };
621        let instance_id = ctrl
622            .guid
623            .unwrap_or_else(|| storage_builder::deterministic_guid(&ctrl.id));
624        storage.add_openhcl_controller(ctrl.id.clone(), controller_type, instance_id)?;
625    }
626
627    for &cli_args::DiskCli {
628        vtl,
629        ref kind,
630        read_only,
631        is_dvd,
632        underhill,
633        ref pcie_port,
634        ref serial,
635        num_queues,
636        ref controller,
637        nsid,
638        lun,
639        ref relay,
640    } in &opt.disk
641    {
642        if serial.is_some() {
643            anyhow::bail!("`serial` is only supported by `--virtio-blk`");
644        }
645        if num_queues.is_some() {
646            anyhow::bail!("`num_queues` is only supported by `--virtio-blk`");
647        }
648        if controller.is_none() && underhill.is_none() && relay.is_none() {
649            tracing::warn!(
650                "--disk without `on` is deprecated; \
651                 use --vmbus-scsi and --disk on=<name> instead"
652            );
653        }
654
655        let relay_target = relay
656            .as_ref()
657            .map(|(name, loc)| storage_builder::RelayTarget {
658                controller: name.clone(),
659                location: *loc,
660            });
661
662        let target = if let Some(name) = controller {
663            if pcie_port.is_some() {
664                anyhow::bail!("`on` is incompatible with `pcie_port` on `--disk`");
665            }
666            storage_builder::DiskLocation::Named {
667                controller: name.clone(),
668                nsid,
669                lun,
670            }
671        } else if pcie_port.is_some() {
672            anyhow::bail!("`--disk` is incompatible with `pcie_port` without `controller`");
673        } else {
674            if opt.no_vmbus {
675                anyhow::bail!(
676                    "`--disk` without `on=` attaches to the default VMBus SCSI controller and \
677                     cannot be used with `--no-vmbus`; use `on=<name>` to attach to a named controller"
678                );
679            }
680            storage_builder::DiskLocation::Scsi(None)
681        };
682
683        storage
684            .add(
685                vtl,
686                underhill,
687                relay_target,
688                target,
689                kind,
690                is_dvd,
691                read_only,
692            )
693            .await?;
694    }
695
696    for &cli_args::IdeDiskCli {
697        ref kind,
698        read_only,
699        channel,
700        device,
701        is_dvd,
702    } in &opt.ide
703    {
704        storage
705            .add(
706                DeviceVtl::Vtl0,
707                None,
708                None,
709                storage_builder::DiskLocation::Ide(channel, device),
710                kind,
711                is_dvd,
712                read_only,
713            )
714            .await?;
715    }
716
717    if !opt.nvme.is_empty() {
718        tracing::warn!("--nvme is deprecated; use --nvme-pci and --disk on=<name> instead");
719
720        // Pre-register implicit PCIe controllers for unique port names.
721        let mut registered_ports = std::collections::BTreeSet::new();
722        for disk in &opt.nvme {
723            if let Some(port) = &disk.pcie_port {
724                if registered_ports.insert(port.clone()) {
725                    storage.add_nvme_controller(
726                        port.clone(),
727                        DeviceVtl::Vtl0,
728                        storage_builder::NvmeControllerTransport::Pcie(port.clone()),
729                        None,
730                    ).with_context(|| format!(
731                        "legacy --nvme flag conflicts with an explicit controller named '{port}'; \
732                         use --nvme-pci and --disk on=<name> instead"
733                    ))?;
734                }
735            }
736        }
737    }
738
739    for &cli_args::DiskCli {
740        vtl,
741        ref kind,
742        read_only,
743        is_dvd,
744        underhill,
745        ref pcie_port,
746        ref serial,
747        num_queues,
748        controller: _,
749        nsid: _,
750        lun: _,
751        relay: _,
752    } in &opt.nvme
753    {
754        if serial.is_some() {
755            anyhow::bail!("`serial` is only supported by `--virtio-blk`");
756        }
757        if num_queues.is_some() {
758            anyhow::bail!("`num_queues` is only supported by `--virtio-blk`");
759        }
760        let target = if let Some(port) = pcie_port {
761            storage_builder::DiskLocation::Named {
762                controller: port.clone(),
763                nsid: None,
764                lun: None,
765            }
766        } else {
767            storage_builder::DiskLocation::Nvme(None)
768        };
769        storage
770            .add(vtl, underhill, None, target, kind, is_dvd, read_only)
771            .await?;
772    }
773
774    for &cli_args::DiskCli {
775        vtl,
776        ref kind,
777        read_only,
778        is_dvd,
779        ref underhill,
780        ref pcie_port,
781        ref serial,
782        num_queues,
783        controller: _,
784        nsid: _,
785        lun: _,
786        relay: _,
787    } in &opt.virtio_blk
788    {
789        if underhill.is_some() {
790            anyhow::bail!("underhill not supported with virtio-blk");
791        }
792        storage
793            .add(
794                vtl,
795                None,
796                None,
797                storage_builder::DiskLocation::VirtioBlk {
798                    pcie_port: pcie_port.clone(),
799                    serial: serial.clone(),
800                    options: virtio_resources::blk::VirtioBlkOptions {
801                        queue_count: num_queues.unwrap_or(opt.virtio_blk_queues),
802                        io_depth: opt.virtio_blk_io_depth,
803                    },
804                },
805                kind,
806                is_dvd,
807                read_only,
808            )
809            .await?;
810    }
811
812    let mut floppy_disks = Vec::new();
813    for disk in &opt.floppy {
814        let &cli_args::FloppyDiskCli {
815            ref kind,
816            read_only,
817        } = disk;
818        floppy_disks.push(FloppyDiskConfig {
819            disk_type: disk_open(kind, read_only).await?,
820            read_only,
821        });
822    }
823
824    let mut vpci_mana_nics = [(); 3].map(|()| None);
825    let mut pcie_mana_nics = BTreeMap::<String, GdmaDeviceHandle>::new();
826    let mut underhill_nics = Vec::new();
827    let mut vpci_devices = Vec::new();
828
829    let mut nic_index = 0;
830    for cli_cfg in &opt.net {
831        if cli_cfg.pcie_port.is_some() {
832            anyhow::bail!("`--net` does not support PCIe");
833        }
834        let vport = parse_endpoint(cli_cfg, &mut nic_index, &mut resources)?;
835        if cli_cfg.underhill {
836            if !opt.no_alias_map {
837                anyhow::bail!("must specify --no-alias-map to offer NICs to VTL2");
838            }
839            let mana = vpci_mana_nics[openhcl_vtl as usize].get_or_insert_with(|| {
840                let vpci_instance_id = mana_vpci_instance_id(openhcl_vtl as usize);
841                underhill_nics.push(vtl2_settings_proto::NicDeviceLegacy {
842                    instance_id: vpci_instance_id.to_string(),
843                    subordinate_instance_id: None,
844                    max_sub_channels: None,
845                });
846                (vpci_instance_id, GdmaDeviceHandle { vports: Vec::new() })
847            });
848            mana.1.vports.push(VportDefinition {
849                mac_address: vport.mac_address,
850                endpoint: vport.endpoint,
851            });
852        } else {
853            vmbus_devices.push(vport.into_netvsp_handle());
854        }
855    }
856
857    if opt.nic {
858        let nic_config = parse_endpoint(
859            &NicConfigCli {
860                vtl: DeviceVtl::Vtl0,
861                endpoint: EndpointConfigCli::Consomme {
862                    cidr: None,
863                    host_fwd: Vec::new(),
864                },
865                mac_address: None,
866                max_queues: None,
867                enable_rx_gso: false,
868                underhill: false,
869                pcie_port: None,
870            },
871            &mut nic_index,
872            &mut resources,
873        )?;
874        vmbus_devices.push(nic_config.into_netvsp_handle());
875    }
876
877    // Build initial PCIe devices list from CLI options. Storage devices
878    // (e.g., NVMe controllers on PCIe ports) are added later by storage_builder.
879    let mut pcie_devices = Vec::new();
880    for (pcie_port_name, config) in usb_controller_configs(&opt.usb_xhci, &opt.usb_device)? {
881        pcie_devices.push(PcieDeviceConfig {
882            port_name: pcie_port_name,
883            resource: config.into_resource(),
884        });
885    }
886    for (index, cli_cfg) in opt.pcie_remote.iter().enumerate() {
887        tracing::info!(
888            port_name = %cli_cfg.port_name,
889            socket_addr = ?cli_cfg.socket_addr,
890            "instantiating PCIe remote device"
891        );
892
893        // Generate a deterministic instance ID based on index
894        const PCIE_REMOTE_BASE_INSTANCE_ID: Guid =
895            guid::guid!("28ed784d-c059-429f-9d9a-46bea02562c0");
896        let instance_id = Guid {
897            data1: index as u32,
898            ..PCIE_REMOTE_BASE_INSTANCE_ID
899        };
900
901        pcie_devices.push(PcieDeviceConfig {
902            port_name: cli_cfg.port_name.clone(),
903            resource: pcie_remote_resources::PcieRemoteHandle {
904                instance_id,
905                socket_addr: cli_cfg.socket_addr.clone(),
906                hu: cli_cfg.hu,
907                controller: cli_cfg.controller,
908            }
909            .into_resource(),
910        });
911    }
912
913    #[cfg(windows)]
914    let mut kernel_vmnics = Vec::new();
915    #[cfg(windows)]
916    for (index, switch_id) in opt.kernel_vmnic.iter().enumerate() {
917        // Pick a random MAC address.
918        let mut mac_address = [0x00, 0x15, 0x5D, 0, 0, 0];
919        getrandom::fill(&mut mac_address[3..]).expect("rng failure");
920
921        // Pick a fixed instance ID based on the index.
922        const BASE_INSTANCE_ID: Guid = guid::guid!("00000000-435d-11ee-9f59-00155d5016fc");
923        let instance_id = Guid {
924            data1: index as u32,
925            ..BASE_INSTANCE_ID
926        };
927
928        let switch_id = if switch_id == "default" {
929            None
930        } else {
931            Some(switch_id.as_str())
932        };
933        let (port_id, port) = new_switch_port(switch_id)?;
934        resources.switch_ports.push(port);
935
936        kernel_vmnics.push(openvmm_defs::config::KernelVmNicConfig {
937            instance_id,
938            mac_address: mac_address.into(),
939            switch_port_id: port_id,
940        });
941    }
942
943    for vport in &opt.mana {
944        let vport = parse_endpoint(vport, &mut nic_index, &mut resources)?;
945        let vport_array = match (vport.vtl as usize, vport.pcie_port) {
946            (vtl, None) => {
947                &mut vpci_mana_nics[vtl]
948                    .get_or_insert_with(|| {
949                        (
950                            mana_vpci_instance_id(vtl),
951                            GdmaDeviceHandle { vports: Vec::new() },
952                        )
953                    })
954                    .1
955                    .vports
956            }
957            (0, Some(pcie_port)) => {
958                &mut pcie_mana_nics
959                    .entry(pcie_port)
960                    .or_insert(GdmaDeviceHandle { vports: Vec::new() })
961                    .vports
962            }
963            _ => anyhow::bail!("PCIe NICs only supported to VTL0"),
964        };
965        vport_array.push(VportDefinition {
966            mac_address: vport.mac_address,
967            endpoint: vport.endpoint,
968        });
969    }
970
971    vpci_devices.extend(
972        vpci_mana_nics
973            .into_iter()
974            .enumerate()
975            .filter_map(|(vtl, nic)| {
976                nic.map(|(instance_id, handle)| VpciDeviceConfig {
977                    vtl: match vtl {
978                        0 => DeviceVtl::Vtl0,
979                        1 => DeviceVtl::Vtl1,
980                        2 => DeviceVtl::Vtl2,
981                        _ => unreachable!(),
982                    },
983                    instance_id,
984                    resource: handle.into_resource(),
985                    vnode: None,
986                })
987            }),
988    );
989
990    pcie_devices.extend(
991        pcie_mana_nics
992            .into_iter()
993            .map(|(pcie_port, handle)| PcieDeviceConfig {
994                port_name: pcie_port,
995                resource: handle.into_resource(),
996            }),
997    );
998
999    for cxl_test in &opt.cxl_test {
1000        pcie_devices.push(PcieDeviceConfig {
1001            port_name: cxl_test.pcie_port.clone(),
1002            resource: CxlTestDeviceHandle {
1003                hdm_size_bytes: cxl_test.hdm_size,
1004            }
1005            .into_resource(),
1006        });
1007    }
1008
1009    let arch = cfg_select! {
1010        guest_arch = "x86_64" => MachineArch::X86_64,
1011        guest_arch = "aarch64" => MachineArch::Aarch64,
1012    };
1013
1014    cfg_select! {
1015        guest_arch = "x86_64" => {
1016            anyhow::ensure!(
1017                opt.amd_iommu.is_empty() || opt.intel_vtd.is_empty(),
1018                "--amd-iommu and --intel-vtd cannot both be used in the same VM"
1019            );
1020
1021            let mut amd_iommu_names: HashSet<&str> =
1022                opt.amd_iommu.iter().map(|s| s.as_str()).collect();
1023            let mut vtd_names: HashSet<&str> = opt.intel_vtd.iter().map(|s| s.as_str()).collect();
1024        }
1025        guest_arch = "aarch64" => {
1026            // Map each `--smmu` entry to its root complex, rejecting duplicate `rc=`
1027            // entries up front. Entries are removed as they are matched to a root
1028            // complex below; any left over refer to unknown root complexes.
1029            let mut smmu_names: std::collections::HashMap<&str, &cli_args::SmmuCli> = {
1030                let mut map = std::collections::HashMap::new();
1031                for s in &opt.smmu {
1032                    if map.insert(s.rc_name.as_str(), s).is_some() {
1033                        anyhow::bail!(
1034                            "--smmu specified multiple times for root complex '{}'",
1035                            s.rc_name
1036                        );
1037                    }
1038                }
1039                map
1040            };
1041        }
1042    }
1043    let mut pcie_root_complexes = Vec::new();
1044    let mut legacy_pci_config_io_for_pcie = false;
1045    for (i, rc_cli) in opt.pcie_root_complex.iter().enumerate() {
1046        let ports: Vec<PciePortConfig> = opt
1047            .pcie_root_port
1048            .iter()
1049            .filter(|port_cli| port_cli.root_complex_name == rc_cli.name)
1050            .map(|port_cli| PciePortConfig {
1051                name: port_cli.name.clone(),
1052                devfn: port_cli.devfn,
1053                hotplug: port_cli.hotplug,
1054                acpi_hotplug: false,
1055                acs_capabilities_supported: port_cli.acs_capabilities_supported,
1056                cxl: port_cli.cxl,
1057                pasid: port_cli.pasid,
1058            })
1059            .collect();
1060
1061        const ONE_MB: u64 = 1024 * 1024;
1062        // Keep all PCI windows 1MB-granular to match layout and downstream placement rules.
1063        let low_mmio_size = (rc_cli.low_mmio as u64).next_multiple_of(ONE_MB);
1064        let high_mmio_size = rc_cli
1065            .high_mmio
1066            .checked_next_multiple_of(ONE_MB)
1067            .context("high mmio rounding error")?;
1068
1069        // Count CXL-capable ports under the root bus. If the root bus has CXL root ports, it needs CHBCR.
1070        let cxl_port_count = ports.iter().filter(|port| port.cxl).count() as u64;
1071
1072        let cxl = if cxl_port_count != 0 {
1073            Some(RootComplexCxlConfig {
1074                hdm_size: rc_cli.hdm,
1075                hdm_window_restrictions: rc_cli.hdm_window_restrictions.bits(),
1076            })
1077        } else {
1078            None
1079        };
1080        let legacy_pci_config_io = arch == MachineArch::X86_64
1081            && !opt.pcat
1082            && rc_cli.segment == 0
1083            && rc_cli.start_bus == 0
1084            && rc_cli.end_bus == u8::MAX;
1085        legacy_pci_config_io_for_pcie |= legacy_pci_config_io;
1086        pcie_root_complexes.push(PcieRootComplexConfig {
1087            index: i as u32,
1088            name: rc_cli.name.clone(),
1089            segment: rc_cli.segment,
1090            start_bus: rc_cli.start_bus,
1091            end_bus: rc_cli.end_bus,
1092            legacy_pci_config_io,
1093            low_mmio: if let Some(base) = rc_cli.low_mmio_base {
1094                PcieMmioRangeConfig::Fixed(
1095                    memory_range::MemoryRange::try_new(base..base.wrapping_add(low_mmio_size))
1096                        .context("invalid low MMIO range")?,
1097                )
1098            } else {
1099                PcieMmioRangeConfig::Dynamic {
1100                    size: low_mmio_size,
1101                }
1102            },
1103            high_mmio: if let Some(base) = rc_cli.high_mmio_base {
1104                PcieMmioRangeConfig::Fixed(
1105                    memory_range::MemoryRange::try_new(base..base.wrapping_add(high_mmio_size))
1106                        .context("invalid high MMIO range")?,
1107                )
1108            } else {
1109                PcieMmioRangeConfig::Dynamic {
1110                    size: high_mmio_size,
1111                }
1112            },
1113            cxl,
1114            ports,
1115            #[cfg(guest_arch = "aarch64")]
1116            iommu: smmu_names.remove(rc_cli.name.as_str()).map(|s| {
1117                openvmm_defs::config::PcieIommuConfig::Smmu {
1118                    accel: s.accel,
1119                    oas: match s.oas {
1120                        cli_args::SmmuOasCli::Auto => openvmm_defs::config::SmmuOas::Auto,
1121                        cli_args::SmmuOasCli::Fixed(bits) => {
1122                            openvmm_defs::config::SmmuOas::Fixed(bits)
1123                        }
1124                    },
1125                    ssidsize: match s.ssidsize {
1126                        cli_args::SmmuSsidSizeCli::Auto => openvmm_defs::config::SmmuSsidSize::Auto,
1127                        cli_args::SmmuSsidSizeCli::Fixed(bits) => {
1128                            openvmm_defs::config::SmmuSsidSize::Fixed(bits)
1129                        }
1130                    },
1131                }
1132            }),
1133            #[cfg(guest_arch = "x86_64")]
1134            iommu: if amd_iommu_names.remove(rc_cli.name.as_str()) {
1135                Some(openvmm_defs::config::PcieIommuConfig::AmdVi)
1136            } else if vtd_names.remove(rc_cli.name.as_str()) {
1137                Some(openvmm_defs::config::PcieIommuConfig::IntelVtd)
1138            } else {
1139                None
1140            },
1141            vnode: rc_cli.vnode,
1142            preserve_bars: rc_cli.preserve_bars,
1143        });
1144    }
1145
1146    cfg_select! {
1147        guest_arch = "x86_64" => {
1148            if let Some(name) = amd_iommu_names.into_iter().next() {
1149                anyhow::bail!("--amd-iommu refers to unknown root complex '{name}'");
1150            }
1151            if let Some(name) = vtd_names.into_iter().next() {
1152                anyhow::bail!("--intel-vtd refers to unknown root complex '{name}'");
1153            }
1154        }
1155        guest_arch = "aarch64" => {
1156            if let Some(name) = smmu_names.into_keys().next() {
1157                anyhow::bail!("--smmu refers to unknown root complex '{name}'");
1158            }
1159        }
1160    }
1161
1162    let pcie_switches = build_switch_list(&opt.pcie_switch);
1163    let pcie_generic_initiators = opt
1164        .pcie_generic_initiator
1165        .iter()
1166        .map(|gi| openvmm_defs::config::PcieGenericInitiatorConfig {
1167            port_name: gi.port_name.clone(),
1168            node: gi.node,
1169        })
1170        .collect();
1171    #[cfg(target_os = "linux")]
1172    let vfio_pcie_devices: Vec<PcieDeviceConfig> = {
1173        use std::collections::HashMap;
1174        use vm_resource::IntoResource;
1175
1176        // Process --iommu flags: open /dev/iommu for each declared context.
1177        let mut iommu_map: HashMap<String, std::fs::File> = HashMap::new();
1178        for iommu_cli in &opt.iommu {
1179            anyhow::ensure!(
1180                !iommu_map.contains_key(&iommu_cli.id),
1181                "duplicate --iommu id={}",
1182                iommu_cli.id
1183            );
1184            let file = std::fs::OpenOptions::new()
1185                .read(true)
1186                .write(true)
1187                .open("/dev/iommu")
1188                .context("failed to open /dev/iommu (is iommufd available?)")?;
1189            iommu_map.insert(iommu_cli.id.clone(), file);
1190        }
1191
1192        opt.vfio
1193            .iter()
1194            .map(|cli_cfg| {
1195                let sysfs_path = Path::new("/sys/bus/pci/devices").join(&cli_cfg.pci_id);
1196
1197                if let Some(iommu_id) = &cli_cfg.iommu {
1198                    // cdev + iommufd path
1199                    let iommufd = iommu_map.get(iommu_id).with_context(|| {
1200                        format!(
1201                            "--vfio device {} references iommu={iommu_id}, \
1202                             but no --iommu id={iommu_id} was specified",
1203                            cli_cfg.pci_id
1204                        )
1205                    })?;
1206                    // Clone the iommufd fd so the per-iommu manager can own it.
1207                    // The first device for a given iommu ID uses the cloned fd
1208                    // to create the IoasManager; subsequent devices reuse the
1209                    // existing manager and the cloned fd is dropped.
1210                    let iommufd = iommufd.try_clone().with_context(|| {
1211                        format!("failed to dup iommufd fd for iommu={iommu_id}")
1212                    })?;
1213
1214                    // Open the cdev device node.
1215                    let vfio_dev_dir = sysfs_path.join("vfio-dev");
1216                    let entry = std::fs::read_dir(&vfio_dev_dir)
1217                        .with_context(|| {
1218                            format!(
1219                                "failed to read {}: is {} bound to vfio-pci?",
1220                                vfio_dev_dir.display(),
1221                                cli_cfg.pci_id
1222                            )
1223                        })?
1224                        .next()
1225                        .context("no vfio-dev entry found")?
1226                        .context("failed to read vfio-dev entry")?;
1227                    let dev_path = Path::new("/dev/vfio/devices").join(entry.file_name());
1228                    let cdev = std::fs::OpenOptions::new()
1229                        .read(true)
1230                        .write(true)
1231                        .open(&dev_path)
1232                        .with_context(|| format!("failed to open {}", dev_path.display()))?;
1233
1234                    Ok(PcieDeviceConfig {
1235                        port_name: cli_cfg.port_name.clone(),
1236                        resource: vfio_assigned_device_resources::VfioCdevDeviceHandle {
1237                            pci_id: cli_cfg.pci_id.clone(),
1238                            cdev,
1239                            iommufd,
1240                            iommu_id: iommu_id.clone(),
1241                            bar_addresses: cli_cfg.bar_addresses,
1242                        }
1243                        .into_resource(),
1244                    })
1245                } else {
1246                    // Legacy group/container path
1247                    let iommu_group_link = std::fs::read_link(sysfs_path.join("iommu_group"))
1248                        .with_context(|| {
1249                            format!("failed to read IOMMU group for {}", cli_cfg.pci_id)
1250                        })?;
1251                    let group_id: u64 = iommu_group_link
1252                        .file_name()
1253                        .and_then(|s| s.to_str())
1254                        .context("invalid iommu_group symlink")?
1255                        .parse()
1256                        .context("failed to parse IOMMU group ID")?;
1257                    let group = std::fs::OpenOptions::new()
1258                        .read(true)
1259                        .write(true)
1260                        .open(format!("/dev/vfio/{group_id}"))
1261                        .with_context(|| format!("failed to open /dev/vfio/{group_id}"))?;
1262
1263                    Ok(PcieDeviceConfig {
1264                        port_name: cli_cfg.port_name.clone(),
1265                        resource: vfio_assigned_device_resources::VfioDeviceHandle {
1266                            pci_id: cli_cfg.pci_id.clone(),
1267                            group,
1268                            bar_addresses: cli_cfg.bar_addresses,
1269                        }
1270                        .into_resource(),
1271                    })
1272                }
1273            })
1274            .collect::<anyhow::Result<Vec<_>>>()?
1275    };
1276
1277    #[cfg(windows)]
1278    let vpci_resources: Vec<_> = opt
1279        .device
1280        .iter()
1281        .map(|path| -> anyhow::Result<_> {
1282            Ok(virt_whp::device::DeviceHandle(
1283                whp::VpciResource::new(
1284                    None,
1285                    Default::default(),
1286                    &whp::VpciResourceDescriptor::Sriov(path, 0, 0),
1287                )
1288                .with_context(|| format!("opening PCI device {}", path))?,
1289            ))
1290        })
1291        .collect::<Result<_, _>>()?;
1292
1293    // Create a vmbusproxy handle if needed by any devices.
1294    #[cfg(windows)]
1295    let vmbusproxy_handle = if !kernel_vmnics.is_empty() {
1296        Some(vmbus_proxy::ProxyHandle::new().context("failed to open vmbusproxy handle")?)
1297    } else {
1298        None
1299    };
1300
1301    let framebuffer = if opt.gfx || opt.vtl2_gfx || opt.vnc.vnc || opt.pcat {
1302        let vram = alloc_shared_memory(FRAMEBUFFER_SIZE, "vram")?;
1303        let (fb, fba) =
1304            framebuffer::framebuffer(vram, FRAMEBUFFER_SIZE, 0).context("creating framebuffer")?;
1305        resources.framebuffer_access = Some(fba);
1306        Some(fb)
1307    } else {
1308        None
1309    };
1310
1311    let load_mode;
1312    let with_hv;
1313
1314    let any_serial_configured = serial0_cfg.is_some()
1315        || serial1_cfg.is_some()
1316        || serial2_cfg.is_some()
1317        || serial3_cfg.is_some();
1318
1319    let has_com3 = serial2_cfg.is_some();
1320
1321    let mut chipset = VmManifestBuilder::new(base_chipset_type(opt), arch);
1322
1323    if legacy_pci_config_io_for_pcie {
1324        chipset = chipset.with_legacy_pci_config_io_for_pcie();
1325    }
1326
1327    if framebuffer.is_some() {
1328        chipset = chipset.with_framebuffer();
1329    }
1330    if opt.guest_watchdog {
1331        chipset = chipset.with_guest_watchdog();
1332    }
1333    if any_serial_configured {
1334        chipset = chipset.with_serial([serial0_cfg, serial1_cfg, serial2_cfg, serial3_cfg]);
1335    }
1336    chipset = chipset.with_serial_debugger_mode(com_debugger_mode);
1337    if opt.battery {
1338        let (tx, rx) = mesh::channel();
1339        tx.send(HostBatteryUpdate::default_present());
1340        chipset = chipset.with_battery(rx);
1341    }
1342    if opt.no_vmbus {
1343        chipset = chipset.without_vmbus();
1344    }
1345    if let Some(cfg) = &opt.debugcon {
1346        chipset = chipset.with_debugcon(
1347            debugcon_cfg.unwrap_or_else(|| DisconnectedSerialBackendHandle.into_resource()),
1348            cfg.port,
1349        );
1350    }
1351
1352    let (base_template, custom_uefi_json) = {
1353        cfg_select! {
1354            guest_arch = "x86_64" => {
1355                use firmware_uefi_resources::x64_secure_boot_templates as secure_boot_templates;
1356            }
1357            guest_arch = "aarch64" => {
1358                use firmware_uefi_resources::aarch64_secure_boot_templates as secure_boot_templates;
1359            }
1360        }
1361        let base_template = opt.secure_boot_template.map(|template| match template {
1362            SecureBootTemplateCli::Windows => secure_boot_templates::microsoft_windows(),
1363            SecureBootTemplateCli::UefiCa => secure_boot_templates::microsoft_uefi_ca(),
1364        });
1365
1366        // TODO: fallback to VMGS read if no command line flag was given
1367
1368        let custom_uefi_json = match &opt.custom_uefi_json {
1369            Some(file) => Some(
1370                fs_err::read(file)
1371                    .context("opening custom uefi json file")?
1372                    .into(),
1373            ),
1374            None => None,
1375        };
1376
1377        (base_template, custom_uefi_json)
1378    };
1379
1380    if (uefi.is_some() && opt.igvm.is_none())
1381        || opt
1382            .igvm
1383            .as_ref()
1384            .is_some_and(|igvm| igvm.personality == IgvmPersonalityCli::Uefi)
1385    {
1386        let log_level = match uefi_options.diagnostics.unwrap_or_default() {
1387            EfiDiagnosticsLogLevelCli::Default => firmware_uefi_resources::LogLevel::make_default(),
1388            EfiDiagnosticsLogLevelCli::Info => firmware_uefi_resources::LogLevel::make_info(),
1389            EfiDiagnosticsLogLevelCli::Full => firmware_uefi_resources::LogLevel::make_full(),
1390        };
1391        let nvram_storage =
1392            non_volatile_store_resource(opt.vmgs.is_some(), vmgs_format::FileId::BIOS_NVRAM);
1393        chipset = chipset.with_uefi(vm_manifest_builder::UefiManifest::new(
1394            arch,
1395            base_template,
1396            custom_uefi_json,
1397            opt.secure_boot,
1398            log_level,
1399            None,
1400            nvram_storage,
1401            None,
1402        ));
1403    }
1404
1405    // Build the SMBIOS config once, up front, so that UEFI and Linux direct
1406    // boot share a single source for the VM's BIOS GUID / system UUID. The TPM
1407    // also keys off this GUID.
1408    let smbios = Box::new(smbios_config_from_cli(&opt.smbios)?);
1409    let bios_guid = smbios.system.uuid;
1410
1411    // Capture the SMBIOS config for the OpenHCL/GED path before `smbios` is
1412    // potentially moved into a non-VTL2 LoadMode below. The GED forwards only
1413    // the system identity to the paravisor and fails closed on BIOS overrides
1414    // it cannot honor, so it is delivered as the shared `SmbiosConfig`.
1415    let ged_smbios = (*smbios).clone();
1416
1417    let tpm_version = opt.tpm.map(|cli_ver| match cli_ver {
1418        TpmVersionCli::V138 => TpmVersion::V138,
1419        TpmVersionCli::V185 => TpmVersion::V185,
1420    });
1421
1422    if let Some(igvm) = &opt.igvm {
1423        let cli_args::UefiCli {
1424            firmware,
1425            debug: _,
1426            enable_memory_protections: _,
1427            force_dma_bounce: _,
1428            force_firmware_version,
1429            disable_frontpage: _,
1430            console: _,
1431            diagnostics: _,
1432            default_boot_always_attempt: _,
1433        } = uefi_options;
1434
1435        anyhow::ensure!(
1436            firmware.is_none(),
1437            "--uefi firmware is not supported with --igvm"
1438        );
1439        anyhow::ensure!(
1440            !force_firmware_version,
1441            "--uefi force_firmware_version is not supported with --igvm"
1442        );
1443        let file = fs_err::File::open(&igvm.firmware)
1444            .context("failed to open igvm file")?
1445            .into();
1446        let cmdline = opt.cmdline.join(" ");
1447        with_hv = match igvm.personality {
1448            IgvmPersonalityCli::Openhcl | IgvmPersonalityCli::Uefi => true,
1449            IgvmPersonalityCli::LinuxDirect => opt.hv,
1450        };
1451
1452        load_mode = LoadMode::Igvm {
1453            file,
1454            cmdline,
1455            vtl2_base_address: if opt.vtl2 {
1456                opt.igvm_vtl2_relocation_type
1457            } else {
1458                Vtl2BaseAddressType::File
1459            },
1460            com_serial: has_com3.then_some(UartId::Com(ComPort::Com3)),
1461            personality: match igvm.personality {
1462                IgvmPersonalityCli::Openhcl => IgvmPersonality::Openhcl,
1463                IgvmPersonalityCli::Uefi => IgvmPersonality::Uefi,
1464                IgvmPersonalityCli::LinuxDirect => IgvmPersonality::LinuxDirect,
1465            },
1466        };
1467
1468        // An IGVM launch carries no SMBIOS field of its own; the identity is
1469        // only delivered over the GET/GED channel, which is absent here. Reject
1470        // overrides that would otherwise be silently dropped.
1471        let smbios_requested = !opt.smbios.is_empty();
1472        let smbios_delivered_via_get = with_get && with_hv;
1473        if smbios_requested && !smbios_delivered_via_get {
1474            anyhow::bail!(
1475                "--smbios is not supported for IGVM launches without an OpenHCL GET channel"
1476            );
1477        }
1478    } else if opt.pcat {
1479        // Emit a nice error early instead of complaining about missing firmware.
1480        if arch != MachineArch::X86_64 {
1481            anyhow::bail!("pcat not supported on this architecture");
1482        }
1483        with_hv = true;
1484
1485        let firmware = openvmm_pcat_locator::find_pcat_bios(opt.pcat_firmware.as_deref())?;
1486        load_mode = LoadMode::Pcat {
1487            firmware,
1488            boot_order: opt
1489                .pcat_boot_order
1490                .map(|x| x.0)
1491                .unwrap_or(DEFAULT_PCAT_BOOT_ORDER),
1492            hibernation_enabled: opt.hibernation,
1493            smbios,
1494        };
1495    } else if let Some(uefi_options) = &uefi {
1496        use openvmm_defs::config::UefiConsoleMode;
1497
1498        let cli_args::UefiCli {
1499            firmware,
1500            debug,
1501            enable_memory_protections,
1502            force_dma_bounce,
1503            force_firmware_version,
1504            disable_frontpage,
1505            console,
1506            diagnostics: _,
1507            default_boot_always_attempt,
1508        } = uefi_options;
1509
1510        if opt.no_hv && cfg!(guest_arch = "x86_64") {
1511            anyhow::bail!("--no-hv is not supported on x86_64");
1512        }
1513
1514        with_hv = !opt.no_hv;
1515
1516        let default_firmware = cli_args::default_uefi_firmware();
1517        let firmware = fs_err::File::open(
1518            firmware
1519                .as_ref()
1520                .or(default_firmware.as_ref())
1521                .context("must provide uefi firmware when booting with uefi")?,
1522        )
1523        .context("failed to open uefi firmware")?;
1524
1525        // TODO: It would be better to default memory protections to on, but currently Linux does not boot via UEFI due to what
1526        //       appears to be a GRUB memory protection fault. Memory protections are therefore only enabled if configured.
1527        load_mode = LoadMode::Uefi {
1528            firmware: firmware.into(),
1529            enable_debugging: *debug,
1530            enable_memory_protections: *enable_memory_protections,
1531            disable_frontpage: *disable_frontpage,
1532            tpm_version,
1533            enable_battery: opt.battery,
1534            enable_serial: any_serial_configured,
1535            enable_vpci_boot: false,
1536            uefi_console_mode: console.map(|m| match m {
1537                UefiConsoleModeCli::Default => UefiConsoleMode::Default,
1538                UefiConsoleModeCli::Com1 => UefiConsoleMode::Com1,
1539                UefiConsoleModeCli::Com2 => UefiConsoleMode::Com2,
1540                UefiConsoleModeCli::None => UefiConsoleMode::None,
1541            }),
1542            default_boot_always_attempt: *default_boot_always_attempt,
1543            smbios,
1544            enable_vmbus: !opt.no_vmbus,
1545            force_dma_bounce: *force_dma_bounce,
1546            enable_hv: !opt.no_hv,
1547            hibernation_enabled: opt.hibernation,
1548            force_firmware_version: *force_firmware_version,
1549        };
1550    } else {
1551        // Linux Direct
1552        let mut cmdline = "panic=-1 debug".to_string();
1553
1554        with_hv = opt.hv;
1555        if with_hv && opt.pcie_root_complex.is_empty() {
1556            cmdline += " pci=off";
1557        }
1558
1559        if !console_str.is_empty() {
1560            let _ = write!(&mut cmdline, " console={}", console_str);
1561        }
1562
1563        if opt.gfx {
1564            cmdline += " console=tty";
1565        }
1566        for extra in &opt.cmdline {
1567            let _ = write!(&mut cmdline, " {}", extra);
1568        }
1569
1570        let kernel = fs_err::File::open(
1571            (opt.kernel.0)
1572                .as_ref()
1573                .context("must provide kernel when booting with linux direct")?,
1574        )
1575        .context("failed to open kernel")?;
1576        let initrd = (opt.initrd.0)
1577            .as_ref()
1578            .map(fs_err::File::open)
1579            .transpose()
1580            .context("failed to open initrd")?;
1581
1582        load_mode = LoadMode::Linux {
1583            kernel: kernel.into(),
1584            initrd: initrd.map(Into::into),
1585            cmdline,
1586            enable_serial: any_serial_configured,
1587            isolation: if matches!(opt.isolation, Some(cli_args::IsolationCli::Snp)) {
1588                openvmm_defs::config::LinuxIsolationConfig::Snp {
1589                    restricted_injection: opt.snp_restricted_injection,
1590                }
1591            } else {
1592                openvmm_defs::config::LinuxIsolationConfig::None
1593            },
1594            boot_mode: if opt.device_tree {
1595                openvmm_defs::config::LinuxDirectBootMode::DeviceTree
1596            } else {
1597                openvmm_defs::config::LinuxDirectBootMode::Acpi
1598            },
1599            smbios,
1600        };
1601    }
1602
1603    if supports_acpi_power_button(&load_mode) {
1604        let (send, recv) = mesh::channel();
1605        let irq = match arch {
1606            MachineArch::X86_64 => DEFAULT_ACPI_POWER_BUTTON_IRQ_X64,
1607            MachineArch::Aarch64 => DEFAULT_ACPI_POWER_BUTTON_SPI_AARCH64,
1608        };
1609        chipset = chipset.with_acpi_power_button(irq, recv);
1610        resources.acpi_power_button = Some(send);
1611    }
1612
1613    let layout_config = chipset.layout_config();
1614    let VmChipsetResult {
1615        chipset,
1616        mut chipset_devices,
1617        pci_chipset_devices,
1618        isa_dma_controller,
1619        capabilities,
1620    } = chipset
1621        .build()
1622        .context("failed to build chipset configuration")?;
1623
1624    let mut vmgs = Some(if let Some(vmgs) = &opt.vmgs {
1625        let encryption_policy = if opt.test_gsp_by_id {
1626            GuestStateEncryptionPolicy::GspById(true)
1627        } else {
1628            GuestStateEncryptionPolicy::None(true)
1629        };
1630        open_vmgs(&vmgs.kind, vmgs.provision, encryption_policy)
1631            .await
1632            .context("failed to open vmgs disk")?
1633    } else {
1634        VmgsResource::Ephemeral
1635    });
1636
1637    if with_get && with_hv {
1638        let has_vtl0_nvme = storage.has_vtl0_nvme();
1639        let vtl2_settings = vtl2_settings_proto::Vtl2Settings {
1640            version: vtl2_settings_proto::vtl2_settings_base::Version::V1.into(),
1641            fixed: Some(Default::default()),
1642            dynamic: Some(vtl2_settings_proto::Vtl2SettingsDynamic {
1643                storage_controllers: storage.build_openhcl_settings(opt.vmbus_redirect),
1644                nic_devices: underhill_nics,
1645            }),
1646            namespace_settings: Vec::default(),
1647        };
1648
1649        // Cache the VTL2 settings for later modification via the interactive console.
1650        resources.vtl2_settings = Some(vtl2_settings.clone());
1651
1652        let (send, guest_request_recv) = mesh::channel();
1653        resources.ged_rpc = Some(send);
1654
1655        let vmgs = vmgs.take().unwrap();
1656
1657        vmbus_devices.extend([
1658            (
1659                openhcl_vtl,
1660                get_resources::gel::GuestEmulationLogHandle.into_resource(),
1661            ),
1662            (
1663                openhcl_vtl,
1664                get_resources::ged::GuestEmulationDeviceHandle {
1665                    firmware: if opt.pcat {
1666                        get_resources::ged::GuestFirmwareConfig::Pcat {
1667                            boot_order: opt
1668                                .pcat_boot_order
1669                                .map_or(DEFAULT_PCAT_BOOT_ORDER, |x| x.0)
1670                                .map(|x| match x {
1671                                    openvmm_defs::config::PcatBootDevice::Floppy => {
1672                                        get_resources::ged::PcatBootDevice::Floppy
1673                                    }
1674                                    openvmm_defs::config::PcatBootDevice::HardDrive => {
1675                                        get_resources::ged::PcatBootDevice::HardDrive
1676                                    }
1677                                    openvmm_defs::config::PcatBootDevice::Optical => {
1678                                        get_resources::ged::PcatBootDevice::Optical
1679                                    }
1680                                    openvmm_defs::config::PcatBootDevice::Network => {
1681                                        get_resources::ged::PcatBootDevice::Network
1682                                    }
1683                                }),
1684                        }
1685                    } else {
1686                        use get_resources::ged::UefiConsoleMode;
1687
1688                        get_resources::ged::GuestFirmwareConfig::Uefi {
1689                            enable_vpci_boot: has_vtl0_nvme,
1690                            firmware_debug: uefi_options.debug,
1691                            enable_memory_protections: uefi_options.enable_memory_protections,
1692                            disable_frontpage: uefi_options.disable_frontpage,
1693                            console_mode: match uefi_options.console.unwrap_or(UefiConsoleModeCli::Default) {
1694                                UefiConsoleModeCli::Default => UefiConsoleMode::Default,
1695                                UefiConsoleModeCli::Com1 => UefiConsoleMode::COM1,
1696                                UefiConsoleModeCli::Com2 => UefiConsoleMode::COM2,
1697                                UefiConsoleModeCli::None => UefiConsoleMode::None,
1698                            },
1699                            default_boot_always_attempt: uefi_options.default_boot_always_attempt,
1700                        }
1701                    },
1702                    com1: with_vmbus_com1_serial,
1703                    com2: with_vmbus_com2_serial,
1704                    serial_tx_only: opt.serial_tx_only,
1705                    vtl2_settings: Some(prost::Message::encode_to_vec(&vtl2_settings)),
1706                    vmbus_redirection: opt.vmbus_redirect,
1707                    vmgs,
1708                    framebuffer: opt
1709                        .vtl2_gfx
1710                        .then(|| SharedFramebufferHandle.into_resource()),
1711                    guest_request_recv,
1712                    tpm_version: tpm_version.map(|v| match v {
1713                        TpmVersion::V138 => get_resources::ged::GedTpmVersion::V138,
1714                        TpmVersion::V185 => get_resources::ged::GedTpmVersion::V185,
1715                    }),
1716                    firmware_event_send: None,
1717                    ipmi_sel_event_send: None,
1718                    secure_boot_enabled: opt.secure_boot,
1719                    secure_boot_template: match opt.secure_boot_template {
1720                        Some(SecureBootTemplateCli::Windows) => {
1721                            get_resources::ged::GuestSecureBootTemplateType::MicrosoftWindows
1722                        },
1723                        Some(SecureBootTemplateCli::UefiCa) => {
1724                            get_resources::ged::GuestSecureBootTemplateType::MicrosoftUefiCertificateAuthority
1725                        }
1726                        None => {
1727                            get_resources::ged::GuestSecureBootTemplateType::None
1728                        },
1729                    },
1730                    enable_battery: opt.battery,
1731                    enable_ipmi: false,
1732                    enable_hibernation: opt.hibernation,
1733                    no_persistent_secrets: true,
1734                    igvm_attest_test_config: None,
1735                    test_gsp_by_id: opt.test_gsp_by_id,
1736                    efi_diagnostics_log_level: {
1737                        match uefi_options.diagnostics.unwrap_or_default() {
1738                            EfiDiagnosticsLogLevelCli::Default => get_resources::ged::EfiDiagnosticsLogLevelType::Default,
1739                            EfiDiagnosticsLogLevelCli::Info => get_resources::ged::EfiDiagnosticsLogLevelType::Info,
1740                            EfiDiagnosticsLogLevelCli::Full => get_resources::ged::EfiDiagnosticsLogLevelType::Full,
1741                        }
1742                    },
1743                    force_dma_bounce_enabled: uefi_options.force_dma_bounce,
1744                    smbios: ged_smbios,
1745                }
1746                .into_resource(),
1747            ),
1748        ]);
1749    }
1750
1751    if let Some(tpm_version) = tpm_version
1752        && !opt.vtl2
1753    {
1754        let register_layout = cfg_select! {
1755            guest_arch = "x86_64" => TpmRegisterLayout::IoPort,
1756            guest_arch = "aarch64" => TpmRegisterLayout::Mmio,
1757        };
1758
1759        let ppi_store =
1760            non_volatile_store_resource(opt.vmgs.is_some(), vmgs_format::FileId::TPM_PPI);
1761        let nvram_store = non_volatile_store_resource(
1762            opt.vmgs.is_some(),
1763            tpm_vmgs::tpm_nvram_file_id(tpm_version),
1764        );
1765
1766        chipset_devices.push(ChipsetDeviceHandle {
1767            name: "tpm".to_string(),
1768            resource: chipset_device_worker_defs::RemoteChipsetDeviceHandle {
1769                device: TpmDeviceHandle {
1770                    version: tpm_version,
1771                    ppi_store,
1772                    nvram_store,
1773                    nvram_size: None,
1774                    refresh_tpm_seeds: false,
1775                    ak_cert_type: tpm_resources::TpmAkCertTypeResource::None,
1776                    register_layout,
1777                    guest_secret_key: None,
1778                    logger: None,
1779                    is_confidential_vm: false,
1780                    bios_guid,
1781                }
1782                .into_resource(),
1783                worker_host: mesh.make_host("tpm", None).await?,
1784            }
1785            .into_resource(),
1786        });
1787    }
1788
1789    let vga_firmware = if opt.pcat {
1790        Some(openvmm_pcat_locator::find_svga_bios(
1791            opt.vga_firmware.as_deref(),
1792        )?)
1793    } else {
1794        None
1795    };
1796
1797    if opt.gfx {
1798        // Channel for the video device to report dirty rectangles to the VNC worker.
1799        let (dirt_send, dirt_recv) = mesh::channel();
1800        resources.dirty_rect_recv = Some(dirt_recv);
1801
1802        vmbus_devices.extend([
1803            (
1804                DeviceVtl::Vtl0,
1805                SynthVideoHandle {
1806                    framebuffer: SharedFramebufferHandle.into_resource(),
1807                    dirt_send: Some(dirt_send),
1808                }
1809                .into_resource(),
1810            ),
1811            (
1812                DeviceVtl::Vtl0,
1813                SynthKeyboardHandle {
1814                    source: MultiplexedInputHandle {
1815                        // Save 0 for PS/2
1816                        elevation: 1,
1817                    }
1818                    .into_resource(),
1819                }
1820                .into_resource(),
1821            ),
1822            (
1823                DeviceVtl::Vtl0,
1824                SynthMouseHandle {
1825                    source: MultiplexedInputHandle {
1826                        // Save 0 for PS/2
1827                        elevation: 1,
1828                    }
1829                    .into_resource(),
1830                }
1831                .into_resource(),
1832            ),
1833        ]);
1834    }
1835
1836    let vsock_listener = |path: Option<&str>| -> anyhow::Result<_> {
1837        if let Some(path) = path {
1838            cleanup_socket(path.as_ref());
1839            let listener = unix_socket::UnixListener::bind(path)
1840                .with_context(|| format!("failed to bind to hybrid vsock path: {}", path))?;
1841            Ok(Some(listener))
1842        } else {
1843            Ok(None)
1844        }
1845    };
1846
1847    let vtl0_vsock_listener = vsock_listener(opt.vmbus_vsock_path.as_deref())?;
1848    let vtl2_vsock_listener = vsock_listener(opt.vmbus_vtl2_vsock_path.as_deref())?;
1849
1850    if let Some(path) = &opt.openhcl_dump_path {
1851        let (resource, task) = spawn_dump_handler(&spawner, path.clone(), None);
1852        task.detach();
1853        vmbus_devices.push((openhcl_vtl, resource));
1854    }
1855
1856    let topology_arch = cfg_select! {
1857        guest_arch = "aarch64" => openvmm_defs::config::ArchTopologyConfig::Aarch64(
1858            openvmm_defs::config::Aarch64TopologyConfig {
1859                // TODO: allow this to be configured from the command line
1860                gic_config: None,
1861                pmu_gsiv: openvmm_defs::config::PmuGsivConfig::Platform,
1862                gic_msi: match opt.gic_msi {
1863                    cli_args::GicMsiCli::Auto => openvmm_defs::config::GicMsiConfig::Auto,
1864                    cli_args::GicMsiCli::Its => openvmm_defs::config::GicMsiConfig::Its,
1865                    cli_args::GicMsiCli::V2m => {
1866                        openvmm_defs::config::GicMsiConfig::V2m { spi_count: None }
1867                    }
1868                },
1869            },
1870        ),
1871        guest_arch = "x86_64" => {
1872            openvmm_defs::config::ArchTopologyConfig::X86(openvmm_defs::config::X86TopologyConfig {
1873                apic_id_offset: opt.apic_id_offset,
1874                x2apic: opt.x2apic,
1875            })
1876        }
1877    };
1878
1879    let with_isolation = if let Some(isolation) = &opt.isolation {
1880        match isolation {
1881            cli_args::IsolationCli::Vbs => {
1882                // TODO: For now, VBS isolation is only supported with VTL2.
1883                if !opt.vtl2 {
1884                    anyhow::bail!("VBS isolation is only currently supported with vtl2");
1885                }
1886
1887                // TODO: Alias map support is not yet implemented with isolation.
1888                if !opt.no_alias_map {
1889                    anyhow::bail!("alias map not supported with isolation");
1890                }
1891
1892                Some(openvmm_defs::config::IsolationType::Vbs)
1893            }
1894            cli_args::IsolationCli::Snp => Some(openvmm_defs::config::IsolationType::Snp {
1895                // SNP host data is currently only configurable via TTRPC.
1896                host_data: None,
1897            }),
1898        }
1899    } else {
1900        None
1901    };
1902
1903    if with_hv && !opt.no_vmbus {
1904        let (shutdown_send, shutdown_recv) = mesh::channel();
1905        resources.shutdown_ic = Some(shutdown_send);
1906        let (kvp_send, kvp_recv) = mesh::channel();
1907        resources.kvp_ic = Some(kvp_send);
1908        vmbus_devices.extend(
1909            [
1910                hyperv_ic_resources::shutdown::ShutdownIcHandle {
1911                    recv: shutdown_recv,
1912                }
1913                .into_resource(),
1914                hyperv_ic_resources::kvp::KvpIcHandle { recv: kvp_recv }.into_resource(),
1915                hyperv_ic_resources::timesync::TimesyncIcHandle.into_resource(),
1916            ]
1917            .map(|r| (DeviceVtl::Vtl0, r)),
1918        );
1919    }
1920
1921    if let Some(hive_path) = &opt.imc {
1922        let file = fs_err::File::open(hive_path).context("failed to open imc hive")?;
1923        vmbus_devices.push((
1924            DeviceVtl::Vtl0,
1925            vmbfs_resources::VmbfsImcDeviceHandle { file: file.into() }.into_resource(),
1926        ));
1927    }
1928
1929    let mut virtio_devices = Vec::new();
1930    let mut add_virtio_device =
1931        |bus, resource: Resource<VirtioDeviceHandle>, pcie_devices: &mut Vec<_>| match bus {
1932            VirtioBusCli::Auto => {
1933                // Use VPCI when possible (currently only on Windows and macOS due
1934                // to KVM backend limitations).
1935                if with_hv && (cfg!(windows) || cfg!(target_os = "macos")) {
1936                    vpci_devices.push(VpciDeviceConfig {
1937                        vtl: DeviceVtl::Vtl0,
1938                        instance_id: Guid::new_random(),
1939                        resource: VirtioPciDeviceHandle(resource).into_resource(),
1940                        vnode: None,
1941                    });
1942                } else {
1943                    virtio_devices.push((VirtioBus::Pci, resource));
1944                }
1945            }
1946            VirtioBusCli::Mmio => virtio_devices.push((VirtioBus::Mmio, resource)),
1947            VirtioBusCli::Pci => virtio_devices.push((VirtioBus::Pci, resource)),
1948            VirtioBusCli::Pcie(port_name) => pcie_devices.push(PcieDeviceConfig {
1949                port_name,
1950                resource: VirtioPciDeviceHandle(resource).into_resource(),
1951            }),
1952            VirtioBusCli::Vpci => vpci_devices.push(VpciDeviceConfig {
1953                vtl: DeviceVtl::Vtl0,
1954                instance_id: Guid::new_random(),
1955                resource: VirtioPciDeviceHandle(resource).into_resource(),
1956                vnode: None,
1957            }),
1958        };
1959
1960    for cli_cfg in &opt.virtio_net {
1961        if cli_cfg.underhill {
1962            anyhow::bail!("use --net uh:[...] to add underhill NICs")
1963        }
1964        let vport = parse_endpoint(cli_cfg, &mut nic_index, &mut resources)?;
1965        let resource = virtio_resources::net::VirtioNetHandle {
1966            max_queues: vport.max_queues,
1967            enable_rx_gso: vport.enable_rx_gso,
1968            mac_address: vport.mac_address,
1969            endpoint: vport.endpoint,
1970        }
1971        .into_resource();
1972        if let Some(pcie_port) = &cli_cfg.pcie_port {
1973            pcie_devices.push(PcieDeviceConfig {
1974                port_name: pcie_port.clone(),
1975                resource: VirtioPciDeviceHandle(resource).into_resource(),
1976            });
1977        } else {
1978            add_virtio_device(VirtioBusCli::Auto, resource, &mut pcie_devices);
1979        }
1980    }
1981
1982    for args in &opt.virtio_fs {
1983        let resource: Resource<VirtioDeviceHandle> = virtio_resources::fs::VirtioFsHandle {
1984            tag: args.tag.clone(),
1985            fs: virtio_resources::fs::VirtioFsBackend::HostFs {
1986                root_path: args.path.clone(),
1987                mount_options: args.options.clone(),
1988                windows_options: None,
1989            },
1990        }
1991        .into_resource();
1992        if let Some(pcie_port) = &args.pcie_port {
1993            pcie_devices.push(PcieDeviceConfig {
1994                port_name: pcie_port.clone(),
1995                resource: VirtioPciDeviceHandle(resource).into_resource(),
1996            });
1997        } else {
1998            add_virtio_device(opt.virtio_fs_bus.clone(), resource, &mut pcie_devices);
1999        }
2000    }
2001
2002    for args in &opt.virtio_fs_shmem {
2003        let resource: Resource<VirtioDeviceHandle> = virtio_resources::fs::VirtioFsHandle {
2004            tag: args.tag.clone(),
2005            fs: virtio_resources::fs::VirtioFsBackend::SectionFs {
2006                root_path: args.path.clone(),
2007            },
2008        }
2009        .into_resource();
2010        if let Some(pcie_port) = &args.pcie_port {
2011            pcie_devices.push(PcieDeviceConfig {
2012                port_name: pcie_port.clone(),
2013                resource: VirtioPciDeviceHandle(resource).into_resource(),
2014            });
2015        } else {
2016            add_virtio_device(opt.virtio_fs_bus.clone(), resource, &mut pcie_devices);
2017        }
2018    }
2019
2020    for args in &opt.virtio_9p {
2021        let resource: Resource<VirtioDeviceHandle> = virtio_resources::p9::VirtioPlan9Handle {
2022            tag: args.tag.clone(),
2023            root_path: args.path.clone(),
2024            debug: opt.virtio_9p_debug,
2025        }
2026        .into_resource();
2027        if let Some(pcie_port) = &args.pcie_port {
2028            pcie_devices.push(PcieDeviceConfig {
2029                port_name: pcie_port.clone(),
2030                resource: VirtioPciDeviceHandle(resource).into_resource(),
2031            });
2032        } else {
2033            add_virtio_device(VirtioBusCli::Auto, resource, &mut pcie_devices);
2034        }
2035    }
2036
2037    if let Some(pmem_args) = &opt.virtio_pmem {
2038        let resource: Resource<VirtioDeviceHandle> = virtio_resources::pmem::VirtioPmemHandle {
2039            file: fs_err::OpenOptions::new()
2040                .read(true)
2041                .write(true)
2042                .open(&pmem_args.path)?
2043                .into(),
2044            read_only: false,
2045        }
2046        .into_resource();
2047        if let Some(pcie_port) = &pmem_args.pcie_port {
2048            pcie_devices.push(PcieDeviceConfig {
2049                port_name: pcie_port.clone(),
2050                resource: VirtioPciDeviceHandle(resource).into_resource(),
2051            });
2052        } else {
2053            add_virtio_device(VirtioBusCli::Auto, resource, &mut pcie_devices);
2054        }
2055    }
2056
2057    if opt.virtio_rng {
2058        let resource: Resource<VirtioDeviceHandle> =
2059            virtio_resources::rng::VirtioRngHandle.into_resource();
2060        if let Some(pcie_port) = &opt.virtio_rng_pcie_port {
2061            pcie_devices.push(PcieDeviceConfig {
2062                port_name: pcie_port.clone(),
2063                resource: VirtioPciDeviceHandle(resource).into_resource(),
2064            });
2065        } else {
2066            add_virtio_device(opt.virtio_rng_bus.clone(), resource, &mut pcie_devices);
2067        }
2068    }
2069
2070    if let Some(rtc) = &opt.virtio_rtc {
2071        let resource: Resource<VirtioDeviceHandle> =
2072            virtio_resources::rtc::VirtioRtcHandle.into_resource();
2073        add_virtio_device(rtc.bus.clone(), resource, &mut pcie_devices);
2074    }
2075
2076    if let Some(backend) = virtio_console_backend {
2077        let resource: Resource<VirtioDeviceHandle> =
2078            virtio_resources::console::VirtioConsoleHandle { backend }.into_resource();
2079        if let Some(pcie_port) = &opt.virtio_console_pcie_port {
2080            pcie_devices.push(PcieDeviceConfig {
2081                port_name: pcie_port.clone(),
2082                resource: VirtioPciDeviceHandle(resource).into_resource(),
2083            });
2084        } else {
2085            add_virtio_device(VirtioBusCli::Auto, resource, &mut pcie_devices);
2086        }
2087    }
2088
2089    // Handle --vhost-user arguments.
2090    #[cfg(target_os = "linux")]
2091    for vhost_cli in &opt.vhost_user {
2092        let stream =
2093            unix_socket::UnixStream::connect(&vhost_cli.socket_path).with_context(|| {
2094                format!(
2095                    "failed to connect to vhost-user socket: {}",
2096                    vhost_cli.socket_path
2097                )
2098            })?;
2099
2100        use crate::cli_args::VhostUserDeviceTypeCli;
2101        let resource: Resource<VirtioDeviceHandle> = match vhost_cli.device_type {
2102            VhostUserDeviceTypeCli::Fs {
2103                ref tag,
2104                num_queues,
2105                queue_size,
2106            } => virtio_resources::vhost_user::VhostUserFsHandle {
2107                socket: stream.into(),
2108                tag: tag.clone(),
2109                num_queues,
2110                queue_size,
2111            }
2112            .into_resource(),
2113            VhostUserDeviceTypeCli::Blk {
2114                num_queues,
2115                queue_size,
2116            } => virtio_resources::vhost_user::VhostUserBlkHandle {
2117                socket: stream.into(),
2118                num_queues,
2119                queue_size,
2120            }
2121            .into_resource(),
2122            VhostUserDeviceTypeCli::Other {
2123                device_id,
2124                ref queue_sizes,
2125            } => virtio_resources::vhost_user::VhostUserGenericHandle {
2126                socket: stream.into(),
2127                device_id,
2128                queue_sizes: queue_sizes.clone(),
2129            }
2130            .into_resource(),
2131        };
2132        if let Some(pcie_port) = &vhost_cli.pcie_port {
2133            pcie_devices.push(PcieDeviceConfig {
2134                port_name: pcie_port.clone(),
2135                resource: VirtioPciDeviceHandle(resource).into_resource(),
2136            });
2137        } else {
2138            add_virtio_device(VirtioBusCli::Auto, resource, &mut pcie_devices);
2139        }
2140    }
2141
2142    let virtio_vsock_bus = opt.virtio_vsock_bus.clone().unwrap_or(VirtioBusCli::Auto);
2143
2144    if let Some(vsock_path) = &opt.virtio_vsock_path {
2145        let listener = vsock_listener(Some(vsock_path))?.unwrap();
2146        let resource: Resource<VirtioDeviceHandle> = virtio_resources::vsock::VirtioVsockHandle {
2147            // The guest CID does not matter since the UDS relay does not use it. It just needs
2148            // to be some non-reserved value for the guest to use.
2149            guest_cid: 0x3,
2150            base_path: vsock_path.clone(),
2151            listener,
2152        }
2153        .into_resource();
2154        add_virtio_device(virtio_vsock_bus.clone(), resource, &mut pcie_devices);
2155    }
2156
2157    #[cfg(target_os = "linux")]
2158    if let Some(guest_cid) = opt.virtio_vsock_vhost_cid {
2159        let vhost = std::fs::OpenOptions::new()
2160            .read(true)
2161            .write(true)
2162            .open("/dev/vhost-vsock")
2163            .context("failed to open /dev/vhost-vsock")?
2164            .into();
2165        let resource =
2166            virtio_resources::vsock::VirtioVsockVhostHandle { vhost, guest_cid }.into_resource();
2167        add_virtio_device(virtio_vsock_bus, resource, &mut pcie_devices);
2168    }
2169
2170    #[cfg(target_os = "linux")]
2171    pcie_devices.extend(vfio_pcie_devices);
2172
2173    let mut cfg = Config {
2174        chipset,
2175        load_mode,
2176        floppy_disks,
2177        pcie_root_complexes,
2178        pcie_ecam_below_4gb: opt.pcie_ecam_below_4gb,
2179        #[cfg(target_os = "linux")]
2180        pcie_devices,
2181        #[cfg(not(target_os = "linux"))]
2182        pcie_devices,
2183        pcie_switches,
2184        pcie_generic_initiators,
2185        vpci_devices,
2186        ide_disks: Vec::new(),
2187        numa: {
2188            if let Some(ref nodes) = opt.numa {
2189                // --numa mode: each --numa flag defines a node.
2190                NumaTopology {
2191                    nodes: nodes
2192                        .iter()
2193                        .map(|n| {
2194                            let vps = match &n.vps {
2195                                Some(vps) if vps.0.is_empty() => VpAssignment::Empty,
2196                                Some(vps) => {
2197                                    VpAssignment::Explicit(vps.expand_below(opt.processors)?)
2198                                }
2199                                None => VpAssignment::FromTopology,
2200                            };
2201                            Ok(NumaNode {
2202                                mem: Some(MemoryConfig {
2203                                    mem_size: n
2204                                        .memory
2205                                        .size
2206                                        .expect("NUMA memory size was validated")
2207                                        .0,
2208                                    prefetch_memory: n.memory.prefetch,
2209                                    private_memory: n.memory.shared == Some(false),
2210                                    transparent_hugepages: n
2211                                        .memory
2212                                        .transparent_hugepages
2213                                        .unwrap_or(!n.memory.hugepages),
2214                                    hugepages: n.memory.hugepages,
2215                                    hugepage_size: n.memory.hugepage_size.map(|m| m.0),
2216                                    host_numa_node: n.host_numa_node,
2217                                }),
2218                                vps,
2219                            })
2220                        })
2221                        .collect::<anyhow::Result<Vec<_>>>()?,
2222                    distances: opt
2223                        .numa_distance
2224                        .as_deref()
2225                        .unwrap_or(&[])
2226                        .iter()
2227                        .map(|d| NumaDistance {
2228                            src: d.src,
2229                            dst: d.dst,
2230                            distance: d.distance,
2231                        })
2232                        .collect(),
2233                }
2234            } else {
2235                // Single-node default from --memory.
2236                NumaTopology {
2237                    nodes: vec![NumaNode {
2238                        mem: Some(MemoryConfig {
2239                            mem_size: opt.memory_size(),
2240                            prefetch_memory: opt.prefetch_memory(),
2241                            private_memory: opt.private_memory(),
2242                            transparent_hugepages: opt.transparent_hugepages(),
2243                            hugepages: opt.memory.hugepages,
2244                            hugepage_size: opt.memory.hugepage_size.map(|m| m.0),
2245                            host_numa_node: None,
2246                        }),
2247                        vps: VpAssignment::FromTopology,
2248                    }],
2249                    distances: vec![],
2250                }
2251            }
2252        },
2253        processor_topology: ProcessorTopologyConfig {
2254            proc_count: opt.processors,
2255            vps_per_socket: opt.vps_per_socket,
2256            enable_smt: match opt.smt {
2257                cli_args::SmtConfigCli::Auto => None,
2258                cli_args::SmtConfigCli::Force => Some(true),
2259                cli_args::SmtConfigCli::Off => Some(false),
2260            },
2261            arch: Some(topology_arch),
2262        },
2263        hypervisor: HypervisorConfig {
2264            with_hv,
2265            with_vtl2: opt.vtl2.then_some(Vtl2Config {
2266                vtl0_alias_map: !opt.no_alias_map,
2267                late_map_vtl0_memory: match opt.late_map_vtl0_policy {
2268                    cli_args::Vtl0LateMapPolicyCli::Off => None,
2269                    cli_args::Vtl0LateMapPolicyCli::Log => Some(LateMapVtl0MemoryPolicy::Log),
2270                    cli_args::Vtl0LateMapPolicyCli::Halt => Some(LateMapVtl0MemoryPolicy::Halt),
2271                    cli_args::Vtl0LateMapPolicyCli::Exception => {
2272                        Some(LateMapVtl0MemoryPolicy::InjectException)
2273                    }
2274                },
2275            }),
2276            with_isolation,
2277            nested_virt: opt.nested_virt,
2278        },
2279        disable_guest_memory_locking: opt.force_guest_memory_bounce,
2280        #[cfg(windows)]
2281        kernel_vmnics,
2282        input: mesh::Receiver::new(),
2283        framebuffer,
2284        vga_firmware,
2285        vtl2_gfx: opt.vtl2_gfx,
2286        virtio_devices,
2287        vmbus: (with_hv && !opt.no_vmbus).then_some(VmbusConfig {
2288            vsock_listener: vtl0_vsock_listener,
2289            vsock_path: opt.vmbus_vsock_path.clone(),
2290            vtl2_redirect: opt.vmbus_redirect,
2291            vmbus_max_version: opt.vmbus_max_version,
2292            #[cfg(windows)]
2293            vmbusproxy_handle,
2294        }),
2295        vtl2_vmbus: (with_hv && opt.vtl2).then_some(VmbusConfig {
2296            vsock_listener: vtl2_vsock_listener,
2297            vsock_path: opt.vmbus_vtl2_vsock_path.clone(),
2298            ..Default::default()
2299        }),
2300        vmbus_devices,
2301        chipset_devices,
2302        pci_chipset_devices,
2303        isa_dma_controller,
2304        chipset_capabilities: capabilities,
2305        layout: layout_config,
2306        #[cfg(windows)]
2307        vpci_resources,
2308        vmgs,
2309        firmware_event_send: None,
2310        debugger_rpc: None,
2311        rtc_delta_milliseconds: 0,
2312    };
2313
2314    storage.build_config(&mut cfg, &mut resources, opt.scsi_sub_channels)?;
2315    let mut pcie_port_names = HashSet::new();
2316    for device in &cfg.pcie_devices {
2317        anyhow::ensure!(
2318            pcie_port_names.insert(&device.port_name),
2319            "multiple devices use PCIe port '{}'",
2320            device.port_name
2321        );
2322    }
2323    resources.serial_driver = Some(serial_driver);
2324    validate_snp_config(&cfg)?;
2325    Ok((cfg, resources))
2326}
2327
2328fn validate_snp_config(cfg: &Config) -> anyhow::Result<()> {
2329    if !matches!(
2330        cfg.hypervisor.with_isolation,
2331        Some(openvmm_defs::config::IsolationType::Snp { .. })
2332    ) {
2333        return Ok(());
2334    }
2335
2336    if !matches!(
2337        cfg.load_mode,
2338        LoadMode::Linux { .. } | LoadMode::Igvm { .. }
2339    ) {
2340        anyhow::bail!("SNP isolation currently only supports Linux direct or IGVM boot");
2341    }
2342    if cfg.hypervisor.with_vtl2.is_some() {
2343        anyhow::bail!("SNP isolation currently does not support VTL2");
2344    }
2345    if cfg.vmbus.is_some() || cfg.vtl2_vmbus.is_some() || !cfg.vmbus_devices.is_empty() {
2346        anyhow::bail!("SNP isolation currently does not support VMBus devices");
2347    }
2348
2349    let only_supported_chipset_devices = cfg.chipset_devices.iter().all(|device| {
2350        matches!(
2351            device.resource.id(),
2352            "serial_16550"
2353                | "pic"
2354                | "pit"
2355                | "generic-ioapic"
2356                | "hyperv_power_management"
2357                | "missing-dev"
2358        )
2359    });
2360    let only_virtio_pcie_devices = cfg
2361        .pcie_devices
2362        .iter()
2363        .all(|device| device.resource.id() == "virtio");
2364    if !cfg.floppy_disks.is_empty()
2365        || !cfg.ide_disks.is_empty()
2366        || !cfg.virtio_devices.is_empty()
2367        || !only_virtio_pcie_devices
2368        || !cfg.vpci_devices.is_empty()
2369        || !only_supported_chipset_devices
2370        || !cfg.pci_chipset_devices.is_empty()
2371    {
2372        anyhow::bail!("SNP isolation currently only supports virtio devices");
2373    }
2374    if cfg.framebuffer.is_some() || cfg.vga_firmware.is_some() || cfg.debugger_rpc.is_some() {
2375        anyhow::bail!("SNP isolation currently does not support this VM configuration");
2376    }
2377
2378    Ok(())
2379}
2380
2381/// Gets the terminal to use for externally launched console windows.
2382pub(crate) fn openvmm_terminal_app() -> Option<PathBuf> {
2383    std::env::var_os("OPENVMM_TERM")
2384        .or_else(|| std::env::var_os("HVLITE_TERM"))
2385        .map(Into::into)
2386}
2387
2388// Tries to remove `path` if it is confirmed to be a Unix socket.
2389fn cleanup_socket(path: &Path) {
2390    let is_socket = cfg_select! {
2391        windows => pal::windows::fs::is_unix_socket(path).unwrap_or(false),
2392        _ => path
2393            .metadata()
2394            .is_ok_and(|meta| std::os::unix::fs::FileTypeExt::is_socket(&meta.file_type())),
2395    };
2396
2397    if is_socket {
2398        let _ = std::fs::remove_file(path);
2399    }
2400}
2401
2402#[cfg(windows)]
2403fn new_switch_port(
2404    switch_id: Option<&str>,
2405) -> anyhow::Result<(
2406    openvmm_defs::config::SwitchPortId,
2407    vmswitch::kernel::SwitchPort,
2408)> {
2409    let id = vmswitch::kernel::SwitchPortId {
2410        switch: match switch_id {
2411            Some(s) => s.parse().context("invalid switch id")?,
2412            None => vmswitch::hcn::DEFAULT_SWITCH,
2413        },
2414        port: Guid::new_random(),
2415    };
2416    let _ = vmswitch::hcn::Network::open(&id.switch)
2417        .with_context(|| format!("could not find switch {}", id.switch))?;
2418
2419    let port = vmswitch::kernel::SwitchPort::new(&id).context("failed to create switch port")?;
2420
2421    let id = openvmm_defs::config::SwitchPortId {
2422        switch: id.switch,
2423        port: id.port,
2424    };
2425    Ok((id, port))
2426}
2427
2428fn parse_endpoint(
2429    cli_cfg: &NicConfigCli,
2430    index: &mut usize,
2431    resources: &mut VmResources,
2432) -> anyhow::Result<NicConfig> {
2433    let _ = resources;
2434    let endpoint = match &cli_cfg.endpoint {
2435        EndpointConfigCli::Consomme { cidr, host_fwd } => {
2436            let ports = host_fwd
2437                .iter()
2438                .map(|fwd| {
2439                    use net_backend_resources::consomme::HostPortProtocol;
2440                    net_backend_resources::consomme::HostPortConfig {
2441                        protocol: match fwd.protocol {
2442                            cli_args::HostPortProtocolCli::Tcp => HostPortProtocol::Tcp,
2443                            cli_args::HostPortProtocolCli::Udp => HostPortProtocol::Udp,
2444                        },
2445                        host_address: fwd
2446                            .host_address
2447                            .map(net_backend_resources::consomme::HostIpAddress::from),
2448                        host_port: net_backend_resources::consomme::HostPort::Fixed(fwd.host_port),
2449                        guest_port: fwd.guest_port,
2450                    }
2451                })
2452                .collect();
2453            // Only wire the bind/unbind RPC channel to the first consomme
2454            // endpoint. Additional consomme NICs work normally but cannot be
2455            // targeted by runtime bind/unbind commands.
2456            let recv = if resources.consomme_rpc.is_none() {
2457                let (send, recv) = mesh::channel();
2458                resources.consomme_rpc = Some(send);
2459                Some(recv)
2460            } else {
2461                None
2462            };
2463            net_backend_resources::consomme::ConsommeHandle {
2464                cidr: cidr.clone(),
2465                params: Default::default(),
2466                ports,
2467                internal_dns: true,
2468                recv,
2469            }
2470            .into_resource()
2471        }
2472        EndpointConfigCli::None => net_backend_resources::null::NullHandle.into_resource(),
2473        EndpointConfigCli::Dio { id } => cfg_select! {
2474            windows => {{
2475                let (port_id, port) = new_switch_port(id.as_deref())?;
2476                resources.switch_ports.push(port);
2477                net_backend_resources::dio::WindowsDirectIoHandle {
2478                    switch_port_id: net_backend_resources::dio::SwitchPortId {
2479                        switch: port_id.switch,
2480                        port: port_id.port,
2481                    },
2482                }
2483                .into_resource()
2484            }}
2485            _ => {{
2486                let _ = id;
2487                bail!("cannot use dio on non-windows platforms")
2488            }}
2489        },
2490        EndpointConfigCli::Tap { name } => cfg_select! {
2491            target_os = "linux" => {{
2492                let fd = net_tap::tap::open_tap(name)
2493                    .with_context(|| format!("failed to open TAP device '{name}'"))?;
2494                net_backend_resources::tap::TapHandle { fd }.into_resource()
2495            }}
2496            _ => {{
2497                let _ = name;
2498                bail!("TAP backend is only supported on Linux")
2499            }}
2500        },
2501    };
2502
2503    let mac_address = cli_cfg.mac_address.unwrap_or_else(|| {
2504        let mut mac_address = [0x00, 0x15, 0x5D, 0, 0, 0];
2505        getrandom::fill(&mut mac_address[3..]).expect("rng failure");
2506        mac_address.into()
2507    });
2508
2509    // Pick a fixed instance ID based on the index.
2510    const BASE_INSTANCE_ID: Guid = guid::guid!("00000000-da43-11ed-936a-00155d6db52f");
2511    let instance_id = Guid {
2512        data1: *index as u32,
2513        ..BASE_INSTANCE_ID
2514    };
2515    *index += 1;
2516
2517    Ok(NicConfig {
2518        vtl: cli_cfg.vtl,
2519        instance_id,
2520        endpoint,
2521        mac_address,
2522        max_queues: cli_cfg.max_queues,
2523        enable_rx_gso: cli_cfg.enable_rx_gso,
2524        pcie_port: cli_cfg.pcie_port.clone(),
2525    })
2526}
2527
2528/// Returns the VPCI instance ID of the MANA device for `vtl`.
2529///
2530/// The ID is fixed so that a guest sees the same device on every boot, rather
2531/// than a new one it records alongside the old.
2532fn mana_vpci_instance_id(vtl: usize) -> Guid {
2533    const BASE_INSTANCE_ID: Guid = guid::guid!("00000000-6a35-477c-a2c0-13484df4873c");
2534    Guid {
2535        data1: vtl as u32,
2536        ..BASE_INSTANCE_ID
2537    }
2538}
2539
2540#[derive(Debug)]
2541struct NicConfig {
2542    vtl: DeviceVtl,
2543    instance_id: Guid,
2544    mac_address: MacAddress,
2545    endpoint: Resource<NetEndpointHandleKind>,
2546    max_queues: Option<u16>,
2547    enable_rx_gso: bool,
2548    pcie_port: Option<String>,
2549}
2550
2551impl NicConfig {
2552    fn into_netvsp_handle(self) -> (DeviceVtl, Resource<VmbusDeviceHandleKind>) {
2553        (
2554            self.vtl,
2555            netvsp_resources::NetvspHandle {
2556                instance_id: self.instance_id,
2557                mac_address: self.mac_address,
2558                endpoint: self.endpoint,
2559                max_queues: self.max_queues,
2560            }
2561            .into_resource(),
2562        )
2563    }
2564}
2565
2566fn non_volatile_store_resource(
2567    with_vmgs: bool,
2568    file_id: vmgs_format::FileId,
2569) -> Resource<NonVolatileStoreKind> {
2570    if with_vmgs {
2571        VmgsFileHandle::new(file_id, true).into_resource()
2572    } else {
2573        EphemeralNonVolatileStoreHandle.into_resource()
2574    }
2575}
2576
2577async fn open_vmgs(
2578    kind: &DiskCliKind,
2579    provision: ProvisionCondition,
2580    encryption_policy: GuestStateEncryptionPolicy,
2581) -> anyhow::Result<VmgsResource> {
2582    let disk = VmgsDisk {
2583        disk: disk_open(kind, false).await?,
2584        encryption_policy,
2585    };
2586    Ok(match provision {
2587        ProvisionCondition::OnEmpty => VmgsResource::Disk(disk),
2588        ProvisionCondition::OnFailure => VmgsResource::ReprovisionOnFailure(disk),
2589        ProvisionCondition::Single => VmgsResource::ReprovisionSingle(disk),
2590    })
2591}
2592
2593enum LayerOrDisk {
2594    Layer(DiskLayerDescription),
2595    Disk(Resource<DiskHandleKind>),
2596}
2597
2598async fn disk_open(
2599    disk_cli: &DiskCliKind,
2600    read_only: bool,
2601) -> anyhow::Result<Resource<DiskHandleKind>> {
2602    let mut layers = Vec::new();
2603    disk_open_inner(disk_cli, read_only, &mut layers).await?;
2604    if layers.len() == 1 && matches!(layers[0], LayerOrDisk::Disk(_)) {
2605        let LayerOrDisk::Disk(disk) = layers.pop().unwrap() else {
2606            unreachable!()
2607        };
2608        Ok(disk)
2609    } else {
2610        Ok(Resource::new(disk_backend_resources::LayeredDiskHandle {
2611            layers: layers
2612                .into_iter()
2613                .map(|layer| match layer {
2614                    LayerOrDisk::Layer(layer) => layer,
2615                    LayerOrDisk::Disk(disk) => DiskLayerDescription {
2616                        layer: DiskLayerHandle(disk).into_resource(),
2617                        read_cache: false,
2618                        write_through: false,
2619                    },
2620                })
2621                .collect(),
2622        }))
2623    }
2624}
2625
2626fn disk_open_inner<'a>(
2627    disk_cli: &'a DiskCliKind,
2628    read_only: bool,
2629    layers: &'a mut Vec<LayerOrDisk>,
2630) -> futures::future::BoxFuture<'a, anyhow::Result<()>> {
2631    Box::pin(async move {
2632        fn layer<T: IntoResource<DiskLayerHandleKind>>(layer: T) -> LayerOrDisk {
2633            LayerOrDisk::Layer(layer.into_resource().into())
2634        }
2635        fn disk<T: IntoResource<DiskHandleKind>>(disk: T) -> LayerOrDisk {
2636            LayerOrDisk::Disk(disk.into_resource())
2637        }
2638        match disk_cli {
2639            &DiskCliKind::Memory(len) => {
2640                layers.push(layer(RamDiskLayerHandle {
2641                    len: Some(len),
2642                    sector_size: None,
2643                }));
2644            }
2645            DiskCliKind::File {
2646                path,
2647                create_with_len,
2648                direct,
2649            } => layers.push(LayerOrDisk::Disk(if let Some(size) = create_with_len {
2650                create_disk_type(
2651                    path,
2652                    *size,
2653                    OpenDiskOptions {
2654                        read_only: false,
2655                        direct: *direct,
2656                    },
2657                )
2658                .with_context(|| format!("failed to create {}", path.display()))?
2659            } else {
2660                open_disk_type(
2661                    path,
2662                    OpenDiskOptions {
2663                        read_only,
2664                        direct: *direct,
2665                    },
2666                )
2667                .await
2668                .with_context(|| format!("failed to open {}", path.display()))?
2669            })),
2670            DiskCliKind::Blob { kind, url } => {
2671                layers.push(disk(disk_backend_resources::BlobDiskHandle {
2672                    url: url.to_owned(),
2673                    format: match kind {
2674                        cli_args::BlobKind::Flat => disk_backend_resources::BlobDiskFormat::Flat,
2675                        cli_args::BlobKind::Vhd1 => {
2676                            disk_backend_resources::BlobDiskFormat::FixedVhd1
2677                        }
2678                    },
2679                }))
2680            }
2681            DiskCliKind::MemoryDiff(inner) => {
2682                layers.push(layer(RamDiskLayerHandle {
2683                    len: None,
2684                    sector_size: None,
2685                }));
2686                disk_open_inner(inner, true, layers).await?;
2687            }
2688            DiskCliKind::PersistentReservationsWrapper(inner) => {
2689                layers.push(disk(disk_backend_resources::DiskWithReservationsHandle(
2690                    disk_open(inner, read_only).await?,
2691                )))
2692            }
2693            DiskCliKind::DelayDiskWrapper {
2694                delay_ms,
2695                disk: inner,
2696            } => layers.push(disk(DelayDiskHandle {
2697                delay: CellUpdater::new(Duration::from_millis(*delay_ms)).cell(),
2698                disk: disk_open(inner, read_only).await?,
2699            })),
2700            DiskCliKind::Crypt {
2701                disk: inner,
2702                cipher,
2703                key_file,
2704            } => layers.push(disk(disk_crypt_resources::DiskCryptHandle {
2705                disk: disk_open(inner, read_only).await?,
2706                cipher: match cipher {
2707                    cli_args::DiskCipher::XtsAes256 => disk_crypt_resources::Cipher::XtsAes256,
2708                },
2709                key: fs_err::read(key_file).context("failed to read key file")?,
2710            })),
2711            DiskCliKind::Sqlite {
2712                path,
2713                create_with_len,
2714            } => {
2715                // FUTURE: this code should be responsible for opening
2716                // file-handle(s) itself, and passing them into sqlite via a custom
2717                // vfs. For now though - simply check if the file exists or not, and
2718                // perform early validation of filesystem-level create options.
2719                match (create_with_len.is_some(), path.exists()) {
2720                    (true, true) => anyhow::bail!(
2721                        "cannot create new sqlite disk at {} - file already exists",
2722                        path.display()
2723                    ),
2724                    (false, false) => anyhow::bail!(
2725                        "cannot open sqlite disk at {} - file not found",
2726                        path.display()
2727                    ),
2728                    _ => {}
2729                }
2730
2731                layers.push(layer(SqliteDiskLayerHandle {
2732                    dbhd_path: path.display().to_string(),
2733                    format_dbhd: create_with_len.map(|len| {
2734                        disk_backend_resources::layer::SqliteDiskLayerFormatParams {
2735                            logically_read_only: false,
2736                            len: Some(len),
2737                        }
2738                    }),
2739                }));
2740            }
2741            DiskCliKind::SqliteDiff { path, create, disk } => {
2742                // FUTURE: this code should be responsible for opening
2743                // file-handle(s) itself, and passing them into sqlite via a custom
2744                // vfs. For now though - simply check if the file exists or not, and
2745                // perform early validation of filesystem-level create options.
2746                match (create, path.exists()) {
2747                    (true, true) => anyhow::bail!(
2748                        "cannot create new sqlite disk at {} - file already exists",
2749                        path.display()
2750                    ),
2751                    (false, false) => anyhow::bail!(
2752                        "cannot open sqlite disk at {} - file not found",
2753                        path.display()
2754                    ),
2755                    _ => {}
2756                }
2757
2758                layers.push(layer(SqliteDiskLayerHandle {
2759                    dbhd_path: path.display().to_string(),
2760                    format_dbhd: create.then_some(
2761                        disk_backend_resources::layer::SqliteDiskLayerFormatParams {
2762                            logically_read_only: false,
2763                            len: None,
2764                        },
2765                    ),
2766                }));
2767                disk_open_inner(disk, true, layers).await?;
2768            }
2769            DiskCliKind::AutoCacheSqlite {
2770                cache_path,
2771                key,
2772                disk,
2773            } => {
2774                layers.push(LayerOrDisk::Layer(DiskLayerDescription {
2775                    read_cache: true,
2776                    write_through: false,
2777                    layer: SqliteAutoCacheDiskLayerHandle {
2778                        cache_path: cache_path.clone(),
2779                        cache_key: key.clone(),
2780                    }
2781                    .into_resource(),
2782                }));
2783                disk_open_inner(disk, read_only, layers).await?;
2784            }
2785        }
2786        Ok(())
2787    })
2788}
2789
2790/// Get the system page size.
2791pub(crate) fn system_page_size() -> u32 {
2792    sparse_mmap::SparseMapping::page_size() as u32
2793}
2794
2795/// The guest architecture string, derived from the compile-time `guest_arch` cfg.
2796pub(crate) const GUEST_ARCH: &str = cfg_select! {
2797    guest_arch = "x86_64" => "x86_64",
2798    guest_arch = "aarch64" => "aarch64",
2799};
2800
2801/// Open a snapshot directory and validate it against the current VM config.
2802/// Returns the shared memory fd (from memory.bin) and the saved device state.
2803fn prepare_snapshot_restore(
2804    snapshot_dir: &Path,
2805    opt: &Options,
2806) -> anyhow::Result<(
2807    openvmm_defs::worker::SharedMemoryFd,
2808    mesh::payload::message::ProtobufMessage,
2809)> {
2810    let snapshot = openvmm_helpers::snapshot::restore::OpenedSnapshot::open(snapshot_dir)?;
2811
2812    // Validate manifest against current VM config.
2813    openvmm_helpers::snapshot::validate_manifest(
2814        snapshot.manifest(),
2815        GUEST_ARCH,
2816        opt.memory_size(),
2817        opt.processors,
2818        system_page_size(),
2819    )?;
2820
2821    // Use the memory.bin that was opened with the snapshot, after checking
2822    // that it has the size that the manifest records.
2823    let memory_file = snapshot.duplicate_memory_file()?;
2824    let shared_memory_fd = openvmm_helpers::shared_memory::file_to_shared_memory_fd(memory_file)?;
2825
2826    // Reconstruct ProtobufMessage from the saved state bytes.
2827    // The save side wrote mesh::payload::encode(ProtobufMessage), so we decode
2828    // back to ProtobufMessage.
2829    let state_msg: mesh::payload::message::ProtobufMessage =
2830        mesh::payload::decode(snapshot.state_bytes())
2831            .context("failed to decode saved state from snapshot")?;
2832
2833    Ok((shared_memory_fd, state_msg))
2834}
2835
2836fn do_main(pidfile_guard: &mut Option<pidfile::Pidfile>) -> anyhow::Result<i32> {
2837    #[cfg(windows)]
2838    pal::windows::disable_hard_error_dialog();
2839
2840    let _tracing_guard = tracing_init::enable_tracing()?;
2841
2842    // Try to run as a worker host.
2843    // On success the worker runs to completion and then exits the process (does
2844    // not return). Any worker host setup errors are return and bubbled up.
2845    meshworker::run_vmm_mesh_host()?;
2846
2847    let opt = cli_args::parse_options();
2848    opt.validate_vm_options()?;
2849
2850    // Print the version number. This comes after argument parsing to not interfere
2851    // with --version and --help.
2852    tracing::info!(version = openvmm_build_info::get().version());
2853
2854    if let Some(path) = &opt.write_saved_state_proto {
2855        mesh::payload::protofile::DescriptorWriter::new(vmcore::save_restore::saved_state_roots())
2856            .write_to_path(path)
2857            .context("failed to write protobuf descriptors")?;
2858        return Ok(0);
2859    }
2860
2861    if let Some(ref path) = opt.pidfile {
2862        *pidfile_guard = Some(pidfile::Pidfile::new(path).context("failed to create pidfile")?);
2863    }
2864
2865    if let Some(path) = opt.relay_console_path {
2866        let console_title = opt.relay_console_title.unwrap_or_default();
2867        return console_relay::relay_console(&path, console_title.as_str()).map(|()| 0);
2868    }
2869
2870    #[cfg(any(feature = "grpc", feature = "ttrpc"))]
2871    {
2872        let rpc = opt
2873            .rpc
2874            .as_ref()
2875            .map(|rpc| {
2876                let transport = match rpc.transport {
2877                    cli_args::RpcTransportCli::Auto => ttrpc::RpcTransport::Auto,
2878                    cli_args::RpcTransportCli::Ttrpc => ttrpc::RpcTransport::Ttrpc,
2879                    cli_args::RpcTransportCli::Grpc => ttrpc::RpcTransport::Grpc,
2880                };
2881                (rpc.path.as_path(), transport)
2882            })
2883            .or_else(|| {
2884                opt.ttrpc
2885                    .as_deref()
2886                    .map(|p| (p, ttrpc::RpcTransport::Ttrpc))
2887            })
2888            .or_else(|| opt.grpc.as_deref().map(|p| (p, ttrpc::RpcTransport::Grpc)));
2889
2890        if let Some((path, transport)) = rpc {
2891            return block_on(async {
2892                let _ = std::fs::remove_file(path);
2893                let listener =
2894                    unix_socket::UnixListener::bind(path).context("failed to bind to socket")?;
2895
2896                // This is a local launch
2897                let (exit_code_send, exit_code_recv) = mesh::oneshot();
2898                let mut handle =
2899                    mesh_worker::launch_local_worker::<ttrpc::TtrpcWorker>(ttrpc::Parameters {
2900                        listener,
2901                        transport,
2902                        exit_code: exit_code_send,
2903                    })
2904                    .await?;
2905
2906                tracing::info!(%transport, path = %path.display(), "listening");
2907
2908                // Signal the parent process that the server is ready.
2909                pal::close_stdout().context("failed to close stdout")?;
2910
2911                handle.join().await?;
2912
2913                exit_code_recv
2914                    .await
2915                    .context("RPC worker did not report an exit code")
2916            });
2917        }
2918    }
2919
2920    DefaultPool::run_with(async |driver| run_control(&driver, opt).await)
2921}
2922
2923fn new_hvsock_service_id(port: u32) -> Guid {
2924    // This GUID is an embedding of the AF_VSOCK port into an
2925    // AF_HYPERV service ID.
2926    Guid {
2927        data1: port,
2928        .."00000000-facb-11e6-bd58-64006a7986d3".parse().unwrap()
2929    }
2930}
2931
2932async fn run_control(driver: &DefaultDriver, opt: Options) -> anyhow::Result<i32> {
2933    let mut mesh = Some(VmmMesh::new(&driver, opt.single_process)?);
2934    let result = run_control_inner(driver, &mut mesh, opt).await;
2935    // If setup failed before the mesh was handed to the controller, shut it
2936    // down so the child host process exits cleanly without noisy logs.
2937    if let Some(mesh) = mesh {
2938        mesh.shutdown().await;
2939    }
2940    result
2941}
2942
2943async fn run_control_inner(
2944    driver: &DefaultDriver,
2945    mesh_slot: &mut Option<VmmMesh>,
2946    mut opt: Options,
2947) -> anyhow::Result<i32> {
2948    let hypervisor = match &opt.hypervisor {
2949        Some(name) => openvmm_helpers::hypervisor::hypervisor_resource(name)?,
2950        None => openvmm_helpers::hypervisor::choose_hypervisor()?,
2951    };
2952    // Keep general validation tied to the selected backend, including auto.
2953    opt.hypervisor = Some(hypervisor.id().to_owned());
2954    let mesh = mesh_slot.as_ref().unwrap();
2955    let (mut vm_config, mut resources) = vm_config_from_command_line(driver, mesh, &opt).await?;
2956
2957    let mut vnc_worker = None;
2958    if opt.gfx || opt.vnc.vnc {
2959        // Parse the listen address. Try as a full SocketAddr (host:port) first;
2960        // fall back to a bare IP, using the configured port.
2961        let addr: std::net::SocketAddr = if let Ok(sa) =
2962            opt.vnc.vnc_listen.parse::<std::net::SocketAddr>()
2963        {
2964            sa
2965        } else {
2966            let ip: std::net::IpAddr = opt.vnc.vnc_listen.parse().with_context(|| {
2967                format!(
2968                    "invalid VNC listen address: {} (expected IP address or socket address like [::1]:5900)",
2969                    opt.vnc.vnc_listen
2970                )
2971            })?;
2972            std::net::SocketAddr::new(ip, opt.vnc.vnc_port)
2973        };
2974
2975        let socket = socket2::Socket::new(
2976            if addr.is_ipv6() {
2977                socket2::Domain::IPV6
2978            } else {
2979                socket2::Domain::IPV4
2980            },
2981            socket2::Type::STREAM,
2982            None,
2983        )
2984        .with_context(|| format!("creating VNC socket for {}", addr))?;
2985
2986        if addr.is_ipv6() {
2987            if let Err(e) = socket.set_only_v6(false) {
2988                tracing::warn!(
2989                    error = %e,
2990                    "failed to enable dual-stack on IPv6 VNC socket, IPv4 clients may not be able to connect"
2991                );
2992            }
2993        }
2994        socket.set_reuse_address(true)?;
2995        socket
2996            .bind(&addr.into())
2997            .with_context(|| format!("binding VNC socket to {}", addr))?;
2998        socket
2999            .listen(128)
3000            .with_context(|| format!("listening on VNC socket {}", addr))?;
3001        let listener: TcpListener = socket.into();
3002
3003        if !addr.ip().is_loopback() {
3004            tracing::warn!(
3005                address = %addr,
3006                "VNC server listening on non-localhost address without authentication"
3007            );
3008        }
3009
3010        let input_send = vm_config.input.sender();
3011        let framebuffer = resources
3012            .framebuffer_access
3013            .take()
3014            .expect("synth video enabled");
3015
3016        let vnc_host = mesh
3017            .make_host("vnc", None)
3018            .await
3019            .context("spawning vnc process failed")?;
3020
3021        vnc_worker = Some(
3022            vnc_host
3023                .launch_worker(
3024                    vnc_worker_defs::VNC_WORKER_TCP,
3025                    VncParameters {
3026                        listener,
3027                        framebuffer,
3028                        input_send,
3029                        dirty_recv: resources.dirty_rect_recv.take(),
3030                        max_clients: opt.vnc.vnc_max_clients,
3031                        evict_oldest: opt.vnc.vnc_evict_oldest,
3032                    },
3033                )
3034                .await?,
3035        )
3036    }
3037
3038    // spin up the debug worker
3039    let gdb_worker = if let Some(port) = opt.gdb {
3040        let listener = TcpListener::bind(format!("127.0.0.1:{}", port))
3041            .with_context(|| format!("binding to gdb port {}", port))?;
3042
3043        let (req_tx, req_rx) = mesh::channel();
3044        vm_config.debugger_rpc = Some(req_rx);
3045
3046        let gdb_host = mesh
3047            .make_host("gdb", None)
3048            .await
3049            .context("spawning gdbstub process failed")?;
3050
3051        Some(
3052            gdb_host
3053                .launch_worker(
3054                    debug_worker_defs::DEBUGGER_WORKER,
3055                    debug_worker_defs::DebuggerParameters {
3056                        listener,
3057                        req_chan: req_tx,
3058                        vp_count: vm_config.processor_topology.proc_count,
3059                        target_arch: cfg_select! {
3060                            guest_arch = "x86_64" => debug_worker_defs::TargetArch::X86_64,
3061                            guest_arch = "aarch64" => debug_worker_defs::TargetArch::Aarch64,
3062                        },
3063                    },
3064                )
3065                .await
3066                .context("failed to launch gdbstub worker")?,
3067        )
3068    } else {
3069        None
3070    };
3071
3072    // spin up the VM
3073    let (vm_rpc, rpc_recv) = mesh::channel();
3074    let (notify_send, notify_recv) = mesh::channel();
3075    let vm_worker = {
3076        let vm_host = mesh.make_host("vm", opt.log_file.clone()).await?;
3077
3078        let (shared_memory, saved_state) = if let Some(snapshot_dir) = &opt.restore_snapshot {
3079            let (fd, state_msg) = prepare_snapshot_restore(snapshot_dir, &opt)?;
3080            (Some(fd), Some(state_msg))
3081        } else {
3082            let shared_memory = opt
3083                .memory_backing_file()
3084                .map(|path| {
3085                    openvmm_helpers::shared_memory::open_memory_backing_file(
3086                        path,
3087                        opt.memory_size(),
3088                    )
3089                })
3090                .transpose()?;
3091            (shared_memory, None)
3092        };
3093
3094        let params = VmWorkerParameters {
3095            hypervisor,
3096            cfg: vm_config,
3097            saved_state,
3098            guest_ram: shared_memory.map(GuestRamSource::MapShared),
3099            rpc: rpc_recv,
3100            notify: notify_send,
3101        };
3102        vm_host
3103            .launch_worker(VM_WORKER, params)
3104            .await
3105            .context("failed to launch vm worker")?
3106    };
3107
3108    if opt.restore_snapshot.is_some() {
3109        tracing::info!("restoring VM from snapshot");
3110    }
3111
3112    if !opt.paused {
3113        vm_rpc.call(VmRpc::Resume, ()).await?;
3114    }
3115
3116    let paravisor_diag = Arc::new(diag_client::DiagClient::from_dialer(
3117        driver.clone(),
3118        DiagDialer {
3119            driver: driver.clone(),
3120            vm_rpc: vm_rpc.clone(),
3121            openhcl_vtl: if opt.vtl2 {
3122                DeviceVtl::Vtl2
3123            } else {
3124                DeviceVtl::Vtl0
3125            },
3126        },
3127    ));
3128
3129    let diag_inspector = DiagInspector::new(driver.clone(), paravisor_diag.clone());
3130
3131    // Create channels between the REPL and VmController.
3132    let (vm_controller_send, vm_controller_recv) = mesh::channel();
3133    let (vm_controller_event_send, vm_controller_event_recv) = mesh::channel();
3134
3135    let has_vtl2 = resources.vtl2_settings.is_some();
3136    let serial_driver = resources
3137        .serial_driver
3138        .take()
3139        .expect("serial driver must outlive serial resources");
3140
3141    // Build the VmController with exclusive resources.
3142    let controller = vm_controller::VmController {
3143        mesh: mesh_slot.take().unwrap(),
3144        vm_worker,
3145        vnc_worker,
3146        gdb_worker,
3147        diag_inspector: Some(diag_inspector),
3148        vtl2_settings: resources.vtl2_settings,
3149        ged_rpc: resources.ged_rpc.clone(),
3150        vm_rpc: vm_rpc.clone(),
3151        paravisor_diag: Some(paravisor_diag),
3152        igvm_path: opt.igvm.as_ref().map(|igvm| igvm.firmware.clone()),
3153        memory_backing_file: opt.memory_backing_file().cloned(),
3154        memory: opt.memory_size(),
3155        processors: opt.processors,
3156        log_file: opt.log_file.clone(),
3157        crash_dump_path: opt.crash_dump_path.clone(),
3158        guest_power_actions: vm_controller::GuestPowerActions {
3159            shutdown: opt.guest_shutdown_action,
3160            reset: opt.guest_reset_action,
3161            crash: opt.guest_crash_action,
3162            watchdog: opt.guest_watchdog_action,
3163        },
3164    };
3165
3166    // Spawn the VmController as a task.
3167    let controller_task = driver.spawn(
3168        "vm-controller",
3169        controller.run(vm_controller_recv, vm_controller_event_send, notify_recv),
3170    );
3171
3172    // Run the REPL with shareable resources.
3173    let repl_result = repl::run_repl(
3174        driver,
3175        repl::ReplResources {
3176            vm_rpc,
3177            vm_controller: vm_controller_send,
3178            vm_controller_events: vm_controller_event_recv,
3179            scsi_rpc: resources.scsi_rpc,
3180            nvme_vtl2_rpc: resources.nvme_vtl2_rpc,
3181            consomme_rpc: resources.consomme_rpc,
3182            shutdown_ic: resources.shutdown_ic,
3183            acpi_power_button: resources.acpi_power_button,
3184            kvp_ic: resources.kvp_ic,
3185            console_in: resources.console_in,
3186            has_vtl2,
3187        },
3188    )
3189    .await;
3190
3191    // Wait for the controller task to finish (it stops the VM worker and
3192    // shuts down the mesh).
3193    controller_task.await;
3194    drop(serial_driver);
3195
3196    // run_repl returns the exit status: the code the guest drove via an opt-in
3197    // exit (VmControllerEvent::ExitRequested), or 0 when the VM stopped normally.
3198    repl_result
3199}
3200
3201struct DiagDialer {
3202    driver: DefaultDriver,
3203    vm_rpc: mesh::Sender<VmRpc>,
3204    openhcl_vtl: DeviceVtl,
3205}
3206
3207impl mesh_rpc::client::Dial for DiagDialer {
3208    type Stream = PolledSocket<unix_socket::UnixStream>;
3209
3210    async fn dial(&mut self) -> io::Result<Self::Stream> {
3211        let service_id = new_hvsock_service_id(1);
3212        let socket = self
3213            .vm_rpc
3214            .call_failable(
3215                VmRpc::ConnectHvsock,
3216                (
3217                    CancelContext::new().with_timeout(Duration::from_secs(2)),
3218                    service_id,
3219                    self.openhcl_vtl,
3220                ),
3221            )
3222            .await
3223            .map_err(io::Error::other)?;
3224
3225        PolledSocket::new(&self.driver, socket)
3226    }
3227}
3228
3229/// An object that implements [`InspectMut`] by sending an inspect request over
3230/// TTRPC to the guest (typically the paravisor running in VTL2), then stitching
3231/// the response back into the inspect tree.
3232///
3233/// This also caches the TTRPC connection to the guest so that only the first
3234/// inspect request has to wait for the connection to be established.
3235pub(crate) struct DiagInspector(DiagInspectorInner);
3236
3237enum DiagInspectorInner {
3238    NotStarted(DefaultDriver, Arc<diag_client::DiagClient>),
3239    Started {
3240        send: mesh::Sender<inspect::Deferred>,
3241        _task: Task<()>,
3242    },
3243    Invalid,
3244}
3245
3246impl DiagInspector {
3247    pub fn new(driver: DefaultDriver, diag_client: Arc<diag_client::DiagClient>) -> Self {
3248        Self(DiagInspectorInner::NotStarted(driver, diag_client))
3249    }
3250
3251    fn start(&mut self) -> &mesh::Sender<inspect::Deferred> {
3252        loop {
3253            match self.0 {
3254                DiagInspectorInner::NotStarted { .. } => {
3255                    let DiagInspectorInner::NotStarted(driver, client) =
3256                        std::mem::replace(&mut self.0, DiagInspectorInner::Invalid)
3257                    else {
3258                        unreachable!()
3259                    };
3260                    let (send, recv) = mesh::channel();
3261                    let task = driver.clone().spawn("diag-inspect", async move {
3262                        Self::run(&client, recv).await
3263                    });
3264
3265                    self.0 = DiagInspectorInner::Started { send, _task: task };
3266                }
3267                DiagInspectorInner::Started { ref send, .. } => break send,
3268                DiagInspectorInner::Invalid => unreachable!(),
3269            }
3270        }
3271    }
3272
3273    async fn run(
3274        diag_client: &diag_client::DiagClient,
3275        mut recv: mesh::Receiver<inspect::Deferred>,
3276    ) {
3277        while let Some(deferred) = recv.next().await {
3278            let info = deferred.external_request();
3279            let result = match info.request_type {
3280                inspect::ExternalRequestType::Inspect { depth } => {
3281                    if depth == 0 {
3282                        Ok(inspect::Node::Unevaluated)
3283                    } else {
3284                        // TODO: Support taking timeouts from the command line
3285                        diag_client
3286                            .inspect(info.path, Some(depth - 1), Some(Duration::from_secs(1)))
3287                            .await
3288                    }
3289                }
3290                inspect::ExternalRequestType::Update { value } => {
3291                    (diag_client.update(info.path, value).await).map(inspect::Node::Value)
3292                }
3293            };
3294            deferred.complete_external(
3295                result.unwrap_or_else(|err| {
3296                    inspect::Node::Failed(inspect::Error::Mesh(format!("{err:#}")))
3297                }),
3298                inspect::SensitivityLevel::Unspecified,
3299            )
3300        }
3301    }
3302}
3303
3304impl InspectMut for DiagInspector {
3305    fn inspect_mut(&mut self, req: inspect::Request<'_>) {
3306        self.start().send(req.defer());
3307    }
3308}
3309
3310#[cfg(test)]
3311mod tests {
3312    use super::*;
3313    use clap::Parser;
3314    use std::fs::File;
3315    use test_with_tracing::test;
3316    use vm_resource::ResourceId;
3317
3318    /// The same boot flags give the same ACPI power button with and without
3319    /// `--restore-snapshot`.
3320    #[test]
3321    fn restore_builds_the_acpi_power_button_of_its_boot_command_line() {
3322        DefaultPool::run_with(async |driver| {
3323            let temp_dir = tempfile::tempdir().unwrap();
3324            let file = |name: &str| {
3325                let path = temp_dir.path().join(name);
3326                File::create(&path).unwrap();
3327                path.to_str().unwrap().to_owned()
3328            };
3329            let kernel = file("kernel");
3330            let initrd = file("initrd");
3331            let uefi = format!("--uefi=firmware={}", file("firmware"));
3332            // The config build does not read the snapshot directory.
3333            let snapshot = temp_dir.path().join("snapshot");
3334            let linux = ["--kernel", kernel.as_str(), "--initrd", initrd.as_str()];
3335
3336            for (boot, has_button) in [
3337                (linux.to_vec(), true),
3338                ([&linux[..], &["--device-tree"]].concat(), false),
3339                (vec![uefi.as_str()], true),
3340            ] {
3341                for restore in [false, true] {
3342                    let mut args = vec!["openvmm", "--single-process"];
3343                    args.extend(&boot);
3344                    if restore {
3345                        args.extend(["--restore-snapshot", snapshot.to_str().unwrap()]);
3346                    }
3347                    let opt = Options::try_parse_from(&args).unwrap();
3348                    let mesh = VmmMesh::new(&driver, true).unwrap();
3349                    let (config, _) = vm_config_from_command_line(driver.clone(), &mesh, &opt)
3350                        .await
3351                        .unwrap();
3352                    mesh.shutdown().await;
3353
3354                    let built = config
3355                        .chipset_devices
3356                        .iter()
3357                        .any(|device| device.name == "acpi-power-button");
3358                    assert_eq!(built, has_button, "{args:?}");
3359                }
3360            }
3361        });
3362    }
3363
3364    #[test]
3365    fn selects_non_volatile_store_backing() {
3366        for file_id in [
3367            vmgs_format::FileId::BIOS_NVRAM,
3368            vmgs_format::FileId::TPM_PPI,
3369            tpm_vmgs::tpm_nvram_file_id(TpmVersion::V138),
3370            tpm_vmgs::tpm_nvram_file_id(TpmVersion::V185),
3371        ] {
3372            assert_eq!(
3373                non_volatile_store_resource(true, file_id).id(),
3374                <VmgsFileHandle as ResourceId<NonVolatileStoreKind>>::ID
3375            );
3376            assert_eq!(
3377                non_volatile_store_resource(false, file_id).id(),
3378                <EphemeralNonVolatileStoreHandle as ResourceId<NonVolatileStoreKind>>::ID
3379            );
3380        }
3381    }
3382
3383    #[test]
3384    fn opens_vmgs_with_provisioning_and_encryption_policy() {
3385        block_on(async {
3386            for provision in [
3387                ProvisionCondition::OnEmpty,
3388                ProvisionCondition::OnFailure,
3389                ProvisionCondition::Single,
3390            ] {
3391                for encryption_policy in [
3392                    GuestStateEncryptionPolicy::None(true),
3393                    GuestStateEncryptionPolicy::GspById(true),
3394                ] {
3395                    let vmgs = open_vmgs(
3396                        &DiskCliKind::Memory(vmgs_format::VMGS_DEFAULT_CAPACITY),
3397                        provision,
3398                        encryption_policy,
3399                    )
3400                    .await
3401                    .unwrap();
3402                    let disk = match (provision, vmgs) {
3403                        (ProvisionCondition::OnEmpty, VmgsResource::Disk(disk))
3404                        | (
3405                            ProvisionCondition::OnFailure,
3406                            VmgsResource::ReprovisionOnFailure(disk),
3407                        )
3408                        | (ProvisionCondition::Single, VmgsResource::ReprovisionSingle(disk)) => {
3409                            disk
3410                        }
3411                        _ => panic!("incorrect VMGS provisioning"),
3412                    };
3413                    assert!(matches!(
3414                        (encryption_policy, disk.encryption_policy),
3415                        (
3416                            GuestStateEncryptionPolicy::None(true),
3417                            GuestStateEncryptionPolicy::None(true)
3418                        ) | (
3419                            GuestStateEncryptionPolicy::GspById(true),
3420                            GuestStateEncryptionPolicy::GspById(true)
3421                        )
3422                    ));
3423                }
3424            }
3425        });
3426    }
3427
3428    /// Declaring controllers alone must not create implicit device attachments.
3429    #[test]
3430    fn usb_cli_empty_controllers() {
3431        let opt = Options::try_parse_from(["openvmm", "--usb-xhci", "usb0", "--usb-xhci", "usb1"])
3432            .unwrap();
3433        let controllers = usb_controller_configs(&opt.usb_xhci, &opt.usb_device).unwrap();
3434        assert_eq!(controllers.len(), 2);
3435        assert!(
3436            controllers
3437                .iter()
3438                .all(|(_, config)| config.devices.is_empty())
3439        );
3440    }
3441
3442    /// A sole controller supplies omitted on values; omitted connectors are left to the resolver.
3443    #[test]
3444    fn usb_cli_infers_single_controller() {
3445        let opt = Options::try_parse_from([
3446            "openvmm",
3447            "--usb-xhci",
3448            "usb0",
3449            "--usb-device",
3450            "mock-hid",
3451            "--usb-device",
3452            "mock-loopback",
3453            "--usb-device",
3454            "mock-storage",
3455            "--usb-device",
3456            "mock-mutt",
3457            "--usb-device",
3458            "mock-supermutt",
3459            "--usb-device",
3460            r"winusb,instance_id=USB\A",
3461            "--usb-device",
3462            "winusb-all",
3463        ])
3464        .unwrap();
3465        let controllers = usb_controller_configs(&opt.usb_xhci, &opt.usb_device).unwrap();
3466        assert_eq!(controllers[0].0, "usb0");
3467        assert_eq!(controllers[0].1.devices.len(), 7);
3468        for config in controllers[0].1.devices.iter().take(6) {
3469            let usb_config_resources::UsbDeviceConfig::Device { connector, .. } = config else {
3470                panic!("expected a device attachment");
3471            };
3472            assert_eq!(*connector, None);
3473        }
3474        assert!(matches!(
3475            controllers[0].1.devices[6],
3476            usb_config_resources::UsbDeviceConfig::Discover(_)
3477        ));
3478    }
3479
3480    /// An omitted on value is ambiguous when more than one controller is declared.
3481    #[test]
3482    fn usb_cli_requires_explicit_controller_when_ambiguous() {
3483        for selection in [
3484            "mock-hid",
3485            "mock-hid,connector=1",
3486            r"winusb,instance_id=USB\A",
3487            "winusb-all",
3488        ] {
3489            let opt = Options::try_parse_from([
3490                "openvmm",
3491                "--usb-xhci",
3492                "usb0",
3493                "--usb-xhci",
3494                "usb1",
3495                "--usb-device",
3496                selection,
3497            ])
3498            .unwrap();
3499            let error = usb_controller_configs(&opt.usb_xhci, &opt.usb_device).unwrap_err();
3500            assert!(error.to_string().contains("on=PCIE_PORT is required"));
3501        }
3502    }
3503
3504    /// Normalization preserves one-based connector numbers and explicit mock overrides.
3505    #[test]
3506    fn usb_cli_preserves_one_based_connectors_and_mock_overrides() {
3507        let opt = Options::try_parse_from([
3508            "openvmm",
3509            "--usb-xhci",
3510            "usb0",
3511            "--usb-xhci",
3512            "usb1",
3513            "--usb-device",
3514            "mock-hid,on=usb0,connector=1,vid=0x1234,pid=65535,serial=HID001",
3515            "--usb-device",
3516            "mock-storage,on=usb1,connector=15,blocks=4096",
3517        ])
3518        .unwrap();
3519        let controllers = usb_controller_configs(&opt.usb_xhci, &opt.usb_device).unwrap();
3520        let usb_config_resources::UsbDeviceConfig::Device { connector, device } =
3521            &controllers[0].1.devices[0]
3522        else {
3523            panic!("expected fixed HID attachment");
3524        };
3525        assert_eq!(*connector, Some(1));
3526        assert_eq!(device.id(), "mock_hid_config");
3527        let usb_config_resources::UsbDeviceConfig::Device { connector, .. } =
3528            &controllers[1].1.devices[0]
3529        else {
3530            panic!("expected fixed storage attachment");
3531        };
3532        assert_eq!(*connector, Some(15));
3533        let cli_args::UsbDeviceCli::Device {
3534            backend: usb::UsbBackend::Hid(handle),
3535            ..
3536        } = &opt.usb_device[0]
3537        else {
3538            panic!("expected HID");
3539        };
3540        assert_eq!(
3541            (handle.identity.vendor_id, handle.identity.product_id),
3542            (Some(0x1234), Some(65535))
3543        );
3544        assert_eq!(handle.identity.serial_number.as_deref(), Some("HID001"));
3545        let cli_args::UsbDeviceCli::Device {
3546            backend: usb::UsbBackend::Storage(handle),
3547            ..
3548        } = &opt.usb_device[1]
3549        else {
3550            panic!("expected storage");
3551        };
3552        assert_eq!(handle.block_count, Some(4096));
3553    }
3554
3555    /// Explicit host IDs are preserved and automatic discovery remains a separate request.
3556    #[test]
3557    fn usb_cli_preserves_winusb_ids_and_automatic_selection() {
3558        let instance_id = r"USB\MS_COMP_WINUSB\A&B C";
3559        let selection = format!("winusb,on=usb0,connector=3,instance_id={instance_id}");
3560        let opt = Options::try_parse_from([
3561            "openvmm",
3562            "--usb-xhci",
3563            "usb0",
3564            "--usb-device",
3565            &selection,
3566            "--usb-device",
3567            "winusb-all,on=usb0",
3568        ])
3569        .unwrap();
3570        let controllers = usb_controller_configs(&opt.usb_xhci, &opt.usb_device).unwrap();
3571        let cli_args::UsbDeviceCli::Device {
3572            backend: usb::UsbBackend::WinUsb(handle),
3573            ..
3574        } = &opt.usb_device[0]
3575        else {
3576            panic!("expected WinUSB");
3577        };
3578        assert_eq!(handle.instance_id, instance_id);
3579        let usb_config_resources::UsbDeviceConfig::Device { connector, device } =
3580            &controllers[0].1.devices[0]
3581        else {
3582            panic!("expected fixed WinUSB attachment");
3583        };
3584        assert_eq!(*connector, Some(3));
3585        assert_eq!(device.id(), "winusb_config");
3586        let usb_config_resources::UsbDeviceConfig::Discover(discovery) =
3587            &controllers[0].1.devices[1]
3588        else {
3589            panic!("expected WinUSB discovery");
3590        };
3591        assert_eq!(discovery.id(), "winusb_all_config");
3592    }
3593
3594    /// Reject malformed backend options and missing, duplicate, or unknown controllers.
3595    #[test]
3596    fn usb_cli_rejects_bad_syntax_and_unknown_controllers() {
3597        for selection in [
3598            "usb0:hid",
3599            "winusb",
3600            "mock-hid,on=usb0,connector=0",
3601            "mock-hid,on=usb0,connector=256",
3602            "mock-hid,on=usb0,connector=1,vid=0x10000",
3603            "mock-hid,on=usb0,connector=1,pid=bad",
3604            "mock-hid,on=usb0,connector=1,unknown=1",
3605            "mock-hid,on=usb0,connector=1,instance_id=USB",
3606            "mock-hid,on=usb0,connector=1,blocks=1",
3607            "mock-supermutt,on=usb0,connector=1,vid=1",
3608            "mock-storage,on=usb0,connector=1,blocks=0",
3609            "winusb,on=usb0,connector=1,instance_id=USB,vid=1",
3610            "winusb-all,on=usb0,connector=1",
3611        ] {
3612            assert!(
3613                Options::try_parse_from([
3614                    "openvmm",
3615                    "--usb-xhci",
3616                    "usb0",
3617                    "--usb-device",
3618                    selection
3619                ])
3620                .is_err()
3621            );
3622        }
3623        assert!(
3624            Options::try_parse_from(["openvmm", "--usb-device", "mock-hid,on=usb0,connector=1"])
3625                .is_err()
3626        );
3627        assert!(Options::try_parse_from(["openvmm", "--usb-xhci", "usb0,unknown=1"]).is_err());
3628        let opt = Options::try_parse_from([
3629            "openvmm",
3630            "--usb-xhci",
3631            "usb0",
3632            "--usb-device",
3633            "mock-hid,on=missing,connector=1",
3634        ])
3635        .unwrap();
3636        assert!(usb_controller_configs(&opt.usb_xhci, &opt.usb_device).is_err());
3637        let opt = Options::try_parse_from(["openvmm", "--usb-xhci", "usb0", "--usb-xhci", "usb0"])
3638            .unwrap();
3639        assert!(usb_controller_configs(&opt.usb_xhci, &opt.usb_device).is_err());
3640    }
3641
3642    /// Backend defaults, capacity limits, and connector conflicts must not be
3643    /// baked into the shared CLI.
3644    #[test]
3645    fn usb_cli_leaves_defaults_and_implementation_limits_to_resolvers() {
3646        let opt = Options::try_parse_from([
3647            "openvmm",
3648            "--usb-xhci",
3649            "usb0",
3650            "--usb-device",
3651            "mock-storage,on=usb0,connector=16,blocks=524289",
3652            "--usb-device",
3653            "mock-storage,on=usb0,connector=1",
3654            "--usb-device",
3655            "mock-hid,on=usb0,connector=1",
3656        ])
3657        .unwrap();
3658        assert!(usb_controller_configs(&opt.usb_xhci, &opt.usb_device).is_ok());
3659        let cli_args::UsbDeviceCli::Device {
3660            backend: usb::UsbBackend::Storage(config),
3661            ..
3662        } = &opt.usb_device[1]
3663        else {
3664            panic!("expected storage");
3665        };
3666        assert_eq!(config.block_count, None);
3667        assert_eq!(config.identity, Default::default());
3668    }
3669
3670    /// Discovery excludes explicit host IDs across controllers regardless of option order.
3671    /// Resource resolution is async even when the test only decodes configuration.
3672    #[pal_async::async_test]
3673    async fn usb_cli_excludes_explicit_winusb_across_controllers() {
3674        use usb_config_resources::UsbDeviceDiscoveryConfigKind;
3675        use usb_config_resources::WinUsbAllConfig;
3676        use vm_resource::CanResolveTo;
3677        use vm_resource::ResolveResource;
3678        use vm_resource::ResourceResolver;
3679
3680        /// Discovery settings decoded for assertions without host enumeration.
3681        struct CapturedDiscoveryConfig {
3682            /// The actual configuration emitted by the CLI.
3683            config: WinUsbAllConfig,
3684        }
3685        /// Reads an opaque discovery resource without constructing USB devices.
3686        struct CaptureDiscoveryConfig;
3687
3688        impl CanResolveTo<CapturedDiscoveryConfig> for UsbDeviceDiscoveryConfigKind {
3689            type Input<'a> = ();
3690        }
3691
3692        impl ResolveResource<UsbDeviceDiscoveryConfigKind, WinUsbAllConfig> for CaptureDiscoveryConfig {
3693            type Output = CapturedDiscoveryConfig;
3694            type Error = std::convert::Infallible;
3695
3696            fn resolve(&self, config: WinUsbAllConfig, _: ()) -> Result<Self::Output, Self::Error> {
3697                Ok(CapturedDiscoveryConfig { config })
3698            }
3699        }
3700
3701        let mut resolver = ResourceResolver::new();
3702        resolver.add_resolver(CaptureDiscoveryConfig);
3703        for selections in [
3704            [
3705                "winusb-all,on=usb0",
3706                r"winusb,on=usb1,instance_id=usb\z",
3707                r"winusb,on=usb1,instance_id=USB\a",
3708            ],
3709            [
3710                r"winusb,on=usb1,instance_id=usb\z",
3711                r"winusb,on=usb1,instance_id=USB\a",
3712                "winusb-all,on=usb0",
3713            ],
3714        ] {
3715            let mut opt =
3716                Options::try_parse_from(["openvmm", "--usb-xhci", "usb0", "--usb-xhci", "usb1"])
3717                    .unwrap();
3718            opt.usb_device = selections
3719                .into_iter()
3720                .map(|selection| selection.parse().unwrap())
3721                .collect();
3722            let mut controllers = usb_controller_configs(&opt.usb_xhci, &opt.usb_device).unwrap();
3723            assert_eq!(controllers[1].1.devices.len(), 2);
3724            let usb_config_resources::UsbDeviceConfig::Discover(discovery) =
3725                controllers[0].1.devices.pop().unwrap()
3726            else {
3727                panic!("expected discovery on usb0");
3728            };
3729            let captured: CapturedDiscoveryConfig = resolver.resolve(discovery, ()).await.unwrap();
3730            assert_eq!(captured.config.excluded_instance_ids, [r"USB\A", r"USB\Z"]);
3731        }
3732    }
3733
3734    /// Reject duplicate host IDs and multiple automatic discovery requests across the VM.
3735    #[test]
3736    fn usb_cli_rejects_overlapping_host_selections() {
3737        for (first, second) in [
3738            (
3739                "winusb,on=usb0,connector=1,instance_id=USB\\A",
3740                "winusb,on=usb1,connector=1,instance_id=usb\\a",
3741            ),
3742            ("winusb-all,on=usb0", "winusb-all,on=usb1"),
3743        ] {
3744            let opt = Options::try_parse_from([
3745                "openvmm",
3746                "--usb-xhci",
3747                "usb0",
3748                "--usb-xhci",
3749                "usb1",
3750                "--usb-device",
3751                first,
3752                "--usb-device",
3753                second,
3754            ])
3755            .unwrap();
3756            assert!(usb_controller_configs(&opt.usb_xhci, &opt.usb_device).is_err());
3757        }
3758    }
3759
3760    #[test]
3761    fn maps_igvm_personalities_to_chipsets() {
3762        for (args, expected) in [
3763            (
3764                vec!["openvmm", "--igvm", "firmware=guest.igvm,personality=uefi"],
3765                BaseChipsetType::HypervGen2Uefi,
3766            ),
3767            (
3768                vec![
3769                    "openvmm",
3770                    "--igvm",
3771                    "firmware=guest.igvm,personality=linux-direct",
3772                ],
3773                BaseChipsetType::UnenlightenedLinuxDirect,
3774            ),
3775            (
3776                vec![
3777                    "openvmm",
3778                    "--igvm",
3779                    "firmware=guest.igvm,personality=linux-direct",
3780                    "--hv",
3781                ],
3782                BaseChipsetType::HyperVGen2LinuxDirect,
3783            ),
3784            (
3785                vec![
3786                    "openvmm",
3787                    "--igvm",
3788                    "firmware=guest.igvm,personality=linux-direct",
3789                    "--isolation",
3790                    "snp",
3791                ],
3792                BaseChipsetType::EnlightenedLinuxDirect,
3793            ),
3794            (
3795                vec![
3796                    "openvmm",
3797                    "--igvm",
3798                    "firmware=guest.igvm,personality=openhcl",
3799                    "--hv",
3800                    "--vtl2",
3801                ],
3802                BaseChipsetType::HclHost,
3803            ),
3804        ] {
3805            let opt = Options::try_parse_from(args).unwrap();
3806            opt.validate_igvm_options().unwrap();
3807            assert!(
3808                std::mem::discriminant(&base_chipset_type(&opt))
3809                    == std::mem::discriminant(&expected)
3810            );
3811        }
3812    }
3813
3814    #[test]
3815    fn builds_openhcl_igvm_config_without_host_uefi() {
3816        DefaultPool::run_with(async |driver| {
3817            let temp_dir = tempfile::tempdir().unwrap();
3818            let igvm_path = temp_dir.path().join("guest.igvm");
3819            File::create(&igvm_path).unwrap();
3820            let igvm_options = format!("firmware={},personality=openhcl", igvm_path.display());
3821            let mesh = VmmMesh::new(&driver, true).unwrap();
3822
3823            for (extra, expected_alias, expected_policy) in [
3824                (vec![], true, Some(LateMapVtl0MemoryPolicy::Halt)),
3825                (
3826                    vec!["--uefi", "console=com1,disable_frontpage"],
3827                    true,
3828                    Some(LateMapVtl0MemoryPolicy::Halt),
3829                ),
3830                (
3831                    vec!["--net", "uh:consomme", "--no-alias-map"],
3832                    false,
3833                    Some(LateMapVtl0MemoryPolicy::Halt),
3834                ),
3835                (
3836                    vec!["--isolation", "vbs", "--no-alias-map"],
3837                    false,
3838                    Some(LateMapVtl0MemoryPolicy::Halt),
3839                ),
3840                (
3841                    vec!["--no-alias-map", "--late-map-vtl0-policy", "exception"],
3842                    false,
3843                    Some(LateMapVtl0MemoryPolicy::InjectException),
3844                ),
3845                (
3846                    vec!["--late-map-vtl0-policy", "log"],
3847                    true,
3848                    Some(LateMapVtl0MemoryPolicy::Log),
3849                ),
3850                (
3851                    vec!["--igvm-vtl2-relocation-type", "vtl2=filesize"],
3852                    true,
3853                    Some(LateMapVtl0MemoryPolicy::Halt),
3854                ),
3855                (
3856                    vec![
3857                        "--igvm-vtl2-relocation-type",
3858                        "vtl2=filesize",
3859                        "--late-map-vtl0-policy",
3860                        "off",
3861                    ],
3862                    true,
3863                    None,
3864                ),
3865            ] {
3866                let mut args = vec![
3867                    "openvmm",
3868                    "--igvm",
3869                    &igvm_options,
3870                    "--hv",
3871                    "--vtl2",
3872                    "--single-process",
3873                ];
3874                args.extend(extra);
3875                let opt = Options::try_parse_from(args).unwrap();
3876                let (config, resources) = vm_config_from_command_line(driver.clone(), &mesh, &opt)
3877                    .await
3878                    .unwrap();
3879
3880                assert!(matches!(config.load_mode, LoadMode::Igvm { .. }));
3881                assert!(config.hypervisor.with_hv);
3882                let vtl2 = config.hypervisor.with_vtl2.as_ref().unwrap();
3883                assert_eq!(vtl2.vtl0_alias_map, expected_alias);
3884                assert_eq!(vtl2.late_map_vtl0_memory, expected_policy);
3885                assert!(config.vmbus.is_some());
3886                assert!(config.vtl2_vmbus.is_some());
3887                assert!(resources.ged_rpc.is_some());
3888                assert!(resources.acpi_power_button.is_none());
3889                for id in ["ged", "gel"] {
3890                    assert!(
3891                        config.vmbus_devices.iter().any(|(vtl, resource)| {
3892                            *vtl == DeviceVtl::Vtl2 && resource.id() == id
3893                        })
3894                    );
3895                }
3896                assert!(
3897                    config
3898                        .chipset_devices
3899                        .iter()
3900                        .all(|device| { device.resource.id() != "hyperv_firmware_uefi" })
3901                );
3902            }
3903            for (extra, expected_error) in [
3904                (
3905                    ["--net", "uh:consomme"],
3906                    "must specify --no-alias-map to offer NICs to VTL2",
3907                ),
3908                (
3909                    ["--isolation", "vbs"],
3910                    "alias map not supported with isolation",
3911                ),
3912            ] {
3913                let mut args = vec![
3914                    "openvmm",
3915                    "--igvm",
3916                    &igvm_options,
3917                    "--hv",
3918                    "--vtl2",
3919                    "--single-process",
3920                ];
3921                args.extend(extra);
3922                let opt = Options::try_parse_from(args).unwrap();
3923                let err = vm_config_from_command_line(driver.clone(), &mesh, &opt)
3924                    .await
3925                    .err()
3926                    .unwrap();
3927                assert_eq!(err.to_string(), expected_error);
3928            }
3929            mesh.shutdown().await;
3930        });
3931    }
3932
3933    #[test]
3934    fn maps_virtio_vsock_to_named_pcie_port() {
3935        DefaultPool::run_with(async |driver| {
3936            let temp_dir = tempfile::tempdir().unwrap();
3937            let kernel_path = temp_dir.path().join("kernel");
3938            File::create(&kernel_path).unwrap();
3939            let initrd_path = temp_dir.path().join("initrd");
3940            File::create(&initrd_path).unwrap();
3941            let socket_path = temp_dir.path().join("vsock");
3942            let cwd = std::env::current_dir().unwrap();
3943            let socket_path = socket_path.strip_prefix(cwd).unwrap_or(&socket_path);
3944            let opt = Options::try_parse_from([
3945                "openvmm",
3946                "--kernel",
3947                kernel_path.to_str().unwrap(),
3948                "--initrd",
3949                initrd_path.to_str().unwrap(),
3950                "--virtio-vsock-path",
3951                socket_path.to_str().unwrap(),
3952                "--virtio-vsock-bus",
3953                "pcie:custom",
3954                "--single-process",
3955            ])
3956            .unwrap();
3957            let mesh = VmmMesh::new(&driver, true).unwrap();
3958
3959            let (config, _resources) = vm_config_from_command_line(driver, &mesh, &opt)
3960                .await
3961                .unwrap();
3962
3963            assert_eq!(config.pcie_devices.len(), 1);
3964            assert_eq!(config.pcie_devices[0].port_name, "custom");
3965            mesh.shutdown().await;
3966        });
3967    }
3968
3969    #[test]
3970    fn maps_virtio_fs_and_rng_to_named_pcie_ports() {
3971        DefaultPool::run_with(async |driver| {
3972            let temp_dir = tempfile::tempdir().unwrap();
3973            let kernel_path = temp_dir.path().join("kernel");
3974            File::create(&kernel_path).unwrap();
3975            let initrd_path = temp_dir.path().join("initrd");
3976            File::create(&initrd_path).unwrap();
3977            let root_path = temp_dir.path().to_str().unwrap();
3978            let opt = Options::try_parse_from([
3979                "openvmm",
3980                "--kernel",
3981                kernel_path.to_str().unwrap(),
3982                "--initrd",
3983                initrd_path.to_str().unwrap(),
3984                "--virtio-fs",
3985                &format!("fs,{root_path}"),
3986                "--virtio-fs-bus",
3987                "pcie:fs",
3988                "--virtio-rng",
3989                "--virtio-rng-bus",
3990                "pcie:rng",
3991                "--single-process",
3992            ])
3993            .unwrap();
3994            let mesh = VmmMesh::new(&driver, true).unwrap();
3995
3996            let (config, _resources) = vm_config_from_command_line(driver, &mesh, &opt)
3997                .await
3998                .unwrap();
3999
4000            let port_names: Vec<_> = config
4001                .pcie_devices
4002                .iter()
4003                .map(|device| device.port_name.as_str())
4004                .collect();
4005            assert_eq!(port_names, ["fs", "rng"]);
4006            mesh.shutdown().await;
4007        });
4008    }
4009
4010    #[test]
4011    fn rejects_duplicate_pcie_port_assignments() {
4012        DefaultPool::run_with(async |driver| {
4013            let temp_dir = tempfile::tempdir().unwrap();
4014            let kernel_path = temp_dir.path().join("kernel");
4015            File::create(&kernel_path).unwrap();
4016            let initrd_path = temp_dir.path().join("initrd");
4017            File::create(&initrd_path).unwrap();
4018            let root_path = temp_dir.path().to_str().unwrap();
4019            let opt = Options::try_parse_from([
4020                "openvmm",
4021                "--kernel",
4022                kernel_path.to_str().unwrap(),
4023                "--initrd",
4024                initrd_path.to_str().unwrap(),
4025                "--virtio-fs",
4026                &format!("pcie_port=custom:fs,{root_path}"),
4027                "--virtio-rng",
4028                "--virtio-rng-bus",
4029                "pcie:custom",
4030                "--single-process",
4031            ])
4032            .unwrap();
4033            let mesh = VmmMesh::new(&driver, true).unwrap();
4034
4035            let error = vm_config_from_command_line(driver, &mesh, &opt)
4036                .await
4037                .err()
4038                .unwrap();
4039
4040            assert_eq!(error.to_string(), "multiple devices use PCIe port 'custom'");
4041            mesh.shutdown().await;
4042        });
4043    }
4044
4045    #[test]
4046    fn rejects_duplicate_pcie_port_assignment_from_storage() {
4047        DefaultPool::run_with(async |driver| {
4048            let temp_dir = tempfile::tempdir().unwrap();
4049            let kernel_path = temp_dir.path().join("kernel");
4050            File::create(&kernel_path).unwrap();
4051            let initrd_path = temp_dir.path().join("initrd");
4052            File::create(&initrd_path).unwrap();
4053            let opt = Options::try_parse_from([
4054                "openvmm",
4055                "--kernel",
4056                kernel_path.to_str().unwrap(),
4057                "--initrd",
4058                initrd_path.to_str().unwrap(),
4059                "--nvme-pci",
4060                "id=nvme0,pcie_port=custom",
4061                "--virtio-rng",
4062                "--virtio-rng-bus",
4063                "pcie:custom",
4064                "--single-process",
4065            ])
4066            .unwrap();
4067            let mesh = VmmMesh::new(&driver, true).unwrap();
4068
4069            let error = vm_config_from_command_line(driver, &mesh, &opt)
4070                .await
4071                .err()
4072                .unwrap();
4073
4074            assert_eq!(error.to_string(), "multiple devices use PCIe port 'custom'");
4075            mesh.shutdown().await;
4076        });
4077    }
4078
4079    /// The MANA devices keep their VPCI instance IDs from one start to the
4080    /// next, and VTL2's ID is the one its settings name.
4081    #[test]
4082    fn mana_vpci_instance_ids_are_stable() {
4083        DefaultPool::run_with(async |driver| {
4084            let temp_dir = tempfile::tempdir().unwrap();
4085            let igvm_path = temp_dir.path().join("guest.igvm");
4086            File::create(&igvm_path).unwrap();
4087            let igvm_options = format!("firmware={},personality=openhcl", igvm_path.display());
4088            let mesh = VmmMesh::new(&driver, true).unwrap();
4089            let opt = Options::try_parse_from([
4090                "openvmm",
4091                "--igvm",
4092                &igvm_options,
4093                "--hv",
4094                "--vtl2",
4095                "--no-alias-map",
4096                "--single-process",
4097                "--mana",
4098                "consomme",
4099                "--net",
4100                "uh:consomme",
4101            ])
4102            .unwrap();
4103
4104            let mut starts = Vec::new();
4105            for _ in 0..2 {
4106                let (config, resources) = vm_config_from_command_line(driver.clone(), &mesh, &opt)
4107                    .await
4108                    .unwrap();
4109                let id = |vtl| {
4110                    let ids: Vec<_> = config
4111                        .vpci_devices
4112                        .iter()
4113                        .filter(|device| device.vtl == vtl && device.resource.id() == "gdma")
4114                        .map(|device| device.instance_id)
4115                        .collect();
4116                    assert_eq!(ids.len(), 1, "{vtl:?}");
4117                    ids[0]
4118                };
4119                let (vtl0, vtl2) = (id(DeviceVtl::Vtl0), id(DeviceVtl::Vtl2));
4120                assert_ne!(vtl0, vtl2);
4121                let nics = resources
4122                    .vtl2_settings
4123                    .unwrap()
4124                    .dynamic
4125                    .unwrap()
4126                    .nic_devices;
4127                assert_eq!(nics.len(), 1);
4128                assert_eq!(nics[0].instance_id, vtl2.to_string());
4129                starts.push((vtl0, vtl2));
4130            }
4131            assert_eq!(starts[0], starts[1]);
4132            mesh.shutdown().await;
4133        });
4134    }
4135}