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