Skip to main content

openvmm_entry/
lib.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! This module implements the interactive control process and the entry point
5//! for the worker process.
6
7#![expect(missing_docs)]
8#![forbid(unsafe_code)]
9
10mod cli_args;
11mod crash_dump;
12mod kvp;
13mod meshworker;
14mod pidfile;
15mod repl;
16mod serial_io;
17mod storage_builder;
18mod tracing_init;
19mod ttrpc;
20mod usb;
21mod vm_controller;
22
23// `pub` so that the missing_docs warning fires for options without
24// documentation.
25pub use cli_args::Options;
26use console_relay::ConsoleLaunchOptions;
27
28use crate::cli_args::SecureBootTemplateCli;
29use anyhow::Context;
30use anyhow::bail;
31use chipset_resources::acpi_power_button::PowerButtonRpc;
32use chipset_resources::battery::HostBatteryUpdate;
33use cli_args::DiskCliKind;
34use cli_args::EfiDiagnosticsLogLevelCli;
35use cli_args::EndpointConfigCli;
36use cli_args::IgvmPersonalityCli;
37use cli_args::NicConfigCli;
38use cli_args::ProvisionCondition;
39use cli_args::SerialConfigCli;
40use cli_args::TpmVersionCli;
41use cli_args::UefiConsoleModeCli;
42use cli_args::VirtioBusCli;
43use crash_dump::spawn_dump_handler;
44use cxl::test::CxlTestDeviceHandle;
45use disk_backend_resources::DelayDiskHandle;
46use disk_backend_resources::DiskLayerDescription;
47use disk_backend_resources::layer::DiskLayerHandle;
48use disk_backend_resources::layer::RamDiskLayerHandle;
49use disk_backend_resources::layer::SqliteAutoCacheDiskLayerHandle;
50use disk_backend_resources::layer::SqliteDiskLayerHandle;
51use floppy_resources::FloppyDiskConfig;
52use framebuffer::FRAMEBUFFER_SIZE;
53use framebuffer::FramebufferAccess;
54use futures::AsyncReadExt;
55use futures::AsyncWrite;
56use futures::StreamExt;
57use futures::executor::block_on;
58use futures::io::AllowStdIo;
59use gdma_resources::GdmaDeviceHandle;
60use gdma_resources::VportDefinition;
61use guid::Guid;
62use input_core::MultiplexedInputHandle;
63use inspect::InspectMut;
64use mesh::CancelContext;
65use mesh::CellUpdater;
66use mesh::rpc::RpcSend;
67use meshworker::VmmMesh;
68use net_backend_resources::mac_address::MacAddress;
69use nvme_resources::NvmeControllerRequest;
70use openvmm_defs::config::Config;
71use openvmm_defs::config::DEFAULT_ACPI_POWER_BUTTON_IRQ_X64;
72use openvmm_defs::config::DEFAULT_ACPI_POWER_BUTTON_SPI_AARCH64;
73use openvmm_defs::config::DEFAULT_PCAT_BOOT_ORDER;
74use openvmm_defs::config::DeviceVtl;
75use openvmm_defs::config::HypervisorConfig;
76use openvmm_defs::config::IgvmPersonality;
77use openvmm_defs::config::LateMapVtl0MemoryPolicy;
78use openvmm_defs::config::LoadMode;
79use openvmm_defs::config::MemoryConfig;
80use openvmm_defs::config::NumaDistance;
81use openvmm_defs::config::NumaNode;
82use openvmm_defs::config::NumaTopology;
83use openvmm_defs::config::PcieDeviceConfig;
84use openvmm_defs::config::PcieMmioRangeConfig;
85use openvmm_defs::config::PciePortConfig;
86use openvmm_defs::config::PcieRootComplexConfig;
87use openvmm_defs::config::PcieSwitchConfig;
88use openvmm_defs::config::ProcessorTopologyConfig;
89use openvmm_defs::config::RootComplexCxlConfig;
90use openvmm_defs::config::UartId;
91use openvmm_defs::config::VirtioBus;
92use openvmm_defs::config::VmbusConfig;
93use openvmm_defs::config::VpAssignment;
94use openvmm_defs::config::VpciDeviceConfig;
95use openvmm_defs::config::Vtl2BaseAddressType;
96use openvmm_defs::config::Vtl2Config;
97use openvmm_defs::rpc::VmRpc;
98use openvmm_defs::worker::VM_WORKER;
99use openvmm_defs::worker::VmWorkerParameters;
100use openvmm_helpers::config::supports_acpi_power_button;
101use openvmm_helpers::disk::OpenDiskOptions;
102use openvmm_helpers::disk::create_disk_type;
103use openvmm_helpers::disk::open_disk_type;
104use pal_async::DefaultDriver;
105use pal_async::DefaultPool;
106use pal_async::socket::PolledSocket;
107use pal_async::task::Spawn;
108use pal_async::task::Task;
109use serial_16550_resources::ComPort;
110use serial_core::resources::DisconnectedSerialBackendHandle;
111use serial_core::resources::NullSerialBackendHandle;
112use sparse_mmap::alloc_shared_memory;
113use std::cell::RefCell;
114use std::collections::BTreeMap;
115use std::collections::HashSet;
116use std::fmt::Write as _;
117use std::io;
118#[cfg(unix)]
119use std::io::IsTerminal;
120use std::io::Write;
121use std::net::TcpListener;
122use std::path::Path;
123use std::path::PathBuf;
124use std::sync::Arc;
125use std::thread;
126use std::time::Duration;
127use storvsp_resources::ScsiControllerRequest;
128use tpm_resources::TpmDeviceHandle;
129use tpm_resources::TpmRegisterLayout;
130use tpm_resources::TpmVersion;
131use uidevices_resources::SynthKeyboardHandle;
132use uidevices_resources::SynthMouseHandle;
133use uidevices_resources::SynthVideoHandle;
134use video_core::SharedFramebufferHandle;
135use virtio_resources::VirtioPciDeviceHandle;
136use vm_manifest_builder::BaseChipsetType;
137use vm_manifest_builder::MachineArch;
138use vm_manifest_builder::VmChipsetResult;
139use vm_manifest_builder::VmManifestBuilder;
140use vm_resource::IntoResource;
141use vm_resource::Resource;
142use vm_resource::kind::DiskHandleKind;
143use vm_resource::kind::DiskLayerHandleKind;
144use vm_resource::kind::NetEndpointHandleKind;
145use vm_resource::kind::NonVolatileStoreKind;
146use vm_resource::kind::VirtioDeviceHandle;
147use vm_resource::kind::VmbusDeviceHandleKind;
148use vmbus_serial_resources::VmbusSerialDeviceHandle;
149use vmbus_serial_resources::VmbusSerialPort;
150use vmcore::non_volatile_store::resources::EphemeralNonVolatileStoreHandle;
151use vmgs_resources::GuestStateEncryptionPolicy;
152use vmgs_resources::VmgsDisk;
153use vmgs_resources::VmgsFileHandle;
154use vmgs_resources::VmgsResource;
155use vmotherboard::ChipsetDeviceHandle;
156use vnc_worker_defs::VncParameters;
157
158pub fn openvmm_main() {
159    // Save the current state of the terminal so we can restore it back to
160    // normal before exiting.
161    #[cfg(unix)]
162    let orig_termios = io::stderr().is_terminal().then(term::get_termios);
163
164    let mut pidfile_guard: Option<pidfile::Pidfile> = None;
165    let exit_code = match do_main(&mut pidfile_guard) {
166        Ok(code) => code,
167        Err(err) => {
168            eprintln!("fatal error: {:?}", err);
169            1
170        }
171    };
172
173    // Restore the terminal to its initial state.
174    #[cfg(unix)]
175    if let Some(orig_termios) = orig_termios {
176        term::set_termios(orig_termios);
177    }
178
179    // Clean up the pidfile before terminating, since
180    // pal::process::terminate skips destructors.
181    drop(pidfile_guard);
182
183    // Terminate the process immediately without graceful shutdown of DLLs or
184    // C++ destructors or anything like that. This is all unnecessary and saves
185    // time on Windows.
186    //
187    // Do flush stdout, though, since there may be buffered data.
188    let _ = io::stdout().flush();
189    pal::process::terminate(exit_code);
190}
191
192#[derive(Default)]
193struct VmResources {
194    console_in: Option<Box<dyn AsyncWrite + Send + Unpin>>,
195    /// Keeps the dedicated serial reactor alive while serial I/O objects exist.
196    serial_driver: Option<DefaultDriver>,
197    framebuffer_access: Option<FramebufferAccess>,
198    shutdown_ic: Option<mesh::Sender<hyperv_ic_resources::shutdown::ShutdownRpc>>,
199    acpi_power_button: Option<mesh::Sender<PowerButtonRpc>>,
200    kvp_ic: Option<mesh::Sender<hyperv_ic_resources::kvp::KvpConnectRpc>>,
201    scsi_rpc: Option<mesh::Sender<ScsiControllerRequest>>,
202    nvme_vtl2_rpc: Option<mesh::Sender<NvmeControllerRequest>>,
203    consomme_rpc: Option<mesh::Sender<net_backend_resources::consomme::ConsommeRequest>>,
204    ged_rpc: Option<mesh::Sender<get_resources::ged::GuestEmulationRequest>>,
205    vtl2_settings: Option<vtl2_settings_proto::Vtl2Settings>,
206    /// Receives dirty rectangles from the synthetic video device for the VNC worker.
207    dirty_rect_recv: Option<mesh::Receiver<Vec<video_core::DirtyRect>>>,
208    #[cfg(windows)]
209    switch_ports: Vec<vmswitch::kernel::SwitchPort>,
210}
211
212struct ConsoleState<'a> {
213    device: &'a str,
214    input: Box<dyn AsyncWrite + Unpin + Send>,
215}
216
217/// Builds controller configurations from the USB command-line options. The
218/// controller resolver assigns omitted connectors and validates connectors.
219fn usb_controller_configs(
220    pcie_ports: &[cli_args::UsbXhciCli],
221    devices: &[cli_args::UsbDeviceCli],
222) -> anyhow::Result<Vec<(String, usb_config_resources::UsbControllerConfig)>> {
223    let mut controllers: Vec<_> = pcie_ports
224        .iter()
225        .map(|pcie_port| usb::UsbControllerSpec {
226            port_name: pcie_port.port_name.clone(),
227            devices: Vec::new(),
228            winusb_all: false,
229        })
230        .collect();
231    let default_pcie_port = if let [pcie_port] = pcie_ports {
232        Some(pcie_port.port_name.as_str())
233    } else {
234        None
235    };
236    for device in devices {
237        let pcie_port_name = device
238            .controller_pcie_port()
239            .or(default_pcie_port)
240            .context("on=PCIE_PORT is required unless exactly one xHCI controller is declared")?;
241        let controller = controllers
242            .iter_mut()
243            .find(|controller| controller.port_name == pcie_port_name)
244            .with_context(|| {
245                format!(
246                    "USB device references undeclared controller on PCIe port {pcie_port_name:?}"
247                )
248            })?;
249        match device {
250            cli_args::UsbDeviceCli::Device { location, backend } => controller.devices.push((
251                location.connector.map(cli_args::UsbConnectorCli::number),
252                backend.clone(),
253            )),
254            cli_args::UsbDeviceCli::WinUsbAll { .. } => {
255                anyhow::ensure!(
256                    !controller.winusb_all,
257                    "winusb-all may be selected only once per VM"
258                );
259                controller.winusb_all = true;
260            }
261        }
262    }
263    usb::controller_configs(controllers)
264}
265
266/// Build a flat list of switches with their parent port assignments.
267///
268/// This function converts hierarchical CLI switch definitions into a flat list
269/// where each switch specifies its parent port directly.
270fn build_switch_list(all_switches: &[cli_args::GenericPcieSwitchCli]) -> Vec<PcieSwitchConfig> {
271    all_switches
272        .iter()
273        .map(|switch_cli| PcieSwitchConfig {
274            name: switch_cli.name.clone(),
275            parent_port: switch_cli.port_name.clone(),
276            ports: (0..switch_cli.num_downstream_ports)
277                .map(|i| PciePortConfig {
278                    name: format!("{}-downstream-{}", switch_cli.name, i),
279                    devfn: None,
280                    hotplug: switch_cli.hotplug,
281                    acs_capabilities_supported: switch_cli.acs_capabilities_supported,
282                    cxl: false,
283                    pasid: switch_cli.pasid,
284                })
285                .collect(),
286        })
287        .collect()
288}
289
290fn base_chipset_type(opt: &Options) -> BaseChipsetType {
291    if let Some(igvm) = &opt.igvm {
292        match igvm.personality {
293            IgvmPersonalityCli::Openhcl => BaseChipsetType::HclHost,
294            IgvmPersonalityCli::Uefi => BaseChipsetType::HypervGen2Uefi,
295            IgvmPersonalityCli::LinuxDirect if opt.isolation.is_some() => {
296                BaseChipsetType::EnlightenedLinuxDirect
297            }
298            IgvmPersonalityCli::LinuxDirect if opt.hv => BaseChipsetType::HyperVGen2LinuxDirect,
299            IgvmPersonalityCli::LinuxDirect => BaseChipsetType::UnenlightenedLinuxDirect,
300        }
301    } else if matches!(opt.isolation, Some(cli_args::IsolationCli::Snp)) {
302        BaseChipsetType::EnlightenedLinuxDirect
303    } else if opt.pcat {
304        BaseChipsetType::HypervGen1
305    } else if opt.uefi.is_some() {
306        BaseChipsetType::HypervGen2Uefi
307    } else if opt.hv {
308        BaseChipsetType::HyperVGen2LinuxDirect
309    } else {
310        BaseChipsetType::UnenlightenedLinuxDirect
311    }
312}
313
314/// Build the loader's [`SmbiosConfig`](openvmm_defs::config::SmbiosConfig) from
315/// the parsed `--smbios` arguments.
316///
317/// Multiple `--smbios` arguments are merged (erroring on a field set twice).
318/// String overrides left unset fall through to the loader's default identity.
319/// The system UUID defaults to the all-zero GUID unless overridden with
320/// `uuid=GUID`; `uuid=random` requests a freshly generated per-VM GUID.
321fn smbios_config_from_cli(
322    args: &[cli_args::SmbiosCli],
323) -> anyhow::Result<openvmm_defs::config::SmbiosConfig> {
324    let mut merged = cli_args::SmbiosCli::default();
325    for arg in args {
326        merged.merge(arg.clone())?;
327    }
328    let cli_args::SmbiosCli {
329        bios:
330            cli_args::SmbiosBiosCli {
331                vendor: bios_vendor,
332                version: bios_version,
333                release_date: bios_release_date,
334                release: bios_release,
335            },
336        system:
337            cli_args::SmbiosSystemCli {
338                manufacturer: system_manufacturer,
339                product_name: system_product,
340                version: system_version,
341                serial_number: system_serial,
342                sku_number: system_sku,
343                family: system_family,
344                uuid: system_uuid,
345            },
346    } = merged;
347    Ok(openvmm_defs::config::SmbiosConfig {
348        bios: openvmm_defs::config::SmbiosBiosOverrides {
349            vendor: bios_vendor,
350            version: bios_version,
351            release_date: bios_release_date,
352            release: bios_release.map(|r| (r.0, r.1)),
353        },
354        system: openvmm_defs::config::SmbiosSystemOverrides {
355            manufacturer: system_manufacturer,
356            product_name: system_product,
357            version: system_version,
358            serial_number: system_serial,
359            sku_number: system_sku,
360            family: system_family,
361            uuid: match system_uuid {
362                None => Guid::ZERO,
363                Some(cli_args::SmbiosUuid::Random) => Guid::new_random(),
364                Some(cli_args::SmbiosUuid::Fixed(guid)) => guid,
365            },
366        },
367    })
368}
369
370async fn vm_config_from_command_line(
371    spawner: impl Spawn,
372    mesh: &VmmMesh,
373    opt: &Options,
374) -> anyhow::Result<(Config, VmResources)> {
375    opt.validate_isolation_options()?;
376    opt.validate_igvm_options()?;
377
378    let (_, serial_driver) = DefaultPool::spawn_on_thread("serial");
379    let uefi = opt.effective_uefi()?;
380    let default_uefi = cli_args::UefiCli::default();
381    let uefi_options = uefi.as_ref().unwrap_or(&default_uefi);
382
383    let openhcl_vtl = if opt.vtl2 {
384        DeviceVtl::Vtl2
385    } else {
386        DeviceVtl::Vtl0
387    };
388
389    let console_state: RefCell<Option<ConsoleState<'_>>> = RefCell::new(None);
390    let setup_serial = |name: &str, cli_cfg, device| -> anyhow::Result<_> {
391        Ok(match cli_cfg {
392            SerialConfigCli::Console => {
393                if let Some(console_state) = console_state.borrow().as_ref() {
394                    bail!("console already set by {}", console_state.device);
395                }
396                let (config, serial) = serial_io::anonymous_serial_pair(&serial_driver)?;
397                let (serial_read, serial_write) = AsyncReadExt::split(serial);
398                *console_state.borrow_mut() = Some(ConsoleState {
399                    device,
400                    input: Box::new(serial_write),
401                });
402                thread::Builder::new()
403                    .name(name.to_owned())
404                    .spawn(move || {
405                        let _ = block_on(futures::io::copy(
406                            serial_read,
407                            &mut AllowStdIo::new(term::raw_stdout()),
408                        ));
409                    })
410                    .unwrap();
411                Some(config)
412            }
413            SerialConfigCli::Stderr => {
414                let (config, serial) = serial_io::anonymous_serial_pair(&serial_driver)?;
415                thread::Builder::new()
416                    .name(name.to_owned())
417                    .spawn(move || {
418                        let _ = block_on(futures::io::copy(
419                            serial,
420                            &mut AllowStdIo::new(term::raw_stderr()),
421                        ));
422                    })
423                    .unwrap();
424                Some(config)
425            }
426            SerialConfigCli::File(path) => Some(serial_io::file_serial(&path, false)?),
427            SerialConfigCli::None => None,
428            SerialConfigCli::Null => Some(NullSerialBackendHandle.into_resource()),
429            SerialConfigCli::Pipe(path) => {
430                Some(serial_io::bind_serial(&path).context("failed to bind serial")?)
431            }
432            SerialConfigCli::Tcp(addr) => {
433                Some(serial_io::bind_tcp_serial(&addr).context("failed to bind serial")?)
434            }
435            SerialConfigCli::NewConsole(app, window_title) => {
436                let path = console_relay::random_console_path();
437                let config =
438                    serial_io::bind_serial(&path).context("failed to bind console serial")?;
439                let window_title =
440                    window_title.unwrap_or_else(|| name.to_uppercase() + " [OpenVMM]");
441
442                console_relay::launch_console(
443                    app.or_else(openvmm_terminal_app).as_deref(),
444                    &path,
445                    ConsoleLaunchOptions {
446                        window_title: Some(window_title),
447                    },
448                )
449                .context("failed to launch console")?;
450
451                Some(config)
452            }
453        })
454    };
455
456    let mut vmbus_devices = Vec::new();
457
458    let com_debugger_mode = [
459        opt.com1.as_ref().is_some_and(|c| c.debugger_mode),
460        opt.com2.as_ref().is_some_and(|c| c.debugger_mode),
461        opt.com3.as_ref().is_some_and(|c| c.debugger_mode),
462        opt.com4.as_ref().is_some_and(|c| c.debugger_mode),
463    ];
464
465    let [serial0_name, serial1_name, serial2_name, serial3_name] = cfg_select! {
466        guest_arch = "x86_64" => ["ttyS0", "ttyS1", "ttyS2", "ttyS3"],
467        guest_arch = "aarch64" => ["ttyAMA0", "ttyAMA1", "ttyAMA2", "ttyAMA3"],
468    };
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            path: pmem_args.path.clone(),
2038            read_only: false,
2039        }
2040        .into_resource();
2041        if let Some(pcie_port) = &pmem_args.pcie_port {
2042            pcie_devices.push(PcieDeviceConfig {
2043                port_name: pcie_port.clone(),
2044                resource: VirtioPciDeviceHandle(resource).into_resource(),
2045            });
2046        } else {
2047            add_virtio_device(VirtioBusCli::Auto, resource, &mut pcie_devices);
2048        }
2049    }
2050
2051    if opt.virtio_rng {
2052        let resource: Resource<VirtioDeviceHandle> =
2053            virtio_resources::rng::VirtioRngHandle.into_resource();
2054        if let Some(pcie_port) = &opt.virtio_rng_pcie_port {
2055            pcie_devices.push(PcieDeviceConfig {
2056                port_name: pcie_port.clone(),
2057                resource: VirtioPciDeviceHandle(resource).into_resource(),
2058            });
2059        } else {
2060            add_virtio_device(opt.virtio_rng_bus.clone(), resource, &mut pcie_devices);
2061        }
2062    }
2063
2064    if let Some(rtc) = &opt.virtio_rtc {
2065        let resource: Resource<VirtioDeviceHandle> =
2066            virtio_resources::rtc::VirtioRtcHandle.into_resource();
2067        add_virtio_device(rtc.bus.clone(), resource, &mut pcie_devices);
2068    }
2069
2070    if let Some(backend) = virtio_console_backend {
2071        let resource: Resource<VirtioDeviceHandle> =
2072            virtio_resources::console::VirtioConsoleHandle { backend }.into_resource();
2073        if let Some(pcie_port) = &opt.virtio_console_pcie_port {
2074            pcie_devices.push(PcieDeviceConfig {
2075                port_name: pcie_port.clone(),
2076                resource: VirtioPciDeviceHandle(resource).into_resource(),
2077            });
2078        } else {
2079            add_virtio_device(VirtioBusCli::Auto, resource, &mut pcie_devices);
2080        }
2081    }
2082
2083    // Handle --vhost-user arguments.
2084    #[cfg(target_os = "linux")]
2085    for vhost_cli in &opt.vhost_user {
2086        let stream =
2087            unix_socket::UnixStream::connect(&vhost_cli.socket_path).with_context(|| {
2088                format!(
2089                    "failed to connect to vhost-user socket: {}",
2090                    vhost_cli.socket_path
2091                )
2092            })?;
2093
2094        use crate::cli_args::VhostUserDeviceTypeCli;
2095        let resource: Resource<VirtioDeviceHandle> = match vhost_cli.device_type {
2096            VhostUserDeviceTypeCli::Fs {
2097                ref tag,
2098                num_queues,
2099                queue_size,
2100            } => virtio_resources::vhost_user::VhostUserFsHandle {
2101                socket: stream.into(),
2102                tag: tag.clone(),
2103                num_queues,
2104                queue_size,
2105            }
2106            .into_resource(),
2107            VhostUserDeviceTypeCli::Blk {
2108                num_queues,
2109                queue_size,
2110            } => virtio_resources::vhost_user::VhostUserBlkHandle {
2111                socket: stream.into(),
2112                num_queues,
2113                queue_size,
2114            }
2115            .into_resource(),
2116            VhostUserDeviceTypeCli::Other {
2117                device_id,
2118                ref queue_sizes,
2119            } => virtio_resources::vhost_user::VhostUserGenericHandle {
2120                socket: stream.into(),
2121                device_id,
2122                queue_sizes: queue_sizes.clone(),
2123            }
2124            .into_resource(),
2125        };
2126        if let Some(pcie_port) = &vhost_cli.pcie_port {
2127            pcie_devices.push(PcieDeviceConfig {
2128                port_name: pcie_port.clone(),
2129                resource: VirtioPciDeviceHandle(resource).into_resource(),
2130            });
2131        } else {
2132            add_virtio_device(VirtioBusCli::Auto, resource, &mut pcie_devices);
2133        }
2134    }
2135
2136    let virtio_vsock_bus = opt.virtio_vsock_bus.clone().unwrap_or(VirtioBusCli::Auto);
2137
2138    if let Some(vsock_path) = &opt.virtio_vsock_path {
2139        let listener = vsock_listener(Some(vsock_path))?.unwrap();
2140        let resource: Resource<VirtioDeviceHandle> = virtio_resources::vsock::VirtioVsockHandle {
2141            // The guest CID does not matter since the UDS relay does not use it. It just needs
2142            // to be some non-reserved value for the guest to use.
2143            guest_cid: 0x3,
2144            base_path: vsock_path.clone(),
2145            listener,
2146        }
2147        .into_resource();
2148        add_virtio_device(virtio_vsock_bus.clone(), resource, &mut pcie_devices);
2149    }
2150
2151    #[cfg(target_os = "linux")]
2152    if let Some(guest_cid) = opt.virtio_vsock_vhost_cid {
2153        let vhost = std::fs::OpenOptions::new()
2154            .read(true)
2155            .write(true)
2156            .open("/dev/vhost-vsock")
2157            .context("failed to open /dev/vhost-vsock")?
2158            .into();
2159        let resource =
2160            virtio_resources::vsock::VirtioVsockVhostHandle { vhost, guest_cid }.into_resource();
2161        add_virtio_device(virtio_vsock_bus, resource, &mut pcie_devices);
2162    }
2163
2164    #[cfg(target_os = "linux")]
2165    pcie_devices.extend(vfio_pcie_devices);
2166
2167    let mut cfg = Config {
2168        chipset,
2169        load_mode,
2170        floppy_disks,
2171        pcie_root_complexes,
2172        pcie_ecam_below_4gb: opt.pcie_ecam_below_4gb,
2173        #[cfg(target_os = "linux")]
2174        pcie_devices,
2175        #[cfg(not(target_os = "linux"))]
2176        pcie_devices,
2177        pcie_switches,
2178        pcie_generic_initiators,
2179        vpci_devices,
2180        ide_disks: Vec::new(),
2181        numa: {
2182            if let Some(ref nodes) = opt.numa {
2183                // --numa mode: each --numa flag defines a node.
2184                NumaTopology {
2185                    nodes: nodes
2186                        .iter()
2187                        .map(|n| {
2188                            let vps = match &n.vps {
2189                                Some(vps) if vps.0.is_empty() => VpAssignment::Empty,
2190                                Some(vps) => {
2191                                    VpAssignment::Explicit(vps.expand_below(opt.processors)?)
2192                                }
2193                                None => VpAssignment::FromTopology,
2194                            };
2195                            Ok(NumaNode {
2196                                mem: Some(MemoryConfig {
2197                                    mem_size: n
2198                                        .memory
2199                                        .size
2200                                        .expect("NUMA memory size was validated")
2201                                        .0,
2202                                    prefetch_memory: n.memory.prefetch,
2203                                    private_memory: n.memory.shared == Some(false),
2204                                    transparent_hugepages: n
2205                                        .memory
2206                                        .transparent_hugepages
2207                                        .unwrap_or(!n.memory.hugepages),
2208                                    hugepages: n.memory.hugepages,
2209                                    hugepage_size: n.memory.hugepage_size.map(|m| m.0),
2210                                    host_numa_node: n.host_numa_node,
2211                                }),
2212                                vps,
2213                            })
2214                        })
2215                        .collect::<anyhow::Result<Vec<_>>>()?,
2216                    distances: opt
2217                        .numa_distance
2218                        .as_deref()
2219                        .unwrap_or(&[])
2220                        .iter()
2221                        .map(|d| NumaDistance {
2222                            src: d.src,
2223                            dst: d.dst,
2224                            distance: d.distance,
2225                        })
2226                        .collect(),
2227                }
2228            } else {
2229                // Single-node default from --memory.
2230                NumaTopology {
2231                    nodes: vec![NumaNode {
2232                        mem: Some(MemoryConfig {
2233                            mem_size: opt.memory_size(),
2234                            prefetch_memory: opt.prefetch_memory(),
2235                            private_memory: opt.private_memory(),
2236                            transparent_hugepages: opt.transparent_hugepages(),
2237                            hugepages: opt.memory.hugepages,
2238                            hugepage_size: opt.memory.hugepage_size.map(|m| m.0),
2239                            host_numa_node: None,
2240                        }),
2241                        vps: VpAssignment::FromTopology,
2242                    }],
2243                    distances: vec![],
2244                }
2245            }
2246        },
2247        processor_topology: ProcessorTopologyConfig {
2248            proc_count: opt.processors,
2249            vps_per_socket: opt.vps_per_socket,
2250            enable_smt: match opt.smt {
2251                cli_args::SmtConfigCli::Auto => None,
2252                cli_args::SmtConfigCli::Force => Some(true),
2253                cli_args::SmtConfigCli::Off => Some(false),
2254            },
2255            arch: Some(topology_arch),
2256        },
2257        hypervisor: HypervisorConfig {
2258            with_hv,
2259            with_vtl2: opt.vtl2.then_some(Vtl2Config {
2260                vtl0_alias_map: !opt.no_alias_map,
2261                late_map_vtl0_memory: match opt.late_map_vtl0_policy {
2262                    cli_args::Vtl0LateMapPolicyCli::Off => None,
2263                    cli_args::Vtl0LateMapPolicyCli::Log => Some(LateMapVtl0MemoryPolicy::Log),
2264                    cli_args::Vtl0LateMapPolicyCli::Halt => Some(LateMapVtl0MemoryPolicy::Halt),
2265                    cli_args::Vtl0LateMapPolicyCli::Exception => {
2266                        Some(LateMapVtl0MemoryPolicy::InjectException)
2267                    }
2268                },
2269            }),
2270            with_isolation,
2271            nested_virt: opt.nested_virt,
2272        },
2273        #[cfg(windows)]
2274        kernel_vmnics,
2275        input: mesh::Receiver::new(),
2276        framebuffer,
2277        vga_firmware,
2278        vtl2_gfx: opt.vtl2_gfx,
2279        virtio_devices,
2280        vmbus: (with_hv && !opt.no_vmbus).then_some(VmbusConfig {
2281            vsock_listener: vtl0_vsock_listener,
2282            vsock_path: opt.vmbus_vsock_path.clone(),
2283            vtl2_redirect: opt.vmbus_redirect,
2284            vmbus_max_version: opt.vmbus_max_version,
2285            #[cfg(windows)]
2286            vmbusproxy_handle,
2287        }),
2288        vtl2_vmbus: (with_hv && opt.vtl2).then_some(VmbusConfig {
2289            vsock_listener: vtl2_vsock_listener,
2290            vsock_path: opt.vmbus_vtl2_vsock_path.clone(),
2291            ..Default::default()
2292        }),
2293        vmbus_devices,
2294        chipset_devices,
2295        pci_chipset_devices,
2296        isa_dma_controller,
2297        chipset_capabilities: capabilities,
2298        layout: layout_config,
2299        #[cfg(windows)]
2300        vpci_resources,
2301        vmgs,
2302        firmware_event_send: None,
2303        debugger_rpc: None,
2304        rtc_delta_milliseconds: 0,
2305    };
2306
2307    storage.build_config(&mut cfg, &mut resources, opt.scsi_sub_channels)?;
2308    let mut pcie_port_names = HashSet::new();
2309    for device in &cfg.pcie_devices {
2310        anyhow::ensure!(
2311            pcie_port_names.insert(&device.port_name),
2312            "multiple devices use PCIe port '{}'",
2313            device.port_name
2314        );
2315    }
2316    resources.serial_driver = Some(serial_driver);
2317    validate_snp_config(&cfg)?;
2318    Ok((cfg, resources))
2319}
2320
2321fn validate_snp_config(cfg: &Config) -> anyhow::Result<()> {
2322    if !matches!(
2323        cfg.hypervisor.with_isolation,
2324        Some(openvmm_defs::config::IsolationType::Snp { .. })
2325    ) {
2326        return Ok(());
2327    }
2328
2329    if !matches!(
2330        cfg.load_mode,
2331        LoadMode::Linux { .. } | LoadMode::Igvm { .. }
2332    ) {
2333        anyhow::bail!("SNP isolation currently only supports Linux direct or IGVM boot");
2334    }
2335    if cfg.hypervisor.with_vtl2.is_some() {
2336        anyhow::bail!("SNP isolation currently does not support VTL2");
2337    }
2338    if cfg.vmbus.is_some() || cfg.vtl2_vmbus.is_some() || !cfg.vmbus_devices.is_empty() {
2339        anyhow::bail!("SNP isolation currently does not support VMBus devices");
2340    }
2341
2342    let only_supported_chipset_devices = cfg.chipset_devices.iter().all(|device| {
2343        matches!(
2344            device.resource.id(),
2345            "serial_16550"
2346                | "pic"
2347                | "pit"
2348                | "generic-ioapic"
2349                | "hyperv_power_management"
2350                | "missing-dev"
2351        )
2352    });
2353    let only_virtio_pcie_devices = cfg
2354        .pcie_devices
2355        .iter()
2356        .all(|device| device.resource.id() == "virtio");
2357    if !cfg.floppy_disks.is_empty()
2358        || !cfg.ide_disks.is_empty()
2359        || !cfg.virtio_devices.is_empty()
2360        || !only_virtio_pcie_devices
2361        || !cfg.vpci_devices.is_empty()
2362        || !only_supported_chipset_devices
2363        || !cfg.pci_chipset_devices.is_empty()
2364    {
2365        anyhow::bail!("SNP isolation currently only supports virtio devices");
2366    }
2367    if cfg.framebuffer.is_some() || cfg.vga_firmware.is_some() || cfg.debugger_rpc.is_some() {
2368        anyhow::bail!("SNP isolation currently does not support this VM configuration");
2369    }
2370
2371    Ok(())
2372}
2373
2374/// Gets the terminal to use for externally launched console windows.
2375pub(crate) fn openvmm_terminal_app() -> Option<PathBuf> {
2376    std::env::var_os("OPENVMM_TERM")
2377        .or_else(|| std::env::var_os("HVLITE_TERM"))
2378        .map(Into::into)
2379}
2380
2381// Tries to remove `path` if it is confirmed to be a Unix socket.
2382fn cleanup_socket(path: &Path) {
2383    let is_socket = cfg_select! {
2384        windows => pal::windows::fs::is_unix_socket(path).unwrap_or(false),
2385        _ => path
2386            .metadata()
2387            .is_ok_and(|meta| std::os::unix::fs::FileTypeExt::is_socket(&meta.file_type())),
2388    };
2389
2390    if is_socket {
2391        let _ = std::fs::remove_file(path);
2392    }
2393}
2394
2395#[cfg(windows)]
2396fn new_switch_port(
2397    switch_id: Option<&str>,
2398) -> anyhow::Result<(
2399    openvmm_defs::config::SwitchPortId,
2400    vmswitch::kernel::SwitchPort,
2401)> {
2402    let id = vmswitch::kernel::SwitchPortId {
2403        switch: match switch_id {
2404            Some(s) => s.parse().context("invalid switch id")?,
2405            None => vmswitch::hcn::DEFAULT_SWITCH,
2406        },
2407        port: Guid::new_random(),
2408    };
2409    let _ = vmswitch::hcn::Network::open(&id.switch)
2410        .with_context(|| format!("could not find switch {}", id.switch))?;
2411
2412    let port = vmswitch::kernel::SwitchPort::new(&id).context("failed to create switch port")?;
2413
2414    let id = openvmm_defs::config::SwitchPortId {
2415        switch: id.switch,
2416        port: id.port,
2417    };
2418    Ok((id, port))
2419}
2420
2421fn parse_endpoint(
2422    cli_cfg: &NicConfigCli,
2423    index: &mut usize,
2424    resources: &mut VmResources,
2425) -> anyhow::Result<NicConfig> {
2426    let _ = resources;
2427    let endpoint = match &cli_cfg.endpoint {
2428        EndpointConfigCli::Consomme { cidr, host_fwd } => {
2429            let ports = host_fwd
2430                .iter()
2431                .map(|fwd| {
2432                    use net_backend_resources::consomme::HostPortProtocol;
2433                    net_backend_resources::consomme::HostPortConfig {
2434                        protocol: match fwd.protocol {
2435                            cli_args::HostPortProtocolCli::Tcp => HostPortProtocol::Tcp,
2436                            cli_args::HostPortProtocolCli::Udp => HostPortProtocol::Udp,
2437                        },
2438                        host_address: fwd
2439                            .host_address
2440                            .map(net_backend_resources::consomme::HostIpAddress::from),
2441                        host_port: net_backend_resources::consomme::HostPort::Fixed(fwd.host_port),
2442                        guest_port: fwd.guest_port,
2443                    }
2444                })
2445                .collect();
2446            // Only wire the bind/unbind RPC channel to the first consomme
2447            // endpoint. Additional consomme NICs work normally but cannot be
2448            // targeted by runtime bind/unbind commands.
2449            let recv = if resources.consomme_rpc.is_none() {
2450                let (send, recv) = mesh::channel();
2451                resources.consomme_rpc = Some(send);
2452                Some(recv)
2453            } else {
2454                None
2455            };
2456            net_backend_resources::consomme::ConsommeHandle {
2457                cidr: cidr.clone(),
2458                params: Default::default(),
2459                ports,
2460                internal_dns: true,
2461                recv,
2462            }
2463            .into_resource()
2464        }
2465        EndpointConfigCli::None => net_backend_resources::null::NullHandle.into_resource(),
2466        EndpointConfigCli::Dio { id } => cfg_select! {
2467            windows => {{
2468                let (port_id, port) = new_switch_port(id.as_deref())?;
2469                resources.switch_ports.push(port);
2470                net_backend_resources::dio::WindowsDirectIoHandle {
2471                    switch_port_id: net_backend_resources::dio::SwitchPortId {
2472                        switch: port_id.switch,
2473                        port: port_id.port,
2474                    },
2475                }
2476                .into_resource()
2477            }}
2478            _ => {{
2479                let _ = id;
2480                bail!("cannot use dio on non-windows platforms")
2481            }}
2482        },
2483        EndpointConfigCli::Tap { name } => cfg_select! {
2484            target_os = "linux" => {{
2485                let fd = net_tap::tap::open_tap(name)
2486                    .with_context(|| format!("failed to open TAP device '{name}'"))?;
2487                net_backend_resources::tap::TapHandle { fd }.into_resource()
2488            }}
2489            _ => {{
2490                let _ = name;
2491                bail!("TAP backend is only supported on Linux")
2492            }}
2493        },
2494    };
2495
2496    let mac_address = cli_cfg.mac_address.unwrap_or_else(|| {
2497        let mut mac_address = [0x00, 0x15, 0x5D, 0, 0, 0];
2498        getrandom::fill(&mut mac_address[3..]).expect("rng failure");
2499        mac_address.into()
2500    });
2501
2502    // Pick a fixed instance ID based on the index.
2503    const BASE_INSTANCE_ID: Guid = guid::guid!("00000000-da43-11ed-936a-00155d6db52f");
2504    let instance_id = Guid {
2505        data1: *index as u32,
2506        ..BASE_INSTANCE_ID
2507    };
2508    *index += 1;
2509
2510    Ok(NicConfig {
2511        vtl: cli_cfg.vtl,
2512        instance_id,
2513        endpoint,
2514        mac_address,
2515        max_queues: cli_cfg.max_queues,
2516        enable_rx_gso: cli_cfg.enable_rx_gso,
2517        pcie_port: cli_cfg.pcie_port.clone(),
2518    })
2519}
2520
2521/// Returns the VPCI instance ID of the MANA device for `vtl`.
2522///
2523/// The ID is fixed so that a guest sees the same device on every boot, rather
2524/// than a new one it records alongside the old.
2525fn mana_vpci_instance_id(vtl: usize) -> Guid {
2526    const BASE_INSTANCE_ID: Guid = guid::guid!("00000000-6a35-477c-a2c0-13484df4873c");
2527    Guid {
2528        data1: vtl as u32,
2529        ..BASE_INSTANCE_ID
2530    }
2531}
2532
2533#[derive(Debug)]
2534struct NicConfig {
2535    vtl: DeviceVtl,
2536    instance_id: Guid,
2537    mac_address: MacAddress,
2538    endpoint: Resource<NetEndpointHandleKind>,
2539    max_queues: Option<u16>,
2540    enable_rx_gso: bool,
2541    pcie_port: Option<String>,
2542}
2543
2544impl NicConfig {
2545    fn into_netvsp_handle(self) -> (DeviceVtl, Resource<VmbusDeviceHandleKind>) {
2546        (
2547            self.vtl,
2548            netvsp_resources::NetvspHandle {
2549                instance_id: self.instance_id,
2550                mac_address: self.mac_address,
2551                endpoint: self.endpoint,
2552                max_queues: self.max_queues,
2553            }
2554            .into_resource(),
2555        )
2556    }
2557}
2558
2559fn non_volatile_store_resource(
2560    with_vmgs: bool,
2561    file_id: vmgs_format::FileId,
2562) -> Resource<NonVolatileStoreKind> {
2563    if with_vmgs {
2564        VmgsFileHandle::new(file_id, true).into_resource()
2565    } else {
2566        EphemeralNonVolatileStoreHandle.into_resource()
2567    }
2568}
2569
2570async fn open_vmgs(
2571    kind: &DiskCliKind,
2572    provision: ProvisionCondition,
2573    encryption_policy: GuestStateEncryptionPolicy,
2574) -> anyhow::Result<VmgsResource> {
2575    let disk = VmgsDisk {
2576        disk: disk_open(kind, false).await?,
2577        encryption_policy,
2578    };
2579    Ok(match provision {
2580        ProvisionCondition::OnEmpty => VmgsResource::Disk(disk),
2581        ProvisionCondition::OnFailure => VmgsResource::ReprovisionOnFailure(disk),
2582        ProvisionCondition::Single => VmgsResource::ReprovisionSingle(disk),
2583    })
2584}
2585
2586enum LayerOrDisk {
2587    Layer(DiskLayerDescription),
2588    Disk(Resource<DiskHandleKind>),
2589}
2590
2591async fn disk_open(
2592    disk_cli: &DiskCliKind,
2593    read_only: bool,
2594) -> anyhow::Result<Resource<DiskHandleKind>> {
2595    let mut layers = Vec::new();
2596    disk_open_inner(disk_cli, read_only, &mut layers).await?;
2597    if layers.len() == 1 && matches!(layers[0], LayerOrDisk::Disk(_)) {
2598        let LayerOrDisk::Disk(disk) = layers.pop().unwrap() else {
2599            unreachable!()
2600        };
2601        Ok(disk)
2602    } else {
2603        Ok(Resource::new(disk_backend_resources::LayeredDiskHandle {
2604            layers: layers
2605                .into_iter()
2606                .map(|layer| match layer {
2607                    LayerOrDisk::Layer(layer) => layer,
2608                    LayerOrDisk::Disk(disk) => DiskLayerDescription {
2609                        layer: DiskLayerHandle(disk).into_resource(),
2610                        read_cache: false,
2611                        write_through: false,
2612                    },
2613                })
2614                .collect(),
2615        }))
2616    }
2617}
2618
2619fn disk_open_inner<'a>(
2620    disk_cli: &'a DiskCliKind,
2621    read_only: bool,
2622    layers: &'a mut Vec<LayerOrDisk>,
2623) -> futures::future::BoxFuture<'a, anyhow::Result<()>> {
2624    Box::pin(async move {
2625        fn layer<T: IntoResource<DiskLayerHandleKind>>(layer: T) -> LayerOrDisk {
2626            LayerOrDisk::Layer(layer.into_resource().into())
2627        }
2628        fn disk<T: IntoResource<DiskHandleKind>>(disk: T) -> LayerOrDisk {
2629            LayerOrDisk::Disk(disk.into_resource())
2630        }
2631        match disk_cli {
2632            &DiskCliKind::Memory(len) => {
2633                layers.push(layer(RamDiskLayerHandle {
2634                    len: Some(len),
2635                    sector_size: None,
2636                }));
2637            }
2638            DiskCliKind::File {
2639                path,
2640                create_with_len,
2641                direct,
2642            } => layers.push(LayerOrDisk::Disk(if let Some(size) = create_with_len {
2643                create_disk_type(
2644                    path,
2645                    *size,
2646                    OpenDiskOptions {
2647                        read_only: false,
2648                        direct: *direct,
2649                    },
2650                )
2651                .with_context(|| format!("failed to create {}", path.display()))?
2652            } else {
2653                open_disk_type(
2654                    path,
2655                    OpenDiskOptions {
2656                        read_only,
2657                        direct: *direct,
2658                    },
2659                )
2660                .await
2661                .with_context(|| format!("failed to open {}", path.display()))?
2662            })),
2663            DiskCliKind::Blob { kind, url } => {
2664                layers.push(disk(disk_backend_resources::BlobDiskHandle {
2665                    url: url.to_owned(),
2666                    format: match kind {
2667                        cli_args::BlobKind::Flat => disk_backend_resources::BlobDiskFormat::Flat,
2668                        cli_args::BlobKind::Vhd1 => {
2669                            disk_backend_resources::BlobDiskFormat::FixedVhd1
2670                        }
2671                    },
2672                }))
2673            }
2674            DiskCliKind::MemoryDiff(inner) => {
2675                layers.push(layer(RamDiskLayerHandle {
2676                    len: None,
2677                    sector_size: None,
2678                }));
2679                disk_open_inner(inner, true, layers).await?;
2680            }
2681            DiskCliKind::PersistentReservationsWrapper(inner) => {
2682                layers.push(disk(disk_backend_resources::DiskWithReservationsHandle(
2683                    disk_open(inner, read_only).await?,
2684                )))
2685            }
2686            DiskCliKind::DelayDiskWrapper {
2687                delay_ms,
2688                disk: inner,
2689            } => layers.push(disk(DelayDiskHandle {
2690                delay: CellUpdater::new(Duration::from_millis(*delay_ms)).cell(),
2691                disk: disk_open(inner, read_only).await?,
2692            })),
2693            DiskCliKind::Crypt {
2694                disk: inner,
2695                cipher,
2696                key_file,
2697            } => layers.push(disk(disk_crypt_resources::DiskCryptHandle {
2698                disk: disk_open(inner, read_only).await?,
2699                cipher: match cipher {
2700                    cli_args::DiskCipher::XtsAes256 => disk_crypt_resources::Cipher::XtsAes256,
2701                },
2702                key: fs_err::read(key_file).context("failed to read key file")?,
2703            })),
2704            DiskCliKind::Sqlite {
2705                path,
2706                create_with_len,
2707            } => {
2708                // FUTURE: this code should be responsible for opening
2709                // file-handle(s) itself, and passing them into sqlite via a custom
2710                // vfs. For now though - simply check if the file exists or not, and
2711                // perform early validation of filesystem-level create options.
2712                match (create_with_len.is_some(), path.exists()) {
2713                    (true, true) => anyhow::bail!(
2714                        "cannot create new sqlite disk at {} - file already exists",
2715                        path.display()
2716                    ),
2717                    (false, false) => anyhow::bail!(
2718                        "cannot open sqlite disk at {} - file not found",
2719                        path.display()
2720                    ),
2721                    _ => {}
2722                }
2723
2724                layers.push(layer(SqliteDiskLayerHandle {
2725                    dbhd_path: path.display().to_string(),
2726                    format_dbhd: create_with_len.map(|len| {
2727                        disk_backend_resources::layer::SqliteDiskLayerFormatParams {
2728                            logically_read_only: false,
2729                            len: Some(len),
2730                        }
2731                    }),
2732                }));
2733            }
2734            DiskCliKind::SqliteDiff { path, create, disk } => {
2735                // FUTURE: this code should be responsible for opening
2736                // file-handle(s) itself, and passing them into sqlite via a custom
2737                // vfs. For now though - simply check if the file exists or not, and
2738                // perform early validation of filesystem-level create options.
2739                match (create, path.exists()) {
2740                    (true, true) => anyhow::bail!(
2741                        "cannot create new sqlite disk at {} - file already exists",
2742                        path.display()
2743                    ),
2744                    (false, false) => anyhow::bail!(
2745                        "cannot open sqlite disk at {} - file not found",
2746                        path.display()
2747                    ),
2748                    _ => {}
2749                }
2750
2751                layers.push(layer(SqliteDiskLayerHandle {
2752                    dbhd_path: path.display().to_string(),
2753                    format_dbhd: create.then_some(
2754                        disk_backend_resources::layer::SqliteDiskLayerFormatParams {
2755                            logically_read_only: false,
2756                            len: None,
2757                        },
2758                    ),
2759                }));
2760                disk_open_inner(disk, true, layers).await?;
2761            }
2762            DiskCliKind::AutoCacheSqlite {
2763                cache_path,
2764                key,
2765                disk,
2766            } => {
2767                layers.push(LayerOrDisk::Layer(DiskLayerDescription {
2768                    read_cache: true,
2769                    write_through: false,
2770                    layer: SqliteAutoCacheDiskLayerHandle {
2771                        cache_path: cache_path.clone(),
2772                        cache_key: key.clone(),
2773                    }
2774                    .into_resource(),
2775                }));
2776                disk_open_inner(disk, read_only, layers).await?;
2777            }
2778        }
2779        Ok(())
2780    })
2781}
2782
2783/// Get the system page size.
2784pub(crate) fn system_page_size() -> u32 {
2785    sparse_mmap::SparseMapping::page_size() as u32
2786}
2787
2788/// The guest architecture string, derived from the compile-time `guest_arch` cfg.
2789pub(crate) const GUEST_ARCH: &str = cfg_select! {
2790    guest_arch = "x86_64" => "x86_64",
2791    guest_arch = "aarch64" => "aarch64",
2792};
2793
2794/// Open a snapshot directory and validate it against the current VM config.
2795/// Returns the shared memory fd (from memory.bin) and the saved device state.
2796fn prepare_snapshot_restore(
2797    snapshot_dir: &Path,
2798    opt: &Options,
2799) -> anyhow::Result<(
2800    openvmm_defs::worker::SharedMemoryFd,
2801    mesh::payload::message::ProtobufMessage,
2802)> {
2803    let (manifest, state_bytes) = openvmm_helpers::snapshot::read_snapshot(snapshot_dir)?;
2804
2805    // Validate manifest against current VM config.
2806    openvmm_helpers::snapshot::validate_manifest(
2807        &manifest,
2808        GUEST_ARCH,
2809        opt.memory_size(),
2810        opt.processors,
2811        system_page_size(),
2812    )?;
2813
2814    // Open memory.bin (existing file, no create, no resize).
2815    let memory_file = fs_err::OpenOptions::new()
2816        .read(true)
2817        .write(true)
2818        .open(snapshot_dir.join("memory.bin"))?;
2819
2820    // Validate file size matches expected memory size.
2821    let file_size = memory_file.metadata()?.len();
2822    if file_size != manifest.memory_size_bytes {
2823        anyhow::bail!(
2824            "memory.bin size ({file_size} bytes) doesn't match manifest ({} bytes)",
2825            manifest.memory_size_bytes,
2826        );
2827    }
2828
2829    let shared_memory_fd =
2830        openvmm_helpers::shared_memory::file_to_shared_memory_fd(memory_file.into())?;
2831
2832    // Reconstruct ProtobufMessage from the saved state bytes.
2833    // The save side wrote mesh::payload::encode(ProtobufMessage), so we decode
2834    // back to ProtobufMessage.
2835    let state_msg: mesh::payload::message::ProtobufMessage = mesh::payload::decode(&state_bytes)
2836        .context("failed to decode saved state from snapshot")?;
2837
2838    Ok((shared_memory_fd, state_msg))
2839}
2840
2841fn do_main(pidfile_guard: &mut Option<pidfile::Pidfile>) -> anyhow::Result<i32> {
2842    #[cfg(windows)]
2843    pal::windows::disable_hard_error_dialog();
2844
2845    let _tracing_guard = tracing_init::enable_tracing()?;
2846
2847    // Try to run as a worker host.
2848    // On success the worker runs to completion and then exits the process (does
2849    // not return). Any worker host setup errors are return and bubbled up.
2850    meshworker::run_vmm_mesh_host()?;
2851
2852    let opt = cli_args::parse_options();
2853
2854    // Print the version number. This comes after argument parsing to not interfere
2855    // with --version and --help.
2856    tracing::info!(version = openvmm_build_info::get().version());
2857
2858    if let Some(path) = &opt.write_saved_state_proto {
2859        mesh::payload::protofile::DescriptorWriter::new(vmcore::save_restore::saved_state_roots())
2860            .write_to_path(path)
2861            .context("failed to write protobuf descriptors")?;
2862        return Ok(0);
2863    }
2864
2865    if let Some(ref path) = opt.pidfile {
2866        *pidfile_guard = Some(pidfile::Pidfile::new(path).context("failed to create pidfile")?);
2867    }
2868
2869    if let Some(path) = opt.relay_console_path {
2870        let console_title = opt.relay_console_title.unwrap_or_default();
2871        return console_relay::relay_console(&path, console_title.as_str()).map(|()| 0);
2872    }
2873
2874    #[cfg(any(feature = "grpc", feature = "ttrpc"))]
2875    {
2876        let rpc = opt
2877            .rpc
2878            .as_ref()
2879            .map(|rpc| {
2880                let transport = match rpc.transport {
2881                    cli_args::RpcTransportCli::Auto => ttrpc::RpcTransport::Auto,
2882                    cli_args::RpcTransportCli::Ttrpc => ttrpc::RpcTransport::Ttrpc,
2883                    cli_args::RpcTransportCli::Grpc => ttrpc::RpcTransport::Grpc,
2884                };
2885                (rpc.path.as_path(), transport)
2886            })
2887            .or_else(|| {
2888                opt.ttrpc
2889                    .as_deref()
2890                    .map(|p| (p, ttrpc::RpcTransport::Ttrpc))
2891            })
2892            .or_else(|| opt.grpc.as_deref().map(|p| (p, ttrpc::RpcTransport::Grpc)));
2893
2894        if let Some((path, transport)) = rpc {
2895            return block_on(async {
2896                let _ = std::fs::remove_file(path);
2897                let listener =
2898                    unix_socket::UnixListener::bind(path).context("failed to bind to socket")?;
2899
2900                // This is a local launch
2901                let (exit_code_send, exit_code_recv) = mesh::oneshot();
2902                let mut handle =
2903                    mesh_worker::launch_local_worker::<ttrpc::TtrpcWorker>(ttrpc::Parameters {
2904                        listener,
2905                        transport,
2906                        exit_code: exit_code_send,
2907                    })
2908                    .await?;
2909
2910                tracing::info!(%transport, path = %path.display(), "listening");
2911
2912                // Signal the parent process that the server is ready.
2913                pal::close_stdout().context("failed to close stdout")?;
2914
2915                handle.join().await?;
2916
2917                exit_code_recv
2918                    .await
2919                    .context("RPC worker did not report an exit code")
2920            });
2921        }
2922    }
2923
2924    DefaultPool::run_with(async |driver| run_control(&driver, opt).await)
2925}
2926
2927fn new_hvsock_service_id(port: u32) -> Guid {
2928    // This GUID is an embedding of the AF_VSOCK port into an
2929    // AF_HYPERV service ID.
2930    Guid {
2931        data1: port,
2932        .."00000000-facb-11e6-bd58-64006a7986d3".parse().unwrap()
2933    }
2934}
2935
2936async fn run_control(driver: &DefaultDriver, opt: Options) -> anyhow::Result<i32> {
2937    let mut mesh = Some(VmmMesh::new(&driver, opt.single_process)?);
2938    let result = run_control_inner(driver, &mut mesh, opt).await;
2939    // If setup failed before the mesh was handed to the controller, shut it
2940    // down so the child host process exits cleanly without noisy logs.
2941    if let Some(mesh) = mesh {
2942        mesh.shutdown().await;
2943    }
2944    result
2945}
2946
2947async fn run_control_inner(
2948    driver: &DefaultDriver,
2949    mesh_slot: &mut Option<VmmMesh>,
2950    opt: Options,
2951) -> anyhow::Result<i32> {
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: match &opt.hypervisor {
3094                Some(name) => openvmm_helpers::hypervisor::hypervisor_resource(name)?,
3095                None => openvmm_helpers::hypervisor::choose_hypervisor()?,
3096            },
3097            cfg: vm_config,
3098            saved_state,
3099            shared_memory,
3100            rpc: rpc_recv,
3101            notify: notify_send,
3102        };
3103        vm_host
3104            .launch_worker(VM_WORKER, params)
3105            .await
3106            .context("failed to launch vm worker")?
3107    };
3108
3109    if opt.restore_snapshot.is_some() {
3110        tracing::info!("restoring VM from snapshot");
3111    }
3112
3113    if !opt.paused {
3114        vm_rpc.call(VmRpc::Resume, ()).await?;
3115    }
3116
3117    let paravisor_diag = Arc::new(diag_client::DiagClient::from_dialer(
3118        driver.clone(),
3119        DiagDialer {
3120            driver: driver.clone(),
3121            vm_rpc: vm_rpc.clone(),
3122            openhcl_vtl: if opt.vtl2 {
3123                DeviceVtl::Vtl2
3124            } else {
3125                DeviceVtl::Vtl0
3126            },
3127        },
3128    ));
3129
3130    let diag_inspector = DiagInspector::new(driver.clone(), paravisor_diag.clone());
3131
3132    // Create channels between the REPL and VmController.
3133    let (vm_controller_send, vm_controller_recv) = mesh::channel();
3134    let (vm_controller_event_send, vm_controller_event_recv) = mesh::channel();
3135
3136    let has_vtl2 = resources.vtl2_settings.is_some();
3137    let serial_driver = resources
3138        .serial_driver
3139        .take()
3140        .expect("serial driver must outlive serial resources");
3141
3142    // Build the VmController with exclusive resources.
3143    let controller = vm_controller::VmController {
3144        mesh: mesh_slot.take().unwrap(),
3145        vm_worker,
3146        vnc_worker,
3147        gdb_worker,
3148        diag_inspector: Some(diag_inspector),
3149        vtl2_settings: resources.vtl2_settings,
3150        ged_rpc: resources.ged_rpc.clone(),
3151        vm_rpc: vm_rpc.clone(),
3152        paravisor_diag: Some(paravisor_diag),
3153        igvm_path: opt.igvm.as_ref().map(|igvm| igvm.firmware.clone()),
3154        memory_backing_file: opt.memory_backing_file().cloned(),
3155        memory: opt.memory_size(),
3156        processors: opt.processors,
3157        log_file: opt.log_file.clone(),
3158        crash_dump_path: opt.crash_dump_path.clone(),
3159        guest_power_actions: vm_controller::GuestPowerActions {
3160            shutdown: opt.guest_shutdown_action,
3161            reset: opt.guest_reset_action,
3162            crash: opt.guest_crash_action,
3163            watchdog: opt.guest_watchdog_action,
3164        },
3165    };
3166
3167    // Spawn the VmController as a task.
3168    let controller_task = driver.spawn(
3169        "vm-controller",
3170        controller.run(vm_controller_recv, vm_controller_event_send, notify_recv),
3171    );
3172
3173    // Run the REPL with shareable resources.
3174    let repl_result = repl::run_repl(
3175        driver,
3176        repl::ReplResources {
3177            vm_rpc,
3178            vm_controller: vm_controller_send,
3179            vm_controller_events: vm_controller_event_recv,
3180            scsi_rpc: resources.scsi_rpc,
3181            nvme_vtl2_rpc: resources.nvme_vtl2_rpc,
3182            consomme_rpc: resources.consomme_rpc,
3183            shutdown_ic: resources.shutdown_ic,
3184            acpi_power_button: resources.acpi_power_button,
3185            kvp_ic: resources.kvp_ic,
3186            console_in: resources.console_in,
3187            has_vtl2,
3188        },
3189    )
3190    .await;
3191
3192    // Wait for the controller task to finish (it stops the VM worker and
3193    // shuts down the mesh).
3194    controller_task.await;
3195    drop(serial_driver);
3196
3197    // run_repl returns the exit status: the code the guest drove via an opt-in
3198    // exit (VmControllerEvent::ExitRequested), or 0 when the VM stopped normally.
3199    repl_result
3200}
3201
3202struct DiagDialer {
3203    driver: DefaultDriver,
3204    vm_rpc: mesh::Sender<VmRpc>,
3205    openhcl_vtl: DeviceVtl,
3206}
3207
3208impl mesh_rpc::client::Dial for DiagDialer {
3209    type Stream = PolledSocket<unix_socket::UnixStream>;
3210
3211    async fn dial(&mut self) -> io::Result<Self::Stream> {
3212        let service_id = new_hvsock_service_id(1);
3213        let socket = self
3214            .vm_rpc
3215            .call_failable(
3216                VmRpc::ConnectHvsock,
3217                (
3218                    CancelContext::new().with_timeout(Duration::from_secs(2)),
3219                    service_id,
3220                    self.openhcl_vtl,
3221                ),
3222            )
3223            .await
3224            .map_err(io::Error::other)?;
3225
3226        PolledSocket::new(&self.driver, socket)
3227    }
3228}
3229
3230/// An object that implements [`InspectMut`] by sending an inspect request over
3231/// TTRPC to the guest (typically the paravisor running in VTL2), then stitching
3232/// the response back into the inspect tree.
3233///
3234/// This also caches the TTRPC connection to the guest so that only the first
3235/// inspect request has to wait for the connection to be established.
3236pub(crate) struct DiagInspector(DiagInspectorInner);
3237
3238enum DiagInspectorInner {
3239    NotStarted(DefaultDriver, Arc<diag_client::DiagClient>),
3240    Started {
3241        send: mesh::Sender<inspect::Deferred>,
3242        _task: Task<()>,
3243    },
3244    Invalid,
3245}
3246
3247impl DiagInspector {
3248    pub fn new(driver: DefaultDriver, diag_client: Arc<diag_client::DiagClient>) -> Self {
3249        Self(DiagInspectorInner::NotStarted(driver, diag_client))
3250    }
3251
3252    fn start(&mut self) -> &mesh::Sender<inspect::Deferred> {
3253        loop {
3254            match self.0 {
3255                DiagInspectorInner::NotStarted { .. } => {
3256                    let DiagInspectorInner::NotStarted(driver, client) =
3257                        std::mem::replace(&mut self.0, DiagInspectorInner::Invalid)
3258                    else {
3259                        unreachable!()
3260                    };
3261                    let (send, recv) = mesh::channel();
3262                    let task = driver.clone().spawn("diag-inspect", async move {
3263                        Self::run(&client, recv).await
3264                    });
3265
3266                    self.0 = DiagInspectorInner::Started { send, _task: task };
3267                }
3268                DiagInspectorInner::Started { ref send, .. } => break send,
3269                DiagInspectorInner::Invalid => unreachable!(),
3270            }
3271        }
3272    }
3273
3274    async fn run(
3275        diag_client: &diag_client::DiagClient,
3276        mut recv: mesh::Receiver<inspect::Deferred>,
3277    ) {
3278        while let Some(deferred) = recv.next().await {
3279            let info = deferred.external_request();
3280            let result = match info.request_type {
3281                inspect::ExternalRequestType::Inspect { depth } => {
3282                    if depth == 0 {
3283                        Ok(inspect::Node::Unevaluated)
3284                    } else {
3285                        // TODO: Support taking timeouts from the command line
3286                        diag_client
3287                            .inspect(info.path, Some(depth - 1), Some(Duration::from_secs(1)))
3288                            .await
3289                    }
3290                }
3291                inspect::ExternalRequestType::Update { value } => {
3292                    (diag_client.update(info.path, value).await).map(inspect::Node::Value)
3293                }
3294            };
3295            deferred.complete_external(
3296                result.unwrap_or_else(|err| {
3297                    inspect::Node::Failed(inspect::Error::Mesh(format!("{err:#}")))
3298                }),
3299                inspect::SensitivityLevel::Unspecified,
3300            )
3301        }
3302    }
3303}
3304
3305impl InspectMut for DiagInspector {
3306    fn inspect_mut(&mut self, req: inspect::Request<'_>) {
3307        self.start().send(req.defer());
3308    }
3309}
3310
3311#[cfg(test)]
3312mod tests {
3313    use super::*;
3314    use clap::Parser;
3315    use std::fs::File;
3316    use test_with_tracing::test;
3317    use vm_resource::ResourceId;
3318
3319    /// The same boot flags give the same ACPI power button with and without
3320    /// `--restore-snapshot`.
3321    #[test]
3322    fn restore_builds_the_acpi_power_button_of_its_boot_command_line() {
3323        DefaultPool::run_with(async |driver| {
3324            let temp_dir = tempfile::tempdir().unwrap();
3325            let file = |name: &str| {
3326                let path = temp_dir.path().join(name);
3327                File::create(&path).unwrap();
3328                path.to_str().unwrap().to_owned()
3329            };
3330            let kernel = file("kernel");
3331            let initrd = file("initrd");
3332            let uefi = format!("--uefi=firmware={}", file("firmware"));
3333            // The config build does not read the snapshot directory.
3334            let snapshot = temp_dir.path().join("snapshot");
3335            let linux = ["--kernel", kernel.as_str(), "--initrd", initrd.as_str()];
3336
3337            for (boot, has_button) in [
3338                (linux.to_vec(), true),
3339                ([&linux[..], &["--device-tree"]].concat(), false),
3340                (vec![uefi.as_str()], true),
3341            ] {
3342                for restore in [false, true] {
3343                    let mut args = vec!["openvmm", "--single-process"];
3344                    args.extend(&boot);
3345                    if restore {
3346                        args.extend(["--restore-snapshot", snapshot.to_str().unwrap()]);
3347                    }
3348                    let opt = Options::try_parse_from(&args).unwrap();
3349                    let mesh = VmmMesh::new(&driver, true).unwrap();
3350                    let (config, _) = vm_config_from_command_line(driver.clone(), &mesh, &opt)
3351                        .await
3352                        .unwrap();
3353                    mesh.shutdown().await;
3354
3355                    let built = config
3356                        .chipset_devices
3357                        .iter()
3358                        .any(|device| device.name == "acpi-power-button");
3359                    assert_eq!(built, has_button, "{args:?}");
3360                }
3361            }
3362        });
3363    }
3364
3365    #[test]
3366    fn selects_non_volatile_store_backing() {
3367        for file_id in [
3368            vmgs_format::FileId::BIOS_NVRAM,
3369            vmgs_format::FileId::TPM_PPI,
3370            tpm_vmgs::tpm_nvram_file_id(TpmVersion::V138),
3371            tpm_vmgs::tpm_nvram_file_id(TpmVersion::V185),
3372        ] {
3373            assert_eq!(
3374                non_volatile_store_resource(true, file_id).id(),
3375                <VmgsFileHandle as ResourceId<NonVolatileStoreKind>>::ID
3376            );
3377            assert_eq!(
3378                non_volatile_store_resource(false, file_id).id(),
3379                <EphemeralNonVolatileStoreHandle as ResourceId<NonVolatileStoreKind>>::ID
3380            );
3381        }
3382    }
3383
3384    #[test]
3385    fn opens_vmgs_with_provisioning_and_encryption_policy() {
3386        block_on(async {
3387            for provision in [
3388                ProvisionCondition::OnEmpty,
3389                ProvisionCondition::OnFailure,
3390                ProvisionCondition::Single,
3391            ] {
3392                for encryption_policy in [
3393                    GuestStateEncryptionPolicy::None(true),
3394                    GuestStateEncryptionPolicy::GspById(true),
3395                ] {
3396                    let vmgs = open_vmgs(
3397                        &DiskCliKind::Memory(vmgs_format::VMGS_DEFAULT_CAPACITY),
3398                        provision,
3399                        encryption_policy,
3400                    )
3401                    .await
3402                    .unwrap();
3403                    let disk = match (provision, vmgs) {
3404                        (ProvisionCondition::OnEmpty, VmgsResource::Disk(disk))
3405                        | (
3406                            ProvisionCondition::OnFailure,
3407                            VmgsResource::ReprovisionOnFailure(disk),
3408                        )
3409                        | (ProvisionCondition::Single, VmgsResource::ReprovisionSingle(disk)) => {
3410                            disk
3411                        }
3412                        _ => panic!("incorrect VMGS provisioning"),
3413                    };
3414                    assert!(matches!(
3415                        (encryption_policy, disk.encryption_policy),
3416                        (
3417                            GuestStateEncryptionPolicy::None(true),
3418                            GuestStateEncryptionPolicy::None(true)
3419                        ) | (
3420                            GuestStateEncryptionPolicy::GspById(true),
3421                            GuestStateEncryptionPolicy::GspById(true)
3422                        )
3423                    ));
3424                }
3425            }
3426        });
3427    }
3428
3429    /// Declaring controllers alone must not create implicit device attachments.
3430    #[test]
3431    fn usb_cli_empty_controllers() {
3432        let opt = Options::try_parse_from(["openvmm", "--usb-xhci", "usb0", "--usb-xhci", "usb1"])
3433            .unwrap();
3434        let controllers = usb_controller_configs(&opt.usb_xhci, &opt.usb_device).unwrap();
3435        assert_eq!(controllers.len(), 2);
3436        assert!(
3437            controllers
3438                .iter()
3439                .all(|(_, config)| config.devices.is_empty())
3440        );
3441    }
3442
3443    /// A sole controller supplies omitted on values; omitted connectors are left to the resolver.
3444    #[test]
3445    fn usb_cli_infers_single_controller() {
3446        let opt = Options::try_parse_from([
3447            "openvmm",
3448            "--usb-xhci",
3449            "usb0",
3450            "--usb-device",
3451            "mock-hid",
3452            "--usb-device",
3453            "mock-loopback",
3454            "--usb-device",
3455            "mock-storage",
3456            "--usb-device",
3457            "mock-mutt",
3458            "--usb-device",
3459            "mock-supermutt",
3460            "--usb-device",
3461            r"winusb,instance_id=USB\A",
3462            "--usb-device",
3463            "winusb-all",
3464        ])
3465        .unwrap();
3466        let controllers = usb_controller_configs(&opt.usb_xhci, &opt.usb_device).unwrap();
3467        assert_eq!(controllers[0].0, "usb0");
3468        assert_eq!(controllers[0].1.devices.len(), 7);
3469        for config in controllers[0].1.devices.iter().take(6) {
3470            let usb_config_resources::UsbDeviceConfig::Device { connector, .. } = config else {
3471                panic!("expected a device attachment");
3472            };
3473            assert_eq!(*connector, None);
3474        }
3475        assert!(matches!(
3476            controllers[0].1.devices[6],
3477            usb_config_resources::UsbDeviceConfig::Discover(_)
3478        ));
3479    }
3480
3481    /// An omitted on value is ambiguous when more than one controller is declared.
3482    #[test]
3483    fn usb_cli_requires_explicit_controller_when_ambiguous() {
3484        for selection in [
3485            "mock-hid",
3486            "mock-hid,connector=1",
3487            r"winusb,instance_id=USB\A",
3488            "winusb-all",
3489        ] {
3490            let opt = Options::try_parse_from([
3491                "openvmm",
3492                "--usb-xhci",
3493                "usb0",
3494                "--usb-xhci",
3495                "usb1",
3496                "--usb-device",
3497                selection,
3498            ])
3499            .unwrap();
3500            let error = usb_controller_configs(&opt.usb_xhci, &opt.usb_device).unwrap_err();
3501            assert!(error.to_string().contains("on=PCIE_PORT is required"));
3502        }
3503    }
3504
3505    /// Normalization preserves one-based connector numbers and explicit mock overrides.
3506    #[test]
3507    fn usb_cli_preserves_one_based_connectors_and_mock_overrides() {
3508        let opt = Options::try_parse_from([
3509            "openvmm",
3510            "--usb-xhci",
3511            "usb0",
3512            "--usb-xhci",
3513            "usb1",
3514            "--usb-device",
3515            "mock-hid,on=usb0,connector=1,vid=0x1234,pid=65535,serial=HID001",
3516            "--usb-device",
3517            "mock-storage,on=usb1,connector=15,blocks=4096",
3518        ])
3519        .unwrap();
3520        let controllers = usb_controller_configs(&opt.usb_xhci, &opt.usb_device).unwrap();
3521        let usb_config_resources::UsbDeviceConfig::Device { connector, device } =
3522            &controllers[0].1.devices[0]
3523        else {
3524            panic!("expected fixed HID attachment");
3525        };
3526        assert_eq!(*connector, Some(1));
3527        assert_eq!(device.id(), "mock_hid_config");
3528        let usb_config_resources::UsbDeviceConfig::Device { connector, .. } =
3529            &controllers[1].1.devices[0]
3530        else {
3531            panic!("expected fixed storage attachment");
3532        };
3533        assert_eq!(*connector, Some(15));
3534        let cli_args::UsbDeviceCli::Device {
3535            backend: usb::UsbBackend::Hid(handle),
3536            ..
3537        } = &opt.usb_device[0]
3538        else {
3539            panic!("expected HID");
3540        };
3541        assert_eq!(
3542            (handle.identity.vendor_id, handle.identity.product_id),
3543            (Some(0x1234), Some(65535))
3544        );
3545        assert_eq!(handle.identity.serial_number.as_deref(), Some("HID001"));
3546        let cli_args::UsbDeviceCli::Device {
3547            backend: usb::UsbBackend::Storage(handle),
3548            ..
3549        } = &opt.usb_device[1]
3550        else {
3551            panic!("expected storage");
3552        };
3553        assert_eq!(handle.block_count, Some(4096));
3554    }
3555
3556    /// Explicit host IDs are preserved and automatic discovery remains a separate request.
3557    #[test]
3558    fn usb_cli_preserves_winusb_ids_and_automatic_selection() {
3559        let instance_id = r"USB\MS_COMP_WINUSB\A&B C";
3560        let selection = format!("winusb,on=usb0,connector=3,instance_id={instance_id}");
3561        let opt = Options::try_parse_from([
3562            "openvmm",
3563            "--usb-xhci",
3564            "usb0",
3565            "--usb-device",
3566            &selection,
3567            "--usb-device",
3568            "winusb-all,on=usb0",
3569        ])
3570        .unwrap();
3571        let controllers = usb_controller_configs(&opt.usb_xhci, &opt.usb_device).unwrap();
3572        let cli_args::UsbDeviceCli::Device {
3573            backend: usb::UsbBackend::WinUsb(handle),
3574            ..
3575        } = &opt.usb_device[0]
3576        else {
3577            panic!("expected WinUSB");
3578        };
3579        assert_eq!(handle.instance_id, instance_id);
3580        let usb_config_resources::UsbDeviceConfig::Device { connector, device } =
3581            &controllers[0].1.devices[0]
3582        else {
3583            panic!("expected fixed WinUSB attachment");
3584        };
3585        assert_eq!(*connector, Some(3));
3586        assert_eq!(device.id(), "winusb_config");
3587        let usb_config_resources::UsbDeviceConfig::Discover(discovery) =
3588            &controllers[0].1.devices[1]
3589        else {
3590            panic!("expected WinUSB discovery");
3591        };
3592        assert_eq!(discovery.id(), "winusb_all_config");
3593    }
3594
3595    /// Reject malformed backend options and missing, duplicate, or unknown controllers.
3596    #[test]
3597    fn usb_cli_rejects_bad_syntax_and_unknown_controllers() {
3598        for selection in [
3599            "usb0:hid",
3600            "winusb",
3601            "mock-hid,on=usb0,connector=0",
3602            "mock-hid,on=usb0,connector=256",
3603            "mock-hid,on=usb0,connector=1,vid=0x10000",
3604            "mock-hid,on=usb0,connector=1,pid=bad",
3605            "mock-hid,on=usb0,connector=1,unknown=1",
3606            "mock-hid,on=usb0,connector=1,instance_id=USB",
3607            "mock-hid,on=usb0,connector=1,blocks=1",
3608            "mock-supermutt,on=usb0,connector=1,vid=1",
3609            "mock-storage,on=usb0,connector=1,blocks=0",
3610            "winusb,on=usb0,connector=1,instance_id=USB,vid=1",
3611            "winusb-all,on=usb0,connector=1",
3612        ] {
3613            assert!(
3614                Options::try_parse_from([
3615                    "openvmm",
3616                    "--usb-xhci",
3617                    "usb0",
3618                    "--usb-device",
3619                    selection
3620                ])
3621                .is_err()
3622            );
3623        }
3624        assert!(
3625            Options::try_parse_from(["openvmm", "--usb-device", "mock-hid,on=usb0,connector=1"])
3626                .is_err()
3627        );
3628        assert!(Options::try_parse_from(["openvmm", "--usb-xhci", "usb0,unknown=1"]).is_err());
3629        let opt = Options::try_parse_from([
3630            "openvmm",
3631            "--usb-xhci",
3632            "usb0",
3633            "--usb-device",
3634            "mock-hid,on=missing,connector=1",
3635        ])
3636        .unwrap();
3637        assert!(usb_controller_configs(&opt.usb_xhci, &opt.usb_device).is_err());
3638        let opt = Options::try_parse_from(["openvmm", "--usb-xhci", "usb0", "--usb-xhci", "usb0"])
3639            .unwrap();
3640        assert!(usb_controller_configs(&opt.usb_xhci, &opt.usb_device).is_err());
3641    }
3642
3643    /// Backend defaults, capacity limits, and connector conflicts must not be
3644    /// baked into the shared CLI.
3645    #[test]
3646    fn usb_cli_leaves_defaults_and_implementation_limits_to_resolvers() {
3647        let opt = Options::try_parse_from([
3648            "openvmm",
3649            "--usb-xhci",
3650            "usb0",
3651            "--usb-device",
3652            "mock-storage,on=usb0,connector=16,blocks=524289",
3653            "--usb-device",
3654            "mock-storage,on=usb0,connector=1",
3655            "--usb-device",
3656            "mock-hid,on=usb0,connector=1",
3657        ])
3658        .unwrap();
3659        assert!(usb_controller_configs(&opt.usb_xhci, &opt.usb_device).is_ok());
3660        let cli_args::UsbDeviceCli::Device {
3661            backend: usb::UsbBackend::Storage(config),
3662            ..
3663        } = &opt.usb_device[1]
3664        else {
3665            panic!("expected storage");
3666        };
3667        assert_eq!(config.block_count, None);
3668        assert_eq!(config.identity, Default::default());
3669    }
3670
3671    /// Discovery excludes explicit host IDs across controllers regardless of option order.
3672    /// Resource resolution is async even when the test only decodes configuration.
3673    #[pal_async::async_test]
3674    async fn usb_cli_excludes_explicit_winusb_across_controllers() {
3675        use usb_config_resources::UsbDeviceDiscoveryConfigKind;
3676        use usb_config_resources::WinUsbAllConfig;
3677        use vm_resource::CanResolveTo;
3678        use vm_resource::ResolveResource;
3679        use vm_resource::ResourceResolver;
3680
3681        /// Discovery settings decoded for assertions without host enumeration.
3682        struct CapturedDiscoveryConfig {
3683            /// The actual configuration emitted by the CLI.
3684            config: WinUsbAllConfig,
3685        }
3686        /// Reads an opaque discovery resource without constructing USB devices.
3687        struct CaptureDiscoveryConfig;
3688
3689        impl CanResolveTo<CapturedDiscoveryConfig> for UsbDeviceDiscoveryConfigKind {
3690            type Input<'a> = ();
3691        }
3692
3693        impl ResolveResource<UsbDeviceDiscoveryConfigKind, WinUsbAllConfig> for CaptureDiscoveryConfig {
3694            type Output = CapturedDiscoveryConfig;
3695            type Error = std::convert::Infallible;
3696
3697            fn resolve(&self, config: WinUsbAllConfig, _: ()) -> Result<Self::Output, Self::Error> {
3698                Ok(CapturedDiscoveryConfig { config })
3699            }
3700        }
3701
3702        let mut resolver = ResourceResolver::new();
3703        resolver.add_resolver(CaptureDiscoveryConfig);
3704        for selections in [
3705            [
3706                "winusb-all,on=usb0",
3707                r"winusb,on=usb1,instance_id=usb\z",
3708                r"winusb,on=usb1,instance_id=USB\a",
3709            ],
3710            [
3711                r"winusb,on=usb1,instance_id=usb\z",
3712                r"winusb,on=usb1,instance_id=USB\a",
3713                "winusb-all,on=usb0",
3714            ],
3715        ] {
3716            let mut opt =
3717                Options::try_parse_from(["openvmm", "--usb-xhci", "usb0", "--usb-xhci", "usb1"])
3718                    .unwrap();
3719            opt.usb_device = selections
3720                .into_iter()
3721                .map(|selection| selection.parse().unwrap())
3722                .collect();
3723            let mut controllers = usb_controller_configs(&opt.usb_xhci, &opt.usb_device).unwrap();
3724            assert_eq!(controllers[1].1.devices.len(), 2);
3725            let usb_config_resources::UsbDeviceConfig::Discover(discovery) =
3726                controllers[0].1.devices.pop().unwrap()
3727            else {
3728                panic!("expected discovery on usb0");
3729            };
3730            let captured: CapturedDiscoveryConfig = resolver.resolve(discovery, ()).await.unwrap();
3731            assert_eq!(captured.config.excluded_instance_ids, [r"USB\A", r"USB\Z"]);
3732        }
3733    }
3734
3735    /// Reject duplicate host IDs and multiple automatic discovery requests across the VM.
3736    #[test]
3737    fn usb_cli_rejects_overlapping_host_selections() {
3738        for (first, second) in [
3739            (
3740                "winusb,on=usb0,connector=1,instance_id=USB\\A",
3741                "winusb,on=usb1,connector=1,instance_id=usb\\a",
3742            ),
3743            ("winusb-all,on=usb0", "winusb-all,on=usb1"),
3744        ] {
3745            let opt = Options::try_parse_from([
3746                "openvmm",
3747                "--usb-xhci",
3748                "usb0",
3749                "--usb-xhci",
3750                "usb1",
3751                "--usb-device",
3752                first,
3753                "--usb-device",
3754                second,
3755            ])
3756            .unwrap();
3757            assert!(usb_controller_configs(&opt.usb_xhci, &opt.usb_device).is_err());
3758        }
3759    }
3760
3761    #[test]
3762    fn maps_igvm_personalities_to_chipsets() {
3763        for (args, expected) in [
3764            (
3765                vec!["openvmm", "--igvm", "firmware=guest.igvm,personality=uefi"],
3766                BaseChipsetType::HypervGen2Uefi,
3767            ),
3768            (
3769                vec![
3770                    "openvmm",
3771                    "--igvm",
3772                    "firmware=guest.igvm,personality=linux-direct",
3773                ],
3774                BaseChipsetType::UnenlightenedLinuxDirect,
3775            ),
3776            (
3777                vec![
3778                    "openvmm",
3779                    "--igvm",
3780                    "firmware=guest.igvm,personality=linux-direct",
3781                    "--hv",
3782                ],
3783                BaseChipsetType::HyperVGen2LinuxDirect,
3784            ),
3785            (
3786                vec![
3787                    "openvmm",
3788                    "--igvm",
3789                    "firmware=guest.igvm,personality=linux-direct",
3790                    "--isolation",
3791                    "snp",
3792                ],
3793                BaseChipsetType::EnlightenedLinuxDirect,
3794            ),
3795            (
3796                vec![
3797                    "openvmm",
3798                    "--igvm",
3799                    "firmware=guest.igvm,personality=openhcl",
3800                    "--hv",
3801                    "--vtl2",
3802                ],
3803                BaseChipsetType::HclHost,
3804            ),
3805        ] {
3806            let opt = Options::try_parse_from(args).unwrap();
3807            opt.validate_igvm_options().unwrap();
3808            assert!(
3809                std::mem::discriminant(&base_chipset_type(&opt))
3810                    == std::mem::discriminant(&expected)
3811            );
3812        }
3813    }
3814
3815    #[test]
3816    fn builds_openhcl_igvm_config_without_host_uefi() {
3817        DefaultPool::run_with(async |driver| {
3818            let temp_dir = tempfile::tempdir().unwrap();
3819            let igvm_path = temp_dir.path().join("guest.igvm");
3820            File::create(&igvm_path).unwrap();
3821            let igvm_options = format!("firmware={},personality=openhcl", igvm_path.display());
3822            let mesh = VmmMesh::new(&driver, true).unwrap();
3823
3824            for (extra, expected_alias, expected_policy) in [
3825                (vec![], true, Some(LateMapVtl0MemoryPolicy::Halt)),
3826                (
3827                    vec!["--uefi", "console=com1,disable_frontpage"],
3828                    true,
3829                    Some(LateMapVtl0MemoryPolicy::Halt),
3830                ),
3831                (
3832                    vec!["--net", "uh:consomme", "--no-alias-map"],
3833                    false,
3834                    Some(LateMapVtl0MemoryPolicy::Halt),
3835                ),
3836                (
3837                    vec!["--isolation", "vbs", "--no-alias-map"],
3838                    false,
3839                    Some(LateMapVtl0MemoryPolicy::Halt),
3840                ),
3841                (
3842                    vec!["--no-alias-map", "--late-map-vtl0-policy", "exception"],
3843                    false,
3844                    Some(LateMapVtl0MemoryPolicy::InjectException),
3845                ),
3846                (
3847                    vec!["--late-map-vtl0-policy", "log"],
3848                    true,
3849                    Some(LateMapVtl0MemoryPolicy::Log),
3850                ),
3851                (
3852                    vec!["--igvm-vtl2-relocation-type", "vtl2=filesize"],
3853                    true,
3854                    Some(LateMapVtl0MemoryPolicy::Halt),
3855                ),
3856                (
3857                    vec![
3858                        "--igvm-vtl2-relocation-type",
3859                        "vtl2=filesize",
3860                        "--late-map-vtl0-policy",
3861                        "off",
3862                    ],
3863                    true,
3864                    None,
3865                ),
3866            ] {
3867                let mut args = vec![
3868                    "openvmm",
3869                    "--igvm",
3870                    &igvm_options,
3871                    "--hv",
3872                    "--vtl2",
3873                    "--single-process",
3874                ];
3875                args.extend(extra);
3876                let opt = Options::try_parse_from(args).unwrap();
3877                let (config, resources) = vm_config_from_command_line(driver.clone(), &mesh, &opt)
3878                    .await
3879                    .unwrap();
3880
3881                assert!(matches!(config.load_mode, LoadMode::Igvm { .. }));
3882                assert!(config.hypervisor.with_hv);
3883                let vtl2 = config.hypervisor.with_vtl2.as_ref().unwrap();
3884                assert_eq!(vtl2.vtl0_alias_map, expected_alias);
3885                assert_eq!(vtl2.late_map_vtl0_memory, expected_policy);
3886                assert!(config.vmbus.is_some());
3887                assert!(config.vtl2_vmbus.is_some());
3888                assert!(resources.ged_rpc.is_some());
3889                assert!(resources.acpi_power_button.is_none());
3890                for id in ["ged", "gel"] {
3891                    assert!(
3892                        config.vmbus_devices.iter().any(|(vtl, resource)| {
3893                            *vtl == DeviceVtl::Vtl2 && resource.id() == id
3894                        })
3895                    );
3896                }
3897                assert!(
3898                    config
3899                        .chipset_devices
3900                        .iter()
3901                        .all(|device| { device.resource.id() != "hyperv_firmware_uefi" })
3902                );
3903            }
3904            for (extra, expected_error) in [
3905                (
3906                    ["--net", "uh:consomme"],
3907                    "must specify --no-alias-map to offer NICs to VTL2",
3908                ),
3909                (
3910                    ["--isolation", "vbs"],
3911                    "alias map not supported with isolation",
3912                ),
3913            ] {
3914                let mut args = vec![
3915                    "openvmm",
3916                    "--igvm",
3917                    &igvm_options,
3918                    "--hv",
3919                    "--vtl2",
3920                    "--single-process",
3921                ];
3922                args.extend(extra);
3923                let opt = Options::try_parse_from(args).unwrap();
3924                let err = vm_config_from_command_line(driver.clone(), &mesh, &opt)
3925                    .await
3926                    .err()
3927                    .unwrap();
3928                assert_eq!(err.to_string(), expected_error);
3929            }
3930            mesh.shutdown().await;
3931        });
3932    }
3933
3934    #[test]
3935    fn maps_virtio_vsock_to_named_pcie_port() {
3936        DefaultPool::run_with(async |driver| {
3937            let temp_dir = tempfile::tempdir().unwrap();
3938            let kernel_path = temp_dir.path().join("kernel");
3939            File::create(&kernel_path).unwrap();
3940            let initrd_path = temp_dir.path().join("initrd");
3941            File::create(&initrd_path).unwrap();
3942            let socket_path = temp_dir.path().join("vsock");
3943            let opt = Options::try_parse_from([
3944                "openvmm",
3945                "--kernel",
3946                kernel_path.to_str().unwrap(),
3947                "--initrd",
3948                initrd_path.to_str().unwrap(),
3949                "--virtio-vsock-path",
3950                socket_path.to_str().unwrap(),
3951                "--virtio-vsock-bus",
3952                "pcie:custom",
3953                "--single-process",
3954            ])
3955            .unwrap();
3956            let mesh = VmmMesh::new(&driver, true).unwrap();
3957
3958            let (config, _resources) = vm_config_from_command_line(driver, &mesh, &opt)
3959                .await
3960                .unwrap();
3961
3962            assert_eq!(config.pcie_devices.len(), 1);
3963            assert_eq!(config.pcie_devices[0].port_name, "custom");
3964            mesh.shutdown().await;
3965        });
3966    }
3967
3968    #[test]
3969    fn maps_virtio_fs_and_rng_to_named_pcie_ports() {
3970        DefaultPool::run_with(async |driver| {
3971            let temp_dir = tempfile::tempdir().unwrap();
3972            let kernel_path = temp_dir.path().join("kernel");
3973            File::create(&kernel_path).unwrap();
3974            let initrd_path = temp_dir.path().join("initrd");
3975            File::create(&initrd_path).unwrap();
3976            let root_path = temp_dir.path().to_str().unwrap();
3977            let opt = Options::try_parse_from([
3978                "openvmm",
3979                "--kernel",
3980                kernel_path.to_str().unwrap(),
3981                "--initrd",
3982                initrd_path.to_str().unwrap(),
3983                "--virtio-fs",
3984                &format!("fs,{root_path}"),
3985                "--virtio-fs-bus",
3986                "pcie:fs",
3987                "--virtio-rng",
3988                "--virtio-rng-bus",
3989                "pcie:rng",
3990                "--single-process",
3991            ])
3992            .unwrap();
3993            let mesh = VmmMesh::new(&driver, true).unwrap();
3994
3995            let (config, _resources) = vm_config_from_command_line(driver, &mesh, &opt)
3996                .await
3997                .unwrap();
3998
3999            let port_names: Vec<_> = config
4000                .pcie_devices
4001                .iter()
4002                .map(|device| device.port_name.as_str())
4003                .collect();
4004            assert_eq!(port_names, ["fs", "rng"]);
4005            mesh.shutdown().await;
4006        });
4007    }
4008
4009    #[test]
4010    fn rejects_duplicate_pcie_port_assignments() {
4011        DefaultPool::run_with(async |driver| {
4012            let temp_dir = tempfile::tempdir().unwrap();
4013            let kernel_path = temp_dir.path().join("kernel");
4014            File::create(&kernel_path).unwrap();
4015            let initrd_path = temp_dir.path().join("initrd");
4016            File::create(&initrd_path).unwrap();
4017            let root_path = temp_dir.path().to_str().unwrap();
4018            let opt = Options::try_parse_from([
4019                "openvmm",
4020                "--kernel",
4021                kernel_path.to_str().unwrap(),
4022                "--initrd",
4023                initrd_path.to_str().unwrap(),
4024                "--virtio-fs",
4025                &format!("pcie_port=custom:fs,{root_path}"),
4026                "--virtio-rng",
4027                "--virtio-rng-bus",
4028                "pcie:custom",
4029                "--single-process",
4030            ])
4031            .unwrap();
4032            let mesh = VmmMesh::new(&driver, true).unwrap();
4033
4034            let error = vm_config_from_command_line(driver, &mesh, &opt)
4035                .await
4036                .err()
4037                .unwrap();
4038
4039            assert_eq!(error.to_string(), "multiple devices use PCIe port 'custom'");
4040            mesh.shutdown().await;
4041        });
4042    }
4043
4044    #[test]
4045    fn rejects_duplicate_pcie_port_assignment_from_storage() {
4046        DefaultPool::run_with(async |driver| {
4047            let temp_dir = tempfile::tempdir().unwrap();
4048            let kernel_path = temp_dir.path().join("kernel");
4049            File::create(&kernel_path).unwrap();
4050            let initrd_path = temp_dir.path().join("initrd");
4051            File::create(&initrd_path).unwrap();
4052            let opt = Options::try_parse_from([
4053                "openvmm",
4054                "--kernel",
4055                kernel_path.to_str().unwrap(),
4056                "--initrd",
4057                initrd_path.to_str().unwrap(),
4058                "--nvme-pci",
4059                "id=nvme0,pcie_port=custom",
4060                "--virtio-rng",
4061                "--virtio-rng-bus",
4062                "pcie:custom",
4063                "--single-process",
4064            ])
4065            .unwrap();
4066            let mesh = VmmMesh::new(&driver, true).unwrap();
4067
4068            let error = vm_config_from_command_line(driver, &mesh, &opt)
4069                .await
4070                .err()
4071                .unwrap();
4072
4073            assert_eq!(error.to_string(), "multiple devices use PCIe port 'custom'");
4074            mesh.shutdown().await;
4075        });
4076    }
4077
4078    /// The MANA devices keep their VPCI instance IDs from one start to the
4079    /// next, and VTL2's ID is the one its settings name.
4080    #[test]
4081    fn mana_vpci_instance_ids_are_stable() {
4082        DefaultPool::run_with(async |driver| {
4083            let temp_dir = tempfile::tempdir().unwrap();
4084            let igvm_path = temp_dir.path().join("guest.igvm");
4085            File::create(&igvm_path).unwrap();
4086            let igvm_options = format!("firmware={},personality=openhcl", igvm_path.display());
4087            let mesh = VmmMesh::new(&driver, true).unwrap();
4088            let opt = Options::try_parse_from([
4089                "openvmm",
4090                "--igvm",
4091                &igvm_options,
4092                "--hv",
4093                "--vtl2",
4094                "--no-alias-map",
4095                "--single-process",
4096                "--mana",
4097                "consomme",
4098                "--net",
4099                "uh:consomme",
4100            ])
4101            .unwrap();
4102
4103            let mut starts = Vec::new();
4104            for _ in 0..2 {
4105                let (config, resources) = vm_config_from_command_line(driver.clone(), &mesh, &opt)
4106                    .await
4107                    .unwrap();
4108                let id = |vtl| {
4109                    let ids: Vec<_> = config
4110                        .vpci_devices
4111                        .iter()
4112                        .filter(|device| device.vtl == vtl && device.resource.id() == "gdma")
4113                        .map(|device| device.instance_id)
4114                        .collect();
4115                    assert_eq!(ids.len(), 1, "{vtl:?}");
4116                    ids[0]
4117                };
4118                let (vtl0, vtl2) = (id(DeviceVtl::Vtl0), id(DeviceVtl::Vtl2));
4119                assert_ne!(vtl0, vtl2);
4120                let nics = resources
4121                    .vtl2_settings
4122                    .unwrap()
4123                    .dynamic
4124                    .unwrap()
4125                    .nic_devices;
4126                assert_eq!(nics.len(), 1);
4127                assert_eq!(nics[0].instance_id, vtl2.to_string());
4128                starts.push((vtl0, vtl2));
4129            }
4130            assert_eq!(starts[0], starts[1]);
4131            mesh.shutdown().await;
4132        });
4133    }
4134}