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