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