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