Skip to main content

openvmm_entry/
lib.rs

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