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 let Some(igvm) = &opt.igvm {
1353        let cli_args::UefiCli {
1354            firmware,
1355            debug: _,
1356            enable_memory_protections: _,
1357            force_dma_bounce: _,
1358            force_firmware_version,
1359            disable_frontpage: _,
1360            console: _,
1361            diagnostics: _,
1362            default_boot_always_attempt: _,
1363        } = uefi_options;
1364
1365        anyhow::ensure!(
1366            firmware.is_none(),
1367            "--uefi firmware is not supported with --igvm"
1368        );
1369        anyhow::ensure!(
1370            !force_firmware_version,
1371            "--uefi force_firmware_version is not supported with --igvm"
1372        );
1373        let file = fs_err::File::open(&igvm.firmware)
1374            .context("failed to open igvm file")?
1375            .into();
1376        let cmdline = opt.cmdline.join(" ");
1377        with_hv = match igvm.personality {
1378            IgvmPersonalityCli::Openhcl | IgvmPersonalityCli::Uefi => true,
1379            IgvmPersonalityCli::LinuxDirect => opt.hv,
1380        };
1381
1382        load_mode = LoadMode::Igvm {
1383            file,
1384            cmdline,
1385            vtl2_base_address: if opt.vtl2 {
1386                opt.igvm_vtl2_relocation_type
1387            } else {
1388                Vtl2BaseAddressType::File
1389            },
1390            com_serial: has_com3.then_some(UartId::Com(ComPort::Com3)),
1391            personality: match igvm.personality {
1392                IgvmPersonalityCli::Openhcl => IgvmPersonality::Openhcl,
1393                IgvmPersonalityCli::Uefi => IgvmPersonality::Uefi,
1394                IgvmPersonalityCli::LinuxDirect => IgvmPersonality::LinuxDirect,
1395            },
1396        };
1397
1398        // An IGVM launch carries no SMBIOS field of its own; the identity is
1399        // only delivered over the GET/GED channel, which is absent here. Reject
1400        // overrides that would otherwise be silently dropped.
1401        let smbios_requested = !opt.smbios.is_empty();
1402        let smbios_delivered_via_get = with_get && with_hv;
1403        if smbios_requested && !smbios_delivered_via_get {
1404            anyhow::bail!(
1405                "--smbios is not supported for IGVM launches without an OpenHCL GET channel"
1406            );
1407        }
1408    } else if opt.pcat {
1409        // Emit a nice error early instead of complaining about missing firmware.
1410        if arch != MachineArch::X86_64 {
1411            anyhow::bail!("pcat not supported on this architecture");
1412        }
1413        with_hv = true;
1414
1415        let firmware = openvmm_pcat_locator::find_pcat_bios(opt.pcat_firmware.as_deref())?;
1416        load_mode = LoadMode::Pcat {
1417            firmware,
1418            boot_order: opt
1419                .pcat_boot_order
1420                .map(|x| x.0)
1421                .unwrap_or(DEFAULT_PCAT_BOOT_ORDER),
1422            hibernation_enabled: opt.hibernation,
1423            smbios,
1424        };
1425    } else if let Some(uefi_options) = &uefi {
1426        use openvmm_defs::config::UefiConsoleMode;
1427
1428        let cli_args::UefiCli {
1429            firmware,
1430            debug,
1431            enable_memory_protections,
1432            force_dma_bounce,
1433            force_firmware_version,
1434            disable_frontpage,
1435            console,
1436            diagnostics: _,
1437            default_boot_always_attempt,
1438        } = uefi_options;
1439
1440        if opt.no_hv && cfg!(guest_arch = "x86_64") {
1441            anyhow::bail!("--no-hv is not supported on x86_64");
1442        }
1443
1444        with_hv = !opt.no_hv;
1445
1446        let default_firmware = cli_args::default_uefi_firmware();
1447        let firmware = fs_err::File::open(
1448            firmware
1449                .as_ref()
1450                .or(default_firmware.as_ref())
1451                .context("must provide uefi firmware when booting with uefi")?,
1452        )
1453        .context("failed to open uefi firmware")?;
1454
1455        // TODO: It would be better to default memory protections to on, but currently Linux does not boot via UEFI due to what
1456        //       appears to be a GRUB memory protection fault. Memory protections are therefore only enabled if configured.
1457        load_mode = LoadMode::Uefi {
1458            firmware: firmware.into(),
1459            enable_debugging: *debug,
1460            enable_memory_protections: *enable_memory_protections,
1461            disable_frontpage: *disable_frontpage,
1462            tpm_version,
1463            enable_battery: opt.battery,
1464            enable_serial: any_serial_configured,
1465            enable_vpci_boot: false,
1466            uefi_console_mode: console.map(|m| match m {
1467                UefiConsoleModeCli::Default => UefiConsoleMode::Default,
1468                UefiConsoleModeCli::Com1 => UefiConsoleMode::Com1,
1469                UefiConsoleModeCli::Com2 => UefiConsoleMode::Com2,
1470                UefiConsoleModeCli::None => UefiConsoleMode::None,
1471            }),
1472            default_boot_always_attempt: *default_boot_always_attempt,
1473            smbios,
1474            enable_vmbus: !opt.no_vmbus,
1475            force_dma_bounce: *force_dma_bounce,
1476            enable_hv: !opt.no_hv,
1477            hibernation_enabled: opt.hibernation,
1478            force_firmware_version: *force_firmware_version,
1479        };
1480    } else {
1481        // Linux Direct
1482        let mut cmdline = "panic=-1 debug".to_string();
1483
1484        with_hv = opt.hv;
1485        if with_hv && opt.pcie_root_complex.is_empty() {
1486            cmdline += " pci=off";
1487        }
1488
1489        if !console_str.is_empty() {
1490            let _ = write!(&mut cmdline, " console={}", console_str);
1491        }
1492
1493        if opt.gfx {
1494            cmdline += " console=tty";
1495        }
1496        for extra in &opt.cmdline {
1497            let _ = write!(&mut cmdline, " {}", extra);
1498        }
1499
1500        let kernel = fs_err::File::open(
1501            (opt.kernel.0)
1502                .as_ref()
1503                .context("must provide kernel when booting with linux direct")?,
1504        )
1505        .context("failed to open kernel")?;
1506        let initrd = (opt.initrd.0)
1507            .as_ref()
1508            .map(fs_err::File::open)
1509            .transpose()
1510            .context("failed to open initrd")?;
1511
1512        load_mode = LoadMode::Linux {
1513            kernel: kernel.into(),
1514            initrd: initrd.map(Into::into),
1515            cmdline,
1516            enable_serial: any_serial_configured,
1517            isolation: if matches!(opt.isolation, Some(cli_args::IsolationCli::Snp)) {
1518                openvmm_defs::config::LinuxIsolationConfig::Snp {
1519                    restricted_injection: opt.snp_restricted_injection,
1520                }
1521            } else {
1522                openvmm_defs::config::LinuxIsolationConfig::None
1523            },
1524            boot_mode: if opt.device_tree {
1525                openvmm_defs::config::LinuxDirectBootMode::DeviceTree
1526            } else {
1527                openvmm_defs::config::LinuxDirectBootMode::Acpi
1528            },
1529            smbios,
1530        };
1531    }
1532
1533    if supports_acpi_power_button(&load_mode) {
1534        let (send, recv) = mesh::channel();
1535        let irq = match arch {
1536            MachineArch::X86_64 => DEFAULT_ACPI_POWER_BUTTON_IRQ_X64,
1537            MachineArch::Aarch64 => DEFAULT_ACPI_POWER_BUTTON_SPI_AARCH64,
1538        };
1539        chipset = chipset.with_acpi_power_button(irq, recv);
1540        resources.acpi_power_button = Some(send);
1541    }
1542
1543    let layout_config = chipset.layout_config();
1544    let VmChipsetResult {
1545        chipset,
1546        mut chipset_devices,
1547        pci_chipset_devices,
1548        isa_dma_controller,
1549        capabilities,
1550    } = chipset
1551        .build()
1552        .context("failed to build chipset configuration")?;
1553
1554    let mut vmgs = Some(if let Some(vmgs) = &opt.vmgs {
1555        let encryption_policy = if opt.test_gsp_by_id {
1556            GuestStateEncryptionPolicy::GspById(true)
1557        } else {
1558            GuestStateEncryptionPolicy::None(true)
1559        };
1560        open_vmgs(&vmgs.kind, vmgs.provision, encryption_policy)
1561            .await
1562            .context("failed to open vmgs disk")?
1563    } else {
1564        VmgsResource::Ephemeral
1565    });
1566
1567    if with_get && with_hv {
1568        let has_vtl0_nvme = storage.has_vtl0_nvme();
1569        let vtl2_settings = vtl2_settings_proto::Vtl2Settings {
1570            version: vtl2_settings_proto::vtl2_settings_base::Version::V1.into(),
1571            fixed: Some(Default::default()),
1572            dynamic: Some(vtl2_settings_proto::Vtl2SettingsDynamic {
1573                storage_controllers: storage.build_openhcl_settings(opt.vmbus_redirect),
1574                nic_devices: underhill_nics,
1575            }),
1576            namespace_settings: Vec::default(),
1577        };
1578
1579        // Cache the VTL2 settings for later modification via the interactive console.
1580        resources.vtl2_settings = Some(vtl2_settings.clone());
1581
1582        let (send, guest_request_recv) = mesh::channel();
1583        resources.ged_rpc = Some(send);
1584
1585        let vmgs = vmgs.take().unwrap();
1586
1587        vmbus_devices.extend([
1588            (
1589                openhcl_vtl,
1590                get_resources::gel::GuestEmulationLogHandle.into_resource(),
1591            ),
1592            (
1593                openhcl_vtl,
1594                get_resources::ged::GuestEmulationDeviceHandle {
1595                    firmware: if opt.pcat {
1596                        get_resources::ged::GuestFirmwareConfig::Pcat {
1597                            boot_order: opt
1598                                .pcat_boot_order
1599                                .map_or(DEFAULT_PCAT_BOOT_ORDER, |x| x.0)
1600                                .map(|x| match x {
1601                                    openvmm_defs::config::PcatBootDevice::Floppy => {
1602                                        get_resources::ged::PcatBootDevice::Floppy
1603                                    }
1604                                    openvmm_defs::config::PcatBootDevice::HardDrive => {
1605                                        get_resources::ged::PcatBootDevice::HardDrive
1606                                    }
1607                                    openvmm_defs::config::PcatBootDevice::Optical => {
1608                                        get_resources::ged::PcatBootDevice::Optical
1609                                    }
1610                                    openvmm_defs::config::PcatBootDevice::Network => {
1611                                        get_resources::ged::PcatBootDevice::Network
1612                                    }
1613                                }),
1614                        }
1615                    } else {
1616                        use get_resources::ged::UefiConsoleMode;
1617
1618                        get_resources::ged::GuestFirmwareConfig::Uefi {
1619                            enable_vpci_boot: has_vtl0_nvme,
1620                            firmware_debug: uefi_options.debug,
1621                            enable_memory_protections: uefi_options.enable_memory_protections,
1622                            disable_frontpage: uefi_options.disable_frontpage,
1623                            console_mode: match uefi_options.console.unwrap_or(UefiConsoleModeCli::Default) {
1624                                UefiConsoleModeCli::Default => UefiConsoleMode::Default,
1625                                UefiConsoleModeCli::Com1 => UefiConsoleMode::COM1,
1626                                UefiConsoleModeCli::Com2 => UefiConsoleMode::COM2,
1627                                UefiConsoleModeCli::None => UefiConsoleMode::None,
1628                            },
1629                            default_boot_always_attempt: uefi_options.default_boot_always_attempt,
1630                        }
1631                    },
1632                    com1: with_vmbus_com1_serial,
1633                    com2: with_vmbus_com2_serial,
1634                    serial_tx_only: opt.serial_tx_only,
1635                    vtl2_settings: Some(prost::Message::encode_to_vec(&vtl2_settings)),
1636                    vmbus_redirection: opt.vmbus_redirect,
1637                    vmgs,
1638                    framebuffer: opt
1639                        .vtl2_gfx
1640                        .then(|| SharedFramebufferHandle.into_resource()),
1641                    guest_request_recv,
1642                    tpm_version: tpm_version.map(|v| match v {
1643                        TpmVersion::V138 => get_resources::ged::GedTpmVersion::V138,
1644                        TpmVersion::V185 => get_resources::ged::GedTpmVersion::V185,
1645                    }),
1646                    firmware_event_send: None,
1647                    ipmi_sel_event_send: None,
1648                    secure_boot_enabled: opt.secure_boot,
1649                    secure_boot_template: match opt.secure_boot_template {
1650                        Some(SecureBootTemplateCli::Windows) => {
1651                            get_resources::ged::GuestSecureBootTemplateType::MicrosoftWindows
1652                        },
1653                        Some(SecureBootTemplateCli::UefiCa) => {
1654                            get_resources::ged::GuestSecureBootTemplateType::MicrosoftUefiCertificateAuthority
1655                        }
1656                        None => {
1657                            get_resources::ged::GuestSecureBootTemplateType::None
1658                        },
1659                    },
1660                    enable_battery: opt.battery,
1661                    enable_ipmi: false,
1662                    enable_hibernation: opt.hibernation,
1663                    no_persistent_secrets: true,
1664                    igvm_attest_test_config: None,
1665                    test_gsp_by_id: opt.test_gsp_by_id,
1666                    efi_diagnostics_log_level: {
1667                        match uefi_options.diagnostics.unwrap_or_default() {
1668                            EfiDiagnosticsLogLevelCli::Default => get_resources::ged::EfiDiagnosticsLogLevelType::Default,
1669                            EfiDiagnosticsLogLevelCli::Info => get_resources::ged::EfiDiagnosticsLogLevelType::Info,
1670                            EfiDiagnosticsLogLevelCli::Full => get_resources::ged::EfiDiagnosticsLogLevelType::Full,
1671                        }
1672                    },
1673                    force_dma_bounce_enabled: uefi_options.force_dma_bounce,
1674                    smbios: ged_smbios,
1675                }
1676                .into_resource(),
1677            ),
1678        ]);
1679    }
1680
1681    if let Some(tpm_version) = tpm_version
1682        && !opt.vtl2
1683    {
1684        let register_layout = if cfg!(guest_arch = "x86_64") {
1685            TpmRegisterLayout::IoPort
1686        } else {
1687            TpmRegisterLayout::Mmio
1688        };
1689
1690        let ppi_store =
1691            non_volatile_store_resource(opt.vmgs.is_some(), vmgs_format::FileId::TPM_PPI);
1692        let nvram_store = non_volatile_store_resource(
1693            opt.vmgs.is_some(),
1694            tpm_vmgs::tpm_nvram_file_id(tpm_version),
1695        );
1696
1697        chipset_devices.push(ChipsetDeviceHandle {
1698            name: "tpm".to_string(),
1699            resource: chipset_device_worker_defs::RemoteChipsetDeviceHandle {
1700                device: TpmDeviceHandle {
1701                    version: tpm_version,
1702                    ppi_store,
1703                    nvram_store,
1704                    nvram_size: None,
1705                    refresh_tpm_seeds: false,
1706                    ak_cert_type: tpm_resources::TpmAkCertTypeResource::None,
1707                    register_layout,
1708                    guest_secret_key: None,
1709                    logger: None,
1710                    is_confidential_vm: false,
1711                    bios_guid,
1712                }
1713                .into_resource(),
1714                worker_host: mesh.make_host("tpm", None).await?,
1715            }
1716            .into_resource(),
1717        });
1718    }
1719
1720    let vga_firmware = if opt.pcat {
1721        Some(openvmm_pcat_locator::find_svga_bios(
1722            opt.vga_firmware.as_deref(),
1723        )?)
1724    } else {
1725        None
1726    };
1727
1728    if opt.gfx {
1729        // Channel for the video device to report dirty rectangles to the VNC worker.
1730        let (dirt_send, dirt_recv) = mesh::channel();
1731        resources.dirty_rect_recv = Some(dirt_recv);
1732
1733        vmbus_devices.extend([
1734            (
1735                DeviceVtl::Vtl0,
1736                SynthVideoHandle {
1737                    framebuffer: SharedFramebufferHandle.into_resource(),
1738                    dirt_send: Some(dirt_send),
1739                }
1740                .into_resource(),
1741            ),
1742            (
1743                DeviceVtl::Vtl0,
1744                SynthKeyboardHandle {
1745                    source: MultiplexedInputHandle {
1746                        // Save 0 for PS/2
1747                        elevation: 1,
1748                    }
1749                    .into_resource(),
1750                }
1751                .into_resource(),
1752            ),
1753            (
1754                DeviceVtl::Vtl0,
1755                SynthMouseHandle {
1756                    source: MultiplexedInputHandle {
1757                        // Save 0 for PS/2
1758                        elevation: 1,
1759                    }
1760                    .into_resource(),
1761                }
1762                .into_resource(),
1763            ),
1764        ]);
1765    }
1766
1767    let vsock_listener = |path: Option<&str>| -> anyhow::Result<_> {
1768        if let Some(path) = path {
1769            cleanup_socket(path.as_ref());
1770            let listener = unix_socket::UnixListener::bind(path)
1771                .with_context(|| format!("failed to bind to hybrid vsock path: {}", path))?;
1772            Ok(Some(listener))
1773        } else {
1774            Ok(None)
1775        }
1776    };
1777
1778    let vtl0_vsock_listener = vsock_listener(opt.vmbus_vsock_path.as_deref())?;
1779    let vtl2_vsock_listener = vsock_listener(opt.vmbus_vtl2_vsock_path.as_deref())?;
1780
1781    if let Some(path) = &opt.openhcl_dump_path {
1782        let (resource, task) = spawn_dump_handler(&spawner, path.clone(), None);
1783        task.detach();
1784        vmbus_devices.push((openhcl_vtl, resource));
1785    }
1786
1787    #[cfg(guest_arch = "aarch64")]
1788    let topology_arch = openvmm_defs::config::ArchTopologyConfig::Aarch64(
1789        openvmm_defs::config::Aarch64TopologyConfig {
1790            // TODO: allow this to be configured from the command line
1791            gic_config: None,
1792            pmu_gsiv: openvmm_defs::config::PmuGsivConfig::Platform,
1793            gic_msi: match opt.gic_msi {
1794                cli_args::GicMsiCli::Auto => openvmm_defs::config::GicMsiConfig::Auto,
1795                cli_args::GicMsiCli::Its => openvmm_defs::config::GicMsiConfig::Its,
1796                cli_args::GicMsiCli::V2m => {
1797                    openvmm_defs::config::GicMsiConfig::V2m { spi_count: None }
1798                }
1799            },
1800        },
1801    );
1802    #[cfg(guest_arch = "x86_64")]
1803    let topology_arch =
1804        openvmm_defs::config::ArchTopologyConfig::X86(openvmm_defs::config::X86TopologyConfig {
1805            apic_id_offset: opt.apic_id_offset,
1806            x2apic: opt.x2apic,
1807        });
1808
1809    let with_isolation = if let Some(isolation) = &opt.isolation {
1810        match isolation {
1811            cli_args::IsolationCli::Vbs => {
1812                // TODO: For now, VBS isolation is only supported with VTL2.
1813                if !opt.vtl2 {
1814                    anyhow::bail!("VBS isolation is only currently supported with vtl2");
1815                }
1816
1817                // TODO: Alias map support is not yet implemented with isolation.
1818                if !opt.no_alias_map {
1819                    anyhow::bail!("alias map not supported with isolation");
1820                }
1821
1822                Some(openvmm_defs::config::IsolationType::Vbs)
1823            }
1824            cli_args::IsolationCli::Snp => Some(openvmm_defs::config::IsolationType::Snp {
1825                // SNP host data is currently only configurable via TTRPC.
1826                host_data: None,
1827            }),
1828        }
1829    } else {
1830        None
1831    };
1832
1833    if with_hv && !opt.no_vmbus {
1834        let (shutdown_send, shutdown_recv) = mesh::channel();
1835        resources.shutdown_ic = Some(shutdown_send);
1836        let (kvp_send, kvp_recv) = mesh::channel();
1837        resources.kvp_ic = Some(kvp_send);
1838        vmbus_devices.extend(
1839            [
1840                hyperv_ic_resources::shutdown::ShutdownIcHandle {
1841                    recv: shutdown_recv,
1842                }
1843                .into_resource(),
1844                hyperv_ic_resources::kvp::KvpIcHandle { recv: kvp_recv }.into_resource(),
1845                hyperv_ic_resources::timesync::TimesyncIcHandle.into_resource(),
1846            ]
1847            .map(|r| (DeviceVtl::Vtl0, r)),
1848        );
1849    }
1850
1851    if let Some(hive_path) = &opt.imc {
1852        let file = fs_err::File::open(hive_path).context("failed to open imc hive")?;
1853        vmbus_devices.push((
1854            DeviceVtl::Vtl0,
1855            vmbfs_resources::VmbfsImcDeviceHandle { file: file.into() }.into_resource(),
1856        ));
1857    }
1858
1859    let mut virtio_devices = Vec::new();
1860    let mut add_virtio_device =
1861        |bus, resource: Resource<VirtioDeviceHandle>, pcie_devices: &mut Vec<_>| match bus {
1862            VirtioBusCli::Auto => {
1863                // Use VPCI when possible (currently only on Windows and macOS due
1864                // to KVM backend limitations).
1865                if with_hv && (cfg!(windows) || cfg!(target_os = "macos")) {
1866                    vpci_devices.push(VpciDeviceConfig {
1867                        vtl: DeviceVtl::Vtl0,
1868                        instance_id: Guid::new_random(),
1869                        resource: VirtioPciDeviceHandle(resource).into_resource(),
1870                        vnode: None,
1871                    });
1872                } else {
1873                    virtio_devices.push((VirtioBus::Pci, resource));
1874                }
1875            }
1876            VirtioBusCli::Mmio => virtio_devices.push((VirtioBus::Mmio, resource)),
1877            VirtioBusCli::Pci => virtio_devices.push((VirtioBus::Pci, resource)),
1878            VirtioBusCli::Pcie(port_name) => pcie_devices.push(PcieDeviceConfig {
1879                port_name,
1880                resource: VirtioPciDeviceHandle(resource).into_resource(),
1881            }),
1882            VirtioBusCli::Vpci => vpci_devices.push(VpciDeviceConfig {
1883                vtl: DeviceVtl::Vtl0,
1884                instance_id: Guid::new_random(),
1885                resource: VirtioPciDeviceHandle(resource).into_resource(),
1886                vnode: None,
1887            }),
1888        };
1889
1890    for cli_cfg in &opt.virtio_net {
1891        if cli_cfg.underhill {
1892            anyhow::bail!("use --net uh:[...] to add underhill NICs")
1893        }
1894        let vport = parse_endpoint(cli_cfg, &mut nic_index, &mut resources)?;
1895        let resource = virtio_resources::net::VirtioNetHandle {
1896            max_queues: vport.max_queues,
1897            enable_rx_gso: vport.enable_rx_gso,
1898            mac_address: vport.mac_address,
1899            endpoint: vport.endpoint,
1900        }
1901        .into_resource();
1902        if let Some(pcie_port) = &cli_cfg.pcie_port {
1903            pcie_devices.push(PcieDeviceConfig {
1904                port_name: pcie_port.clone(),
1905                resource: VirtioPciDeviceHandle(resource).into_resource(),
1906            });
1907        } else {
1908            add_virtio_device(VirtioBusCli::Auto, resource, &mut pcie_devices);
1909        }
1910    }
1911
1912    for args in &opt.virtio_fs {
1913        let resource: Resource<VirtioDeviceHandle> = virtio_resources::fs::VirtioFsHandle {
1914            tag: args.tag.clone(),
1915            fs: virtio_resources::fs::VirtioFsBackend::HostFs {
1916                root_path: args.path.clone(),
1917                mount_options: args.options.clone(),
1918            },
1919        }
1920        .into_resource();
1921        if let Some(pcie_port) = &args.pcie_port {
1922            pcie_devices.push(PcieDeviceConfig {
1923                port_name: pcie_port.clone(),
1924                resource: VirtioPciDeviceHandle(resource).into_resource(),
1925            });
1926        } else {
1927            add_virtio_device(opt.virtio_fs_bus.clone(), resource, &mut pcie_devices);
1928        }
1929    }
1930
1931    for args in &opt.virtio_fs_shmem {
1932        let resource: Resource<VirtioDeviceHandle> = virtio_resources::fs::VirtioFsHandle {
1933            tag: args.tag.clone(),
1934            fs: virtio_resources::fs::VirtioFsBackend::SectionFs {
1935                root_path: args.path.clone(),
1936            },
1937        }
1938        .into_resource();
1939        if let Some(pcie_port) = &args.pcie_port {
1940            pcie_devices.push(PcieDeviceConfig {
1941                port_name: pcie_port.clone(),
1942                resource: VirtioPciDeviceHandle(resource).into_resource(),
1943            });
1944        } else {
1945            add_virtio_device(opt.virtio_fs_bus.clone(), resource, &mut pcie_devices);
1946        }
1947    }
1948
1949    for args in &opt.virtio_9p {
1950        let resource: Resource<VirtioDeviceHandle> = virtio_resources::p9::VirtioPlan9Handle {
1951            tag: args.tag.clone(),
1952            root_path: args.path.clone(),
1953            debug: opt.virtio_9p_debug,
1954        }
1955        .into_resource();
1956        if let Some(pcie_port) = &args.pcie_port {
1957            pcie_devices.push(PcieDeviceConfig {
1958                port_name: pcie_port.clone(),
1959                resource: VirtioPciDeviceHandle(resource).into_resource(),
1960            });
1961        } else {
1962            add_virtio_device(VirtioBusCli::Auto, resource, &mut pcie_devices);
1963        }
1964    }
1965
1966    if let Some(pmem_args) = &opt.virtio_pmem {
1967        let resource: Resource<VirtioDeviceHandle> = virtio_resources::pmem::VirtioPmemHandle {
1968            path: pmem_args.path.clone(),
1969            read_only: false,
1970        }
1971        .into_resource();
1972        if let Some(pcie_port) = &pmem_args.pcie_port {
1973            pcie_devices.push(PcieDeviceConfig {
1974                port_name: pcie_port.clone(),
1975                resource: VirtioPciDeviceHandle(resource).into_resource(),
1976            });
1977        } else {
1978            add_virtio_device(VirtioBusCli::Auto, resource, &mut pcie_devices);
1979        }
1980    }
1981
1982    if opt.virtio_rng {
1983        let resource: Resource<VirtioDeviceHandle> =
1984            virtio_resources::rng::VirtioRngHandle.into_resource();
1985        if let Some(pcie_port) = &opt.virtio_rng_pcie_port {
1986            pcie_devices.push(PcieDeviceConfig {
1987                port_name: pcie_port.clone(),
1988                resource: VirtioPciDeviceHandle(resource).into_resource(),
1989            });
1990        } else {
1991            add_virtio_device(opt.virtio_rng_bus.clone(), resource, &mut pcie_devices);
1992        }
1993    }
1994
1995    if let Some(rtc) = &opt.virtio_rtc {
1996        let resource: Resource<VirtioDeviceHandle> =
1997            virtio_resources::rtc::VirtioRtcHandle.into_resource();
1998        add_virtio_device(rtc.bus.clone(), resource, &mut pcie_devices);
1999    }
2000
2001    if let Some(backend) = virtio_console_backend {
2002        let resource: Resource<VirtioDeviceHandle> =
2003            virtio_resources::console::VirtioConsoleHandle { backend }.into_resource();
2004        if let Some(pcie_port) = &opt.virtio_console_pcie_port {
2005            pcie_devices.push(PcieDeviceConfig {
2006                port_name: pcie_port.clone(),
2007                resource: VirtioPciDeviceHandle(resource).into_resource(),
2008            });
2009        } else {
2010            add_virtio_device(VirtioBusCli::Auto, resource, &mut pcie_devices);
2011        }
2012    }
2013
2014    // Handle --vhost-user arguments.
2015    #[cfg(target_os = "linux")]
2016    for vhost_cli in &opt.vhost_user {
2017        let stream =
2018            unix_socket::UnixStream::connect(&vhost_cli.socket_path).with_context(|| {
2019                format!(
2020                    "failed to connect to vhost-user socket: {}",
2021                    vhost_cli.socket_path
2022                )
2023            })?;
2024
2025        use crate::cli_args::VhostUserDeviceTypeCli;
2026        let resource: Resource<VirtioDeviceHandle> = match vhost_cli.device_type {
2027            VhostUserDeviceTypeCli::Fs {
2028                ref tag,
2029                num_queues,
2030                queue_size,
2031            } => virtio_resources::vhost_user::VhostUserFsHandle {
2032                socket: stream.into(),
2033                tag: tag.clone(),
2034                num_queues,
2035                queue_size,
2036            }
2037            .into_resource(),
2038            VhostUserDeviceTypeCli::Blk {
2039                num_queues,
2040                queue_size,
2041            } => virtio_resources::vhost_user::VhostUserBlkHandle {
2042                socket: stream.into(),
2043                num_queues,
2044                queue_size,
2045            }
2046            .into_resource(),
2047            VhostUserDeviceTypeCli::Other {
2048                device_id,
2049                ref queue_sizes,
2050            } => virtio_resources::vhost_user::VhostUserGenericHandle {
2051                socket: stream.into(),
2052                device_id,
2053                queue_sizes: queue_sizes.clone(),
2054            }
2055            .into_resource(),
2056        };
2057        if let Some(pcie_port) = &vhost_cli.pcie_port {
2058            pcie_devices.push(PcieDeviceConfig {
2059                port_name: pcie_port.clone(),
2060                resource: VirtioPciDeviceHandle(resource).into_resource(),
2061            });
2062        } else {
2063            add_virtio_device(VirtioBusCli::Auto, resource, &mut pcie_devices);
2064        }
2065    }
2066
2067    let virtio_vsock_bus = opt.virtio_vsock_bus.clone().unwrap_or(VirtioBusCli::Auto);
2068
2069    if let Some(vsock_path) = &opt.virtio_vsock_path {
2070        let listener = vsock_listener(Some(vsock_path))?.unwrap();
2071        let resource: Resource<VirtioDeviceHandle> = virtio_resources::vsock::VirtioVsockHandle {
2072            // The guest CID does not matter since the UDS relay does not use it. It just needs
2073            // to be some non-reserved value for the guest to use.
2074            guest_cid: 0x3,
2075            base_path: vsock_path.clone(),
2076            listener,
2077        }
2078        .into_resource();
2079        add_virtio_device(virtio_vsock_bus.clone(), resource, &mut pcie_devices);
2080    }
2081
2082    #[cfg(target_os = "linux")]
2083    if let Some(guest_cid) = opt.virtio_vsock_vhost_cid {
2084        let vhost = std::fs::OpenOptions::new()
2085            .read(true)
2086            .write(true)
2087            .open("/dev/vhost-vsock")
2088            .context("failed to open /dev/vhost-vsock")?
2089            .into();
2090        let resource =
2091            virtio_resources::vsock::VirtioVsockVhostHandle { vhost, guest_cid }.into_resource();
2092        add_virtio_device(virtio_vsock_bus, resource, &mut pcie_devices);
2093    }
2094
2095    #[cfg(target_os = "linux")]
2096    pcie_devices.extend(vfio_pcie_devices);
2097
2098    let mut cfg = Config {
2099        chipset,
2100        load_mode,
2101        floppy_disks,
2102        pcie_root_complexes,
2103        pcie_ecam_below_4gb: opt.pcie_ecam_below_4gb,
2104        #[cfg(target_os = "linux")]
2105        pcie_devices,
2106        #[cfg(not(target_os = "linux"))]
2107        pcie_devices,
2108        pcie_switches,
2109        pcie_generic_initiators,
2110        vpci_devices,
2111        ide_disks: Vec::new(),
2112        numa: {
2113            if let Some(ref nodes) = opt.numa {
2114                // --numa mode: each --numa flag defines a node.
2115                NumaTopology {
2116                    nodes: nodes
2117                        .iter()
2118                        .map(|n| {
2119                            let vps = match &n.vps {
2120                                Some(vps) if vps.0.is_empty() => VpAssignment::Empty,
2121                                Some(vps) => {
2122                                    VpAssignment::Explicit(vps.expand_below(opt.processors)?)
2123                                }
2124                                None => VpAssignment::FromTopology,
2125                            };
2126                            Ok(NumaNode {
2127                                mem: Some(MemoryConfig {
2128                                    mem_size: n
2129                                        .memory
2130                                        .size
2131                                        .expect("NUMA memory size was validated")
2132                                        .0,
2133                                    prefetch_memory: n.memory.prefetch,
2134                                    private_memory: n.memory.shared == Some(false),
2135                                    transparent_hugepages: n
2136                                        .memory
2137                                        .transparent_hugepages
2138                                        .unwrap_or(!n.memory.hugepages),
2139                                    hugepages: n.memory.hugepages,
2140                                    hugepage_size: n.memory.hugepage_size.map(|m| m.0),
2141                                    host_numa_node: n.host_numa_node,
2142                                }),
2143                                vps,
2144                            })
2145                        })
2146                        .collect::<anyhow::Result<Vec<_>>>()?,
2147                    distances: opt
2148                        .numa_distance
2149                        .as_deref()
2150                        .unwrap_or(&[])
2151                        .iter()
2152                        .map(|d| NumaDistance {
2153                            src: d.src,
2154                            dst: d.dst,
2155                            distance: d.distance,
2156                        })
2157                        .collect(),
2158                }
2159            } else {
2160                // Single-node default from --memory.
2161                NumaTopology {
2162                    nodes: vec![NumaNode {
2163                        mem: Some(MemoryConfig {
2164                            mem_size: opt.memory_size(),
2165                            prefetch_memory: opt.prefetch_memory(),
2166                            private_memory: opt.private_memory(),
2167                            transparent_hugepages: opt.transparent_hugepages(),
2168                            hugepages: opt.memory.hugepages,
2169                            hugepage_size: opt.memory.hugepage_size.map(|m| m.0),
2170                            host_numa_node: None,
2171                        }),
2172                        vps: VpAssignment::FromTopology,
2173                    }],
2174                    distances: vec![],
2175                }
2176            }
2177        },
2178        processor_topology: ProcessorTopologyConfig {
2179            proc_count: opt.processors,
2180            vps_per_socket: opt.vps_per_socket,
2181            enable_smt: match opt.smt {
2182                cli_args::SmtConfigCli::Auto => None,
2183                cli_args::SmtConfigCli::Force => Some(true),
2184                cli_args::SmtConfigCli::Off => Some(false),
2185            },
2186            arch: Some(topology_arch),
2187        },
2188        hypervisor: HypervisorConfig {
2189            with_hv,
2190            with_vtl2: opt.vtl2.then_some(Vtl2Config {
2191                vtl0_alias_map: !opt.no_alias_map,
2192                late_map_vtl0_memory: match opt.late_map_vtl0_policy {
2193                    cli_args::Vtl0LateMapPolicyCli::Off => None,
2194                    cli_args::Vtl0LateMapPolicyCli::Log => Some(LateMapVtl0MemoryPolicy::Log),
2195                    cli_args::Vtl0LateMapPolicyCli::Halt => Some(LateMapVtl0MemoryPolicy::Halt),
2196                    cli_args::Vtl0LateMapPolicyCli::Exception => {
2197                        Some(LateMapVtl0MemoryPolicy::InjectException)
2198                    }
2199                },
2200            }),
2201            with_isolation,
2202            nested_virt: opt.nested_virt,
2203        },
2204        #[cfg(windows)]
2205        kernel_vmnics,
2206        input: mesh::Receiver::new(),
2207        framebuffer,
2208        vga_firmware,
2209        vtl2_gfx: opt.vtl2_gfx,
2210        virtio_devices,
2211        vmbus: (with_hv && !opt.no_vmbus).then_some(VmbusConfig {
2212            vsock_listener: vtl0_vsock_listener,
2213            vsock_path: opt.vmbus_vsock_path.clone(),
2214            vtl2_redirect: opt.vmbus_redirect,
2215            vmbus_max_version: opt.vmbus_max_version,
2216            #[cfg(windows)]
2217            vmbusproxy_handle,
2218        }),
2219        vtl2_vmbus: (with_hv && opt.vtl2).then_some(VmbusConfig {
2220            vsock_listener: vtl2_vsock_listener,
2221            vsock_path: opt.vmbus_vtl2_vsock_path.clone(),
2222            ..Default::default()
2223        }),
2224        vmbus_devices,
2225        chipset_devices,
2226        pci_chipset_devices,
2227        isa_dma_controller,
2228        chipset_capabilities: capabilities,
2229        layout: layout_config,
2230        #[cfg(windows)]
2231        vpci_resources,
2232        vmgs,
2233        firmware_event_send: None,
2234        debugger_rpc: None,
2235        rtc_delta_milliseconds: 0,
2236    };
2237
2238    storage.build_config(&mut cfg, &mut resources, opt.scsi_sub_channels)?;
2239    let mut pcie_port_names = HashSet::new();
2240    for device in &cfg.pcie_devices {
2241        anyhow::ensure!(
2242            pcie_port_names.insert(&device.port_name),
2243            "multiple devices use PCIe port '{}'",
2244            device.port_name
2245        );
2246    }
2247    resources.serial_driver = Some(serial_driver);
2248    validate_snp_config(&cfg)?;
2249    Ok((cfg, resources))
2250}
2251
2252fn validate_snp_config(cfg: &Config) -> anyhow::Result<()> {
2253    if !matches!(
2254        cfg.hypervisor.with_isolation,
2255        Some(openvmm_defs::config::IsolationType::Snp { .. })
2256    ) {
2257        return Ok(());
2258    }
2259
2260    if !matches!(
2261        cfg.load_mode,
2262        LoadMode::Linux { .. } | LoadMode::Igvm { .. }
2263    ) {
2264        anyhow::bail!("SNP isolation currently only supports Linux direct or IGVM boot");
2265    }
2266    if cfg.hypervisor.with_vtl2.is_some() {
2267        anyhow::bail!("SNP isolation currently does not support VTL2");
2268    }
2269    if cfg.vmbus.is_some() || cfg.vtl2_vmbus.is_some() || !cfg.vmbus_devices.is_empty() {
2270        anyhow::bail!("SNP isolation currently does not support VMBus devices");
2271    }
2272
2273    let only_supported_chipset_devices = cfg.chipset_devices.iter().all(|device| {
2274        matches!(
2275            device.resource.id(),
2276            "serial_16550"
2277                | "pic"
2278                | "pit"
2279                | "generic-ioapic"
2280                | "hyperv_power_management"
2281                | "missing-dev"
2282        )
2283    });
2284    let only_virtio_pcie_devices = cfg
2285        .pcie_devices
2286        .iter()
2287        .all(|device| device.resource.id() == "virtio");
2288    if !cfg.floppy_disks.is_empty()
2289        || !cfg.ide_disks.is_empty()
2290        || !cfg.virtio_devices.is_empty()
2291        || !only_virtio_pcie_devices
2292        || !cfg.vpci_devices.is_empty()
2293        || !only_supported_chipset_devices
2294        || !cfg.pci_chipset_devices.is_empty()
2295    {
2296        anyhow::bail!("SNP isolation currently only supports virtio devices");
2297    }
2298    if cfg.framebuffer.is_some() || cfg.vga_firmware.is_some() || cfg.debugger_rpc.is_some() {
2299        anyhow::bail!("SNP isolation currently does not support this VM configuration");
2300    }
2301
2302    Ok(())
2303}
2304
2305/// Gets the terminal to use for externally launched console windows.
2306pub(crate) fn openvmm_terminal_app() -> Option<PathBuf> {
2307    std::env::var_os("OPENVMM_TERM")
2308        .or_else(|| std::env::var_os("HVLITE_TERM"))
2309        .map(Into::into)
2310}
2311
2312// Tries to remove `path` if it is confirmed to be a Unix socket.
2313fn cleanup_socket(path: &Path) {
2314    #[cfg(windows)]
2315    let is_socket = pal::windows::fs::is_unix_socket(path).unwrap_or(false);
2316    #[cfg(not(windows))]
2317    let is_socket = path
2318        .metadata()
2319        .is_ok_and(|meta| std::os::unix::fs::FileTypeExt::is_socket(&meta.file_type()));
2320
2321    if is_socket {
2322        let _ = std::fs::remove_file(path);
2323    }
2324}
2325
2326#[cfg(windows)]
2327fn new_switch_port(
2328    switch_id: Option<&str>,
2329) -> anyhow::Result<(
2330    openvmm_defs::config::SwitchPortId,
2331    vmswitch::kernel::SwitchPort,
2332)> {
2333    let id = vmswitch::kernel::SwitchPortId {
2334        switch: match switch_id {
2335            Some(s) => s.parse().context("invalid switch id")?,
2336            None => vmswitch::hcn::DEFAULT_SWITCH,
2337        },
2338        port: Guid::new_random(),
2339    };
2340    let _ = vmswitch::hcn::Network::open(&id.switch)
2341        .with_context(|| format!("could not find switch {}", id.switch))?;
2342
2343    let port = vmswitch::kernel::SwitchPort::new(&id).context("failed to create switch port")?;
2344
2345    let id = openvmm_defs::config::SwitchPortId {
2346        switch: id.switch,
2347        port: id.port,
2348    };
2349    Ok((id, port))
2350}
2351
2352fn parse_endpoint(
2353    cli_cfg: &NicConfigCli,
2354    index: &mut usize,
2355    resources: &mut VmResources,
2356) -> anyhow::Result<NicConfig> {
2357    let _ = resources;
2358    let endpoint = match &cli_cfg.endpoint {
2359        EndpointConfigCli::Consomme { cidr, host_fwd } => {
2360            let ports = host_fwd
2361                .iter()
2362                .map(|fwd| {
2363                    use net_backend_resources::consomme::HostPortProtocol;
2364                    net_backend_resources::consomme::HostPortConfig {
2365                        protocol: match fwd.protocol {
2366                            cli_args::HostPortProtocolCli::Tcp => HostPortProtocol::Tcp,
2367                            cli_args::HostPortProtocolCli::Udp => HostPortProtocol::Udp,
2368                        },
2369                        host_address: fwd
2370                            .host_address
2371                            .map(net_backend_resources::consomme::HostIpAddress::from),
2372                        host_port: net_backend_resources::consomme::HostPort::Fixed(fwd.host_port),
2373                        guest_port: fwd.guest_port,
2374                    }
2375                })
2376                .collect();
2377            // Only wire the bind/unbind RPC channel to the first consomme
2378            // endpoint. Additional consomme NICs work normally but cannot be
2379            // targeted by runtime bind/unbind commands.
2380            let recv = if resources.consomme_rpc.is_none() {
2381                let (send, recv) = mesh::channel();
2382                resources.consomme_rpc = Some(send);
2383                Some(recv)
2384            } else {
2385                None
2386            };
2387            net_backend_resources::consomme::ConsommeHandle {
2388                cidr: cidr.clone(),
2389                params: Default::default(),
2390                ports,
2391                internal_dns: true,
2392                recv,
2393            }
2394            .into_resource()
2395        }
2396        EndpointConfigCli::None => net_backend_resources::null::NullHandle.into_resource(),
2397        EndpointConfigCli::Dio { id } => {
2398            #[cfg(windows)]
2399            {
2400                let (port_id, port) = new_switch_port(id.as_deref())?;
2401                resources.switch_ports.push(port);
2402                net_backend_resources::dio::WindowsDirectIoHandle {
2403                    switch_port_id: net_backend_resources::dio::SwitchPortId {
2404                        switch: port_id.switch,
2405                        port: port_id.port,
2406                    },
2407                }
2408                .into_resource()
2409            }
2410
2411            #[cfg(not(windows))]
2412            {
2413                let _ = id;
2414                bail!("cannot use dio on non-windows platforms")
2415            }
2416        }
2417        EndpointConfigCli::Tap { name } => {
2418            #[cfg(target_os = "linux")]
2419            {
2420                let fd = net_tap::tap::open_tap(name)
2421                    .with_context(|| format!("failed to open TAP device '{name}'"))?;
2422                net_backend_resources::tap::TapHandle { fd }.into_resource()
2423            }
2424
2425            #[cfg(not(target_os = "linux"))]
2426            {
2427                let _ = name;
2428                bail!("TAP backend is only supported on Linux")
2429            }
2430        }
2431    };
2432
2433    let mac_address = cli_cfg.mac_address.unwrap_or_else(|| {
2434        let mut mac_address = [0x00, 0x15, 0x5D, 0, 0, 0];
2435        getrandom::fill(&mut mac_address[3..]).expect("rng failure");
2436        mac_address.into()
2437    });
2438
2439    // Pick a fixed instance ID based on the index.
2440    const BASE_INSTANCE_ID: Guid = guid::guid!("00000000-da43-11ed-936a-00155d6db52f");
2441    let instance_id = Guid {
2442        data1: *index as u32,
2443        ..BASE_INSTANCE_ID
2444    };
2445    *index += 1;
2446
2447    Ok(NicConfig {
2448        vtl: cli_cfg.vtl,
2449        instance_id,
2450        endpoint,
2451        mac_address,
2452        max_queues: cli_cfg.max_queues,
2453        enable_rx_gso: cli_cfg.enable_rx_gso,
2454        pcie_port: cli_cfg.pcie_port.clone(),
2455    })
2456}
2457
2458#[derive(Debug)]
2459struct NicConfig {
2460    vtl: DeviceVtl,
2461    instance_id: Guid,
2462    mac_address: MacAddress,
2463    endpoint: Resource<NetEndpointHandleKind>,
2464    max_queues: Option<u16>,
2465    enable_rx_gso: bool,
2466    pcie_port: Option<String>,
2467}
2468
2469impl NicConfig {
2470    fn into_netvsp_handle(self) -> (DeviceVtl, Resource<VmbusDeviceHandleKind>) {
2471        (
2472            self.vtl,
2473            netvsp_resources::NetvspHandle {
2474                instance_id: self.instance_id,
2475                mac_address: self.mac_address,
2476                endpoint: self.endpoint,
2477                max_queues: self.max_queues,
2478            }
2479            .into_resource(),
2480        )
2481    }
2482}
2483
2484fn non_volatile_store_resource(
2485    with_vmgs: bool,
2486    file_id: vmgs_format::FileId,
2487) -> Resource<NonVolatileStoreKind> {
2488    if with_vmgs {
2489        VmgsFileHandle::new(file_id, true).into_resource()
2490    } else {
2491        EphemeralNonVolatileStoreHandle.into_resource()
2492    }
2493}
2494
2495async fn open_vmgs(
2496    kind: &DiskCliKind,
2497    provision: ProvisionCondition,
2498    encryption_policy: GuestStateEncryptionPolicy,
2499) -> anyhow::Result<VmgsResource> {
2500    let disk = VmgsDisk {
2501        disk: disk_open(kind, false).await?,
2502        encryption_policy,
2503    };
2504    Ok(match provision {
2505        ProvisionCondition::OnEmpty => VmgsResource::Disk(disk),
2506        ProvisionCondition::OnFailure => VmgsResource::ReprovisionOnFailure(disk),
2507        ProvisionCondition::Single => VmgsResource::ReprovisionSingle(disk),
2508    })
2509}
2510
2511enum LayerOrDisk {
2512    Layer(DiskLayerDescription),
2513    Disk(Resource<DiskHandleKind>),
2514}
2515
2516async fn disk_open(
2517    disk_cli: &DiskCliKind,
2518    read_only: bool,
2519) -> anyhow::Result<Resource<DiskHandleKind>> {
2520    let mut layers = Vec::new();
2521    disk_open_inner(disk_cli, read_only, &mut layers).await?;
2522    if layers.len() == 1 && matches!(layers[0], LayerOrDisk::Disk(_)) {
2523        let LayerOrDisk::Disk(disk) = layers.pop().unwrap() else {
2524            unreachable!()
2525        };
2526        Ok(disk)
2527    } else {
2528        Ok(Resource::new(disk_backend_resources::LayeredDiskHandle {
2529            layers: layers
2530                .into_iter()
2531                .map(|layer| match layer {
2532                    LayerOrDisk::Layer(layer) => layer,
2533                    LayerOrDisk::Disk(disk) => DiskLayerDescription {
2534                        layer: DiskLayerHandle(disk).into_resource(),
2535                        read_cache: false,
2536                        write_through: false,
2537                    },
2538                })
2539                .collect(),
2540        }))
2541    }
2542}
2543
2544fn disk_open_inner<'a>(
2545    disk_cli: &'a DiskCliKind,
2546    read_only: bool,
2547    layers: &'a mut Vec<LayerOrDisk>,
2548) -> futures::future::BoxFuture<'a, anyhow::Result<()>> {
2549    Box::pin(async move {
2550        fn layer<T: IntoResource<DiskLayerHandleKind>>(layer: T) -> LayerOrDisk {
2551            LayerOrDisk::Layer(layer.into_resource().into())
2552        }
2553        fn disk<T: IntoResource<DiskHandleKind>>(disk: T) -> LayerOrDisk {
2554            LayerOrDisk::Disk(disk.into_resource())
2555        }
2556        match disk_cli {
2557            &DiskCliKind::Memory(len) => {
2558                layers.push(layer(RamDiskLayerHandle {
2559                    len: Some(len),
2560                    sector_size: None,
2561                }));
2562            }
2563            DiskCliKind::File {
2564                path,
2565                create_with_len,
2566                direct,
2567            } => layers.push(LayerOrDisk::Disk(if let Some(size) = create_with_len {
2568                create_disk_type(
2569                    path,
2570                    *size,
2571                    OpenDiskOptions {
2572                        read_only: false,
2573                        direct: *direct,
2574                    },
2575                )
2576                .with_context(|| format!("failed to create {}", path.display()))?
2577            } else {
2578                open_disk_type(
2579                    path,
2580                    OpenDiskOptions {
2581                        read_only,
2582                        direct: *direct,
2583                    },
2584                )
2585                .await
2586                .with_context(|| format!("failed to open {}", path.display()))?
2587            })),
2588            DiskCliKind::Blob { kind, url } => {
2589                layers.push(disk(disk_backend_resources::BlobDiskHandle {
2590                    url: url.to_owned(),
2591                    format: match kind {
2592                        cli_args::BlobKind::Flat => disk_backend_resources::BlobDiskFormat::Flat,
2593                        cli_args::BlobKind::Vhd1 => {
2594                            disk_backend_resources::BlobDiskFormat::FixedVhd1
2595                        }
2596                    },
2597                }))
2598            }
2599            DiskCliKind::MemoryDiff(inner) => {
2600                layers.push(layer(RamDiskLayerHandle {
2601                    len: None,
2602                    sector_size: None,
2603                }));
2604                disk_open_inner(inner, true, layers).await?;
2605            }
2606            DiskCliKind::PersistentReservationsWrapper(inner) => {
2607                layers.push(disk(disk_backend_resources::DiskWithReservationsHandle(
2608                    disk_open(inner, read_only).await?,
2609                )))
2610            }
2611            DiskCliKind::DelayDiskWrapper {
2612                delay_ms,
2613                disk: inner,
2614            } => layers.push(disk(DelayDiskHandle {
2615                delay: CellUpdater::new(Duration::from_millis(*delay_ms)).cell(),
2616                disk: disk_open(inner, read_only).await?,
2617            })),
2618            DiskCliKind::Crypt {
2619                disk: inner,
2620                cipher,
2621                key_file,
2622            } => layers.push(disk(disk_crypt_resources::DiskCryptHandle {
2623                disk: disk_open(inner, read_only).await?,
2624                cipher: match cipher {
2625                    cli_args::DiskCipher::XtsAes256 => disk_crypt_resources::Cipher::XtsAes256,
2626                },
2627                key: fs_err::read(key_file).context("failed to read key file")?,
2628            })),
2629            DiskCliKind::Sqlite {
2630                path,
2631                create_with_len,
2632            } => {
2633                // FUTURE: this code should be responsible for opening
2634                // file-handle(s) itself, and passing them into sqlite via a custom
2635                // vfs. For now though - simply check if the file exists or not, and
2636                // perform early validation of filesystem-level create options.
2637                match (create_with_len.is_some(), path.exists()) {
2638                    (true, true) => anyhow::bail!(
2639                        "cannot create new sqlite disk at {} - file already exists",
2640                        path.display()
2641                    ),
2642                    (false, false) => anyhow::bail!(
2643                        "cannot open sqlite disk at {} - file not found",
2644                        path.display()
2645                    ),
2646                    _ => {}
2647                }
2648
2649                layers.push(layer(SqliteDiskLayerHandle {
2650                    dbhd_path: path.display().to_string(),
2651                    format_dbhd: create_with_len.map(|len| {
2652                        disk_backend_resources::layer::SqliteDiskLayerFormatParams {
2653                            logically_read_only: false,
2654                            len: Some(len),
2655                        }
2656                    }),
2657                }));
2658            }
2659            DiskCliKind::SqliteDiff { path, create, disk } => {
2660                // FUTURE: this code should be responsible for opening
2661                // file-handle(s) itself, and passing them into sqlite via a custom
2662                // vfs. For now though - simply check if the file exists or not, and
2663                // perform early validation of filesystem-level create options.
2664                match (create, path.exists()) {
2665                    (true, true) => anyhow::bail!(
2666                        "cannot create new sqlite disk at {} - file already exists",
2667                        path.display()
2668                    ),
2669                    (false, false) => anyhow::bail!(
2670                        "cannot open sqlite disk at {} - file not found",
2671                        path.display()
2672                    ),
2673                    _ => {}
2674                }
2675
2676                layers.push(layer(SqliteDiskLayerHandle {
2677                    dbhd_path: path.display().to_string(),
2678                    format_dbhd: create.then_some(
2679                        disk_backend_resources::layer::SqliteDiskLayerFormatParams {
2680                            logically_read_only: false,
2681                            len: None,
2682                        },
2683                    ),
2684                }));
2685                disk_open_inner(disk, true, layers).await?;
2686            }
2687            DiskCliKind::AutoCacheSqlite {
2688                cache_path,
2689                key,
2690                disk,
2691            } => {
2692                layers.push(LayerOrDisk::Layer(DiskLayerDescription {
2693                    read_cache: true,
2694                    write_through: false,
2695                    layer: SqliteAutoCacheDiskLayerHandle {
2696                        cache_path: cache_path.clone(),
2697                        cache_key: key.clone(),
2698                    }
2699                    .into_resource(),
2700                }));
2701                disk_open_inner(disk, read_only, layers).await?;
2702            }
2703        }
2704        Ok(())
2705    })
2706}
2707
2708/// Get the system page size.
2709pub(crate) fn system_page_size() -> u32 {
2710    sparse_mmap::SparseMapping::page_size() as u32
2711}
2712
2713/// The guest architecture string, derived from the compile-time `guest_arch` cfg.
2714pub(crate) const GUEST_ARCH: &str = if cfg!(guest_arch = "x86_64") {
2715    "x86_64"
2716} else {
2717    "aarch64"
2718};
2719
2720/// Open a snapshot directory and validate it against the current VM config.
2721/// Returns the shared memory fd (from memory.bin) and the saved device state.
2722fn prepare_snapshot_restore(
2723    snapshot_dir: &Path,
2724    opt: &Options,
2725) -> anyhow::Result<(
2726    openvmm_defs::worker::SharedMemoryFd,
2727    mesh::payload::message::ProtobufMessage,
2728)> {
2729    let (manifest, state_bytes) = openvmm_helpers::snapshot::read_snapshot(snapshot_dir)?;
2730
2731    // Validate manifest against current VM config.
2732    openvmm_helpers::snapshot::validate_manifest(
2733        &manifest,
2734        GUEST_ARCH,
2735        opt.memory_size(),
2736        opt.processors,
2737        system_page_size(),
2738    )?;
2739
2740    // Open memory.bin (existing file, no create, no resize).
2741    let memory_file = fs_err::OpenOptions::new()
2742        .read(true)
2743        .write(true)
2744        .open(snapshot_dir.join("memory.bin"))?;
2745
2746    // Validate file size matches expected memory size.
2747    let file_size = memory_file.metadata()?.len();
2748    if file_size != manifest.memory_size_bytes {
2749        anyhow::bail!(
2750            "memory.bin size ({file_size} bytes) doesn't match manifest ({} bytes)",
2751            manifest.memory_size_bytes,
2752        );
2753    }
2754
2755    let shared_memory_fd =
2756        openvmm_helpers::shared_memory::file_to_shared_memory_fd(memory_file.into())?;
2757
2758    // Reconstruct ProtobufMessage from the saved state bytes.
2759    // The save side wrote mesh::payload::encode(ProtobufMessage), so we decode
2760    // back to ProtobufMessage.
2761    let state_msg: mesh::payload::message::ProtobufMessage = mesh::payload::decode(&state_bytes)
2762        .context("failed to decode saved state from snapshot")?;
2763
2764    Ok((shared_memory_fd, state_msg))
2765}
2766
2767fn do_main(pidfile_guard: &mut Option<pidfile::Pidfile>) -> anyhow::Result<i32> {
2768    #[cfg(windows)]
2769    pal::windows::disable_hard_error_dialog();
2770
2771    let _tracing_guard = tracing_init::enable_tracing()?;
2772
2773    // Try to run as a worker host.
2774    // On success the worker runs to completion and then exits the process (does
2775    // not return). Any worker host setup errors are return and bubbled up.
2776    meshworker::run_vmm_mesh_host()?;
2777
2778    let opt = cli_args::parse_options();
2779
2780    // Print the version number. This comes after argument parsing to not interfere
2781    // with --version and --help.
2782    tracing::info!(version = openvmm_build_info::get().version());
2783
2784    if let Some(path) = &opt.write_saved_state_proto {
2785        mesh::payload::protofile::DescriptorWriter::new(vmcore::save_restore::saved_state_roots())
2786            .write_to_path(path)
2787            .context("failed to write protobuf descriptors")?;
2788        return Ok(0);
2789    }
2790
2791    if let Some(ref path) = opt.pidfile {
2792        *pidfile_guard = Some(pidfile::Pidfile::new(path).context("failed to create pidfile")?);
2793    }
2794
2795    if let Some(path) = opt.relay_console_path {
2796        let console_title = opt.relay_console_title.unwrap_or_default();
2797        return console_relay::relay_console(&path, console_title.as_str()).map(|()| 0);
2798    }
2799
2800    #[cfg(any(feature = "grpc", feature = "ttrpc"))]
2801    {
2802        let rpc = opt
2803            .rpc
2804            .as_ref()
2805            .map(|rpc| {
2806                let transport = match rpc.transport {
2807                    cli_args::RpcTransportCli::Auto => ttrpc::RpcTransport::Auto,
2808                    cli_args::RpcTransportCli::Ttrpc => ttrpc::RpcTransport::Ttrpc,
2809                    cli_args::RpcTransportCli::Grpc => ttrpc::RpcTransport::Grpc,
2810                };
2811                (rpc.path.as_path(), transport)
2812            })
2813            .or_else(|| {
2814                opt.ttrpc
2815                    .as_deref()
2816                    .map(|p| (p, ttrpc::RpcTransport::Ttrpc))
2817            })
2818            .or_else(|| opt.grpc.as_deref().map(|p| (p, ttrpc::RpcTransport::Grpc)));
2819
2820        if let Some((path, transport)) = rpc {
2821            return block_on(async {
2822                let _ = std::fs::remove_file(path);
2823                let listener =
2824                    unix_socket::UnixListener::bind(path).context("failed to bind to socket")?;
2825
2826                // This is a local launch
2827                let (exit_code_send, exit_code_recv) = mesh::oneshot();
2828                let mut handle =
2829                    mesh_worker::launch_local_worker::<ttrpc::TtrpcWorker>(ttrpc::Parameters {
2830                        listener,
2831                        transport,
2832                        exit_code: exit_code_send,
2833                    })
2834                    .await?;
2835
2836                tracing::info!(%transport, path = %path.display(), "listening");
2837
2838                // Signal the parent process that the server is ready.
2839                pal::close_stdout().context("failed to close stdout")?;
2840
2841                handle.join().await?;
2842
2843                exit_code_recv
2844                    .await
2845                    .context("RPC worker did not report an exit code")
2846            });
2847        }
2848    }
2849
2850    DefaultPool::run_with(async |driver| run_control(&driver, opt).await)
2851}
2852
2853fn new_hvsock_service_id(port: u32) -> Guid {
2854    // This GUID is an embedding of the AF_VSOCK port into an
2855    // AF_HYPERV service ID.
2856    Guid {
2857        data1: port,
2858        .."00000000-facb-11e6-bd58-64006a7986d3".parse().unwrap()
2859    }
2860}
2861
2862async fn run_control(driver: &DefaultDriver, opt: Options) -> anyhow::Result<i32> {
2863    let mut mesh = Some(VmmMesh::new(&driver, opt.single_process)?);
2864    let result = run_control_inner(driver, &mut mesh, opt).await;
2865    // If setup failed before the mesh was handed to the controller, shut it
2866    // down so the child host process exits cleanly without noisy logs.
2867    if let Some(mesh) = mesh {
2868        mesh.shutdown().await;
2869    }
2870    result
2871}
2872
2873async fn run_control_inner(
2874    driver: &DefaultDriver,
2875    mesh_slot: &mut Option<VmmMesh>,
2876    opt: Options,
2877) -> anyhow::Result<i32> {
2878    let mesh = mesh_slot.as_ref().unwrap();
2879    let (mut vm_config, mut resources) = vm_config_from_command_line(driver, mesh, &opt).await?;
2880
2881    let mut vnc_worker = None;
2882    if opt.gfx || opt.vnc.vnc {
2883        // Parse the listen address. Try as a full SocketAddr (host:port) first;
2884        // fall back to a bare IP, using the configured port.
2885        let addr: std::net::SocketAddr = if let Ok(sa) =
2886            opt.vnc.vnc_listen.parse::<std::net::SocketAddr>()
2887        {
2888            sa
2889        } else {
2890            let ip: std::net::IpAddr = opt.vnc.vnc_listen.parse().with_context(|| {
2891                format!(
2892                    "invalid VNC listen address: {} (expected IP address or socket address like [::1]:5900)",
2893                    opt.vnc.vnc_listen
2894                )
2895            })?;
2896            std::net::SocketAddr::new(ip, opt.vnc.vnc_port)
2897        };
2898
2899        let socket = socket2::Socket::new(
2900            if addr.is_ipv6() {
2901                socket2::Domain::IPV6
2902            } else {
2903                socket2::Domain::IPV4
2904            },
2905            socket2::Type::STREAM,
2906            None,
2907        )
2908        .with_context(|| format!("creating VNC socket for {}", addr))?;
2909
2910        if addr.is_ipv6() {
2911            if let Err(e) = socket.set_only_v6(false) {
2912                tracing::warn!(
2913                    error = %e,
2914                    "failed to enable dual-stack on IPv6 VNC socket, IPv4 clients may not be able to connect"
2915                );
2916            }
2917        }
2918        socket.set_reuse_address(true)?;
2919        socket
2920            .bind(&addr.into())
2921            .with_context(|| format!("binding VNC socket to {}", addr))?;
2922        socket
2923            .listen(128)
2924            .with_context(|| format!("listening on VNC socket {}", addr))?;
2925        let listener: TcpListener = socket.into();
2926
2927        if !addr.ip().is_loopback() {
2928            tracing::warn!(
2929                address = %addr,
2930                "VNC server listening on non-localhost address without authentication"
2931            );
2932        }
2933
2934        let input_send = vm_config.input.sender();
2935        let framebuffer = resources
2936            .framebuffer_access
2937            .take()
2938            .expect("synth video enabled");
2939
2940        let vnc_host = mesh
2941            .make_host("vnc", None)
2942            .await
2943            .context("spawning vnc process failed")?;
2944
2945        vnc_worker = Some(
2946            vnc_host
2947                .launch_worker(
2948                    vnc_worker_defs::VNC_WORKER_TCP,
2949                    VncParameters {
2950                        listener,
2951                        framebuffer,
2952                        input_send,
2953                        dirty_recv: resources.dirty_rect_recv.take(),
2954                        max_clients: opt.vnc.vnc_max_clients,
2955                        evict_oldest: opt.vnc.vnc_evict_oldest,
2956                    },
2957                )
2958                .await?,
2959        )
2960    }
2961
2962    // spin up the debug worker
2963    let gdb_worker = if let Some(port) = opt.gdb {
2964        let listener = TcpListener::bind(format!("127.0.0.1:{}", port))
2965            .with_context(|| format!("binding to gdb port {}", port))?;
2966
2967        let (req_tx, req_rx) = mesh::channel();
2968        vm_config.debugger_rpc = Some(req_rx);
2969
2970        let gdb_host = mesh
2971            .make_host("gdb", None)
2972            .await
2973            .context("spawning gdbstub process failed")?;
2974
2975        Some(
2976            gdb_host
2977                .launch_worker(
2978                    debug_worker_defs::DEBUGGER_WORKER,
2979                    debug_worker_defs::DebuggerParameters {
2980                        listener,
2981                        req_chan: req_tx,
2982                        vp_count: vm_config.processor_topology.proc_count,
2983                        target_arch: if cfg!(guest_arch = "x86_64") {
2984                            debug_worker_defs::TargetArch::X86_64
2985                        } else {
2986                            debug_worker_defs::TargetArch::Aarch64
2987                        },
2988                    },
2989                )
2990                .await
2991                .context("failed to launch gdbstub worker")?,
2992        )
2993    } else {
2994        None
2995    };
2996
2997    // spin up the VM
2998    let (vm_rpc, rpc_recv) = mesh::channel();
2999    let (notify_send, notify_recv) = mesh::channel();
3000    let vm_worker = {
3001        let vm_host = mesh.make_host("vm", opt.log_file.clone()).await?;
3002
3003        let (shared_memory, saved_state) = if let Some(snapshot_dir) = &opt.restore_snapshot {
3004            let (fd, state_msg) = prepare_snapshot_restore(snapshot_dir, &opt)?;
3005            (Some(fd), Some(state_msg))
3006        } else {
3007            let shared_memory = opt
3008                .memory_backing_file()
3009                .map(|path| {
3010                    openvmm_helpers::shared_memory::open_memory_backing_file(
3011                        path,
3012                        opt.memory_size(),
3013                    )
3014                })
3015                .transpose()?;
3016            (shared_memory, None)
3017        };
3018
3019        let params = VmWorkerParameters {
3020            hypervisor: match &opt.hypervisor {
3021                Some(name) => openvmm_helpers::hypervisor::hypervisor_resource(name)?,
3022                None => openvmm_helpers::hypervisor::choose_hypervisor()?,
3023            },
3024            cfg: vm_config,
3025            saved_state,
3026            shared_memory,
3027            rpc: rpc_recv,
3028            notify: notify_send,
3029        };
3030        vm_host
3031            .launch_worker(VM_WORKER, params)
3032            .await
3033            .context("failed to launch vm worker")?
3034    };
3035
3036    if opt.restore_snapshot.is_some() {
3037        tracing::info!("restoring VM from snapshot");
3038    }
3039
3040    if !opt.paused {
3041        vm_rpc.call(VmRpc::Resume, ()).await?;
3042    }
3043
3044    let paravisor_diag = Arc::new(diag_client::DiagClient::from_dialer(
3045        driver.clone(),
3046        DiagDialer {
3047            driver: driver.clone(),
3048            vm_rpc: vm_rpc.clone(),
3049            openhcl_vtl: if opt.vtl2 {
3050                DeviceVtl::Vtl2
3051            } else {
3052                DeviceVtl::Vtl0
3053            },
3054        },
3055    ));
3056
3057    let diag_inspector = DiagInspector::new(driver.clone(), paravisor_diag.clone());
3058
3059    // Create channels between the REPL and VmController.
3060    let (vm_controller_send, vm_controller_recv) = mesh::channel();
3061    let (vm_controller_event_send, vm_controller_event_recv) = mesh::channel();
3062
3063    let has_vtl2 = resources.vtl2_settings.is_some();
3064    let serial_driver = resources
3065        .serial_driver
3066        .take()
3067        .expect("serial driver must outlive serial resources");
3068
3069    // Build the VmController with exclusive resources.
3070    let controller = vm_controller::VmController {
3071        mesh: mesh_slot.take().unwrap(),
3072        vm_worker,
3073        vnc_worker,
3074        gdb_worker,
3075        diag_inspector: Some(diag_inspector),
3076        vtl2_settings: resources.vtl2_settings,
3077        ged_rpc: resources.ged_rpc.clone(),
3078        vm_rpc: vm_rpc.clone(),
3079        paravisor_diag: Some(paravisor_diag),
3080        igvm_path: opt.igvm.as_ref().map(|igvm| igvm.firmware.clone()),
3081        memory_backing_file: opt.memory_backing_file().cloned(),
3082        memory: opt.memory_size(),
3083        processors: opt.processors,
3084        log_file: opt.log_file.clone(),
3085        crash_dump_path: opt.crash_dump_path.clone(),
3086        guest_power_actions: vm_controller::GuestPowerActions {
3087            shutdown: opt.guest_shutdown_action,
3088            reset: opt.guest_reset_action,
3089            crash: opt.guest_crash_action,
3090            watchdog: opt.guest_watchdog_action,
3091        },
3092    };
3093
3094    // Spawn the VmController as a task.
3095    let controller_task = driver.spawn(
3096        "vm-controller",
3097        controller.run(vm_controller_recv, vm_controller_event_send, notify_recv),
3098    );
3099
3100    // Run the REPL with shareable resources.
3101    let repl_result = repl::run_repl(
3102        driver,
3103        repl::ReplResources {
3104            vm_rpc,
3105            vm_controller: vm_controller_send,
3106            vm_controller_events: vm_controller_event_recv,
3107            scsi_rpc: resources.scsi_rpc,
3108            nvme_vtl2_rpc: resources.nvme_vtl2_rpc,
3109            consomme_rpc: resources.consomme_rpc,
3110            shutdown_ic: resources.shutdown_ic,
3111            acpi_power_button: resources.acpi_power_button,
3112            kvp_ic: resources.kvp_ic,
3113            console_in: resources.console_in,
3114            has_vtl2,
3115        },
3116    )
3117    .await;
3118
3119    // Wait for the controller task to finish (it stops the VM worker and
3120    // shuts down the mesh).
3121    controller_task.await;
3122    drop(serial_driver);
3123
3124    // run_repl returns the exit status: the code the guest drove via an opt-in
3125    // exit (VmControllerEvent::ExitRequested), or 0 when the VM stopped normally.
3126    repl_result
3127}
3128
3129struct DiagDialer {
3130    driver: DefaultDriver,
3131    vm_rpc: mesh::Sender<VmRpc>,
3132    openhcl_vtl: DeviceVtl,
3133}
3134
3135impl mesh_rpc::client::Dial for DiagDialer {
3136    type Stream = PolledSocket<unix_socket::UnixStream>;
3137
3138    async fn dial(&mut self) -> io::Result<Self::Stream> {
3139        let service_id = new_hvsock_service_id(1);
3140        let socket = self
3141            .vm_rpc
3142            .call_failable(
3143                VmRpc::ConnectHvsock,
3144                (
3145                    CancelContext::new().with_timeout(Duration::from_secs(2)),
3146                    service_id,
3147                    self.openhcl_vtl,
3148                ),
3149            )
3150            .await
3151            .map_err(io::Error::other)?;
3152
3153        PolledSocket::new(&self.driver, socket)
3154    }
3155}
3156
3157/// An object that implements [`InspectMut`] by sending an inspect request over
3158/// TTRPC to the guest (typically the paravisor running in VTL2), then stitching
3159/// the response back into the inspect tree.
3160///
3161/// This also caches the TTRPC connection to the guest so that only the first
3162/// inspect request has to wait for the connection to be established.
3163pub(crate) struct DiagInspector(DiagInspectorInner);
3164
3165enum DiagInspectorInner {
3166    NotStarted(DefaultDriver, Arc<diag_client::DiagClient>),
3167    Started {
3168        send: mesh::Sender<inspect::Deferred>,
3169        _task: Task<()>,
3170    },
3171    Invalid,
3172}
3173
3174impl DiagInspector {
3175    pub fn new(driver: DefaultDriver, diag_client: Arc<diag_client::DiagClient>) -> Self {
3176        Self(DiagInspectorInner::NotStarted(driver, diag_client))
3177    }
3178
3179    fn start(&mut self) -> &mesh::Sender<inspect::Deferred> {
3180        loop {
3181            match self.0 {
3182                DiagInspectorInner::NotStarted { .. } => {
3183                    let DiagInspectorInner::NotStarted(driver, client) =
3184                        std::mem::replace(&mut self.0, DiagInspectorInner::Invalid)
3185                    else {
3186                        unreachable!()
3187                    };
3188                    let (send, recv) = mesh::channel();
3189                    let task = driver.clone().spawn("diag-inspect", async move {
3190                        Self::run(&client, recv).await
3191                    });
3192
3193                    self.0 = DiagInspectorInner::Started { send, _task: task };
3194                }
3195                DiagInspectorInner::Started { ref send, .. } => break send,
3196                DiagInspectorInner::Invalid => unreachable!(),
3197            }
3198        }
3199    }
3200
3201    async fn run(
3202        diag_client: &diag_client::DiagClient,
3203        mut recv: mesh::Receiver<inspect::Deferred>,
3204    ) {
3205        while let Some(deferred) = recv.next().await {
3206            let info = deferred.external_request();
3207            let result = match info.request_type {
3208                inspect::ExternalRequestType::Inspect { depth } => {
3209                    if depth == 0 {
3210                        Ok(inspect::Node::Unevaluated)
3211                    } else {
3212                        // TODO: Support taking timeouts from the command line
3213                        diag_client
3214                            .inspect(info.path, Some(depth - 1), Some(Duration::from_secs(1)))
3215                            .await
3216                    }
3217                }
3218                inspect::ExternalRequestType::Update { value } => {
3219                    (diag_client.update(info.path, value).await).map(inspect::Node::Value)
3220                }
3221            };
3222            deferred.complete_external(
3223                result.unwrap_or_else(|err| {
3224                    inspect::Node::Failed(inspect::Error::Mesh(format!("{err:#}")))
3225                }),
3226                inspect::SensitivityLevel::Unspecified,
3227            )
3228        }
3229    }
3230}
3231
3232impl InspectMut for DiagInspector {
3233    fn inspect_mut(&mut self, req: inspect::Request<'_>) {
3234        self.start().send(req.defer());
3235    }
3236}
3237
3238#[cfg(test)]
3239mod tests {
3240    use super::*;
3241    use clap::Parser;
3242    use std::fs::File;
3243    use test_with_tracing::test;
3244    use vm_resource::ResourceId;
3245
3246    /// The same boot flags give the same ACPI power button with and without
3247    /// `--restore-snapshot`.
3248    #[test]
3249    fn restore_builds_the_acpi_power_button_of_its_boot_command_line() {
3250        DefaultPool::run_with(async |driver| {
3251            let temp_dir = tempfile::tempdir().unwrap();
3252            let file = |name: &str| {
3253                let path = temp_dir.path().join(name);
3254                File::create(&path).unwrap();
3255                path.to_str().unwrap().to_owned()
3256            };
3257            let kernel = file("kernel");
3258            let initrd = file("initrd");
3259            let uefi = format!("--uefi=firmware={}", file("firmware"));
3260            // The config build does not read the snapshot directory.
3261            let snapshot = temp_dir.path().join("snapshot");
3262            let linux = ["--kernel", kernel.as_str(), "--initrd", initrd.as_str()];
3263
3264            for (boot, has_button) in [
3265                (linux.to_vec(), true),
3266                ([&linux[..], &["--device-tree"]].concat(), false),
3267                (vec![uefi.as_str()], true),
3268            ] {
3269                for restore in [false, true] {
3270                    let mut args = vec!["openvmm", "--single-process"];
3271                    args.extend(&boot);
3272                    if restore {
3273                        args.extend(["--restore-snapshot", snapshot.to_str().unwrap()]);
3274                    }
3275                    let opt = Options::try_parse_from(&args).unwrap();
3276                    let mesh = VmmMesh::new(&driver, true).unwrap();
3277                    let (config, _) = vm_config_from_command_line(driver.clone(), &mesh, &opt)
3278                        .await
3279                        .unwrap();
3280                    mesh.shutdown().await;
3281
3282                    let built = config
3283                        .chipset_devices
3284                        .iter()
3285                        .any(|device| device.name == "acpi-power-button");
3286                    assert_eq!(built, has_button, "{args:?}");
3287                }
3288            }
3289        });
3290    }
3291
3292    #[test]
3293    fn selects_non_volatile_store_backing() {
3294        for file_id in [
3295            vmgs_format::FileId::BIOS_NVRAM,
3296            vmgs_format::FileId::TPM_PPI,
3297            tpm_vmgs::tpm_nvram_file_id(TpmVersion::V138),
3298            tpm_vmgs::tpm_nvram_file_id(TpmVersion::V185),
3299        ] {
3300            assert_eq!(
3301                non_volatile_store_resource(true, file_id).id(),
3302                <VmgsFileHandle as ResourceId<NonVolatileStoreKind>>::ID
3303            );
3304            assert_eq!(
3305                non_volatile_store_resource(false, file_id).id(),
3306                <EphemeralNonVolatileStoreHandle as ResourceId<NonVolatileStoreKind>>::ID
3307            );
3308        }
3309    }
3310
3311    #[test]
3312    fn opens_vmgs_with_provisioning_and_encryption_policy() {
3313        block_on(async {
3314            for provision in [
3315                ProvisionCondition::OnEmpty,
3316                ProvisionCondition::OnFailure,
3317                ProvisionCondition::Single,
3318            ] {
3319                for encryption_policy in [
3320                    GuestStateEncryptionPolicy::None(true),
3321                    GuestStateEncryptionPolicy::GspById(true),
3322                ] {
3323                    let vmgs = open_vmgs(
3324                        &DiskCliKind::Memory(vmgs_format::VMGS_DEFAULT_CAPACITY),
3325                        provision,
3326                        encryption_policy,
3327                    )
3328                    .await
3329                    .unwrap();
3330                    let disk = match (provision, vmgs) {
3331                        (ProvisionCondition::OnEmpty, VmgsResource::Disk(disk))
3332                        | (
3333                            ProvisionCondition::OnFailure,
3334                            VmgsResource::ReprovisionOnFailure(disk),
3335                        )
3336                        | (ProvisionCondition::Single, VmgsResource::ReprovisionSingle(disk)) => {
3337                            disk
3338                        }
3339                        _ => panic!("incorrect VMGS provisioning"),
3340                    };
3341                    assert!(matches!(
3342                        (encryption_policy, disk.encryption_policy),
3343                        (
3344                            GuestStateEncryptionPolicy::None(true),
3345                            GuestStateEncryptionPolicy::None(true)
3346                        ) | (
3347                            GuestStateEncryptionPolicy::GspById(true),
3348                            GuestStateEncryptionPolicy::GspById(true)
3349                        )
3350                    ));
3351                }
3352            }
3353        });
3354    }
3355
3356    #[test]
3357    fn maps_igvm_personalities_to_chipsets() {
3358        for (args, expected) in [
3359            (
3360                vec!["openvmm", "--igvm", "firmware=guest.igvm,personality=uefi"],
3361                BaseChipsetType::HypervGen2Uefi,
3362            ),
3363            (
3364                vec![
3365                    "openvmm",
3366                    "--igvm",
3367                    "firmware=guest.igvm,personality=linux-direct",
3368                ],
3369                BaseChipsetType::UnenlightenedLinuxDirect,
3370            ),
3371            (
3372                vec![
3373                    "openvmm",
3374                    "--igvm",
3375                    "firmware=guest.igvm,personality=linux-direct",
3376                    "--hv",
3377                ],
3378                BaseChipsetType::HyperVGen2LinuxDirect,
3379            ),
3380            (
3381                vec![
3382                    "openvmm",
3383                    "--igvm",
3384                    "firmware=guest.igvm,personality=linux-direct",
3385                    "--isolation",
3386                    "snp",
3387                ],
3388                BaseChipsetType::EnlightenedLinuxDirect,
3389            ),
3390            (
3391                vec![
3392                    "openvmm",
3393                    "--igvm",
3394                    "firmware=guest.igvm,personality=openhcl",
3395                    "--hv",
3396                    "--vtl2",
3397                ],
3398                BaseChipsetType::HclHost,
3399            ),
3400        ] {
3401            let opt = Options::try_parse_from(args).unwrap();
3402            opt.validate_igvm_options().unwrap();
3403            assert!(
3404                std::mem::discriminant(&base_chipset_type(&opt))
3405                    == std::mem::discriminant(&expected)
3406            );
3407        }
3408    }
3409
3410    #[test]
3411    fn builds_openhcl_igvm_config_without_host_uefi() {
3412        DefaultPool::run_with(async |driver| {
3413            let temp_dir = tempfile::tempdir().unwrap();
3414            let igvm_path = temp_dir.path().join("guest.igvm");
3415            File::create(&igvm_path).unwrap();
3416            let igvm_options = format!("firmware={},personality=openhcl", igvm_path.display());
3417            let mesh = VmmMesh::new(&driver, true).unwrap();
3418
3419            for (extra, expected_alias, expected_policy) in [
3420                (vec![], true, Some(LateMapVtl0MemoryPolicy::Halt)),
3421                (
3422                    vec!["--uefi", "console=com1,disable_frontpage"],
3423                    true,
3424                    Some(LateMapVtl0MemoryPolicy::Halt),
3425                ),
3426                (
3427                    vec!["--net", "uh:consomme", "--no-alias-map"],
3428                    false,
3429                    Some(LateMapVtl0MemoryPolicy::Halt),
3430                ),
3431                (
3432                    vec!["--isolation", "vbs", "--no-alias-map"],
3433                    false,
3434                    Some(LateMapVtl0MemoryPolicy::Halt),
3435                ),
3436                (
3437                    vec!["--no-alias-map", "--late-map-vtl0-policy", "exception"],
3438                    false,
3439                    Some(LateMapVtl0MemoryPolicy::InjectException),
3440                ),
3441                (
3442                    vec!["--late-map-vtl0-policy", "log"],
3443                    true,
3444                    Some(LateMapVtl0MemoryPolicy::Log),
3445                ),
3446                (
3447                    vec!["--igvm-vtl2-relocation-type", "vtl2=filesize"],
3448                    true,
3449                    Some(LateMapVtl0MemoryPolicy::Halt),
3450                ),
3451                (
3452                    vec![
3453                        "--igvm-vtl2-relocation-type",
3454                        "vtl2=filesize",
3455                        "--late-map-vtl0-policy",
3456                        "off",
3457                    ],
3458                    true,
3459                    None,
3460                ),
3461            ] {
3462                let mut args = vec![
3463                    "openvmm",
3464                    "--igvm",
3465                    &igvm_options,
3466                    "--hv",
3467                    "--vtl2",
3468                    "--single-process",
3469                ];
3470                args.extend(extra);
3471                let opt = Options::try_parse_from(args).unwrap();
3472                let (config, resources) = vm_config_from_command_line(driver.clone(), &mesh, &opt)
3473                    .await
3474                    .unwrap();
3475
3476                assert!(matches!(config.load_mode, LoadMode::Igvm { .. }));
3477                assert!(config.hypervisor.with_hv);
3478                let vtl2 = config.hypervisor.with_vtl2.as_ref().unwrap();
3479                assert_eq!(vtl2.vtl0_alias_map, expected_alias);
3480                assert_eq!(vtl2.late_map_vtl0_memory, expected_policy);
3481                assert!(config.vmbus.is_some());
3482                assert!(config.vtl2_vmbus.is_some());
3483                assert!(resources.ged_rpc.is_some());
3484                assert!(resources.acpi_power_button.is_none());
3485                for id in ["ged", "gel"] {
3486                    assert!(
3487                        config.vmbus_devices.iter().any(|(vtl, resource)| {
3488                            *vtl == DeviceVtl::Vtl2 && resource.id() == id
3489                        })
3490                    );
3491                }
3492                assert!(
3493                    config
3494                        .chipset_devices
3495                        .iter()
3496                        .all(|device| { device.resource.id() != "hyperv_firmware_uefi" })
3497                );
3498            }
3499            for (extra, expected_error) in [
3500                (
3501                    ["--net", "uh:consomme"],
3502                    "must specify --no-alias-map to offer NICs to VTL2",
3503                ),
3504                (
3505                    ["--isolation", "vbs"],
3506                    "alias map not supported with isolation",
3507                ),
3508            ] {
3509                let mut args = vec![
3510                    "openvmm",
3511                    "--igvm",
3512                    &igvm_options,
3513                    "--hv",
3514                    "--vtl2",
3515                    "--single-process",
3516                ];
3517                args.extend(extra);
3518                let opt = Options::try_parse_from(args).unwrap();
3519                let err = vm_config_from_command_line(driver.clone(), &mesh, &opt)
3520                    .await
3521                    .err()
3522                    .unwrap();
3523                assert_eq!(err.to_string(), expected_error);
3524            }
3525            mesh.shutdown().await;
3526        });
3527    }
3528
3529    #[test]
3530    fn maps_virtio_vsock_to_named_pcie_port() {
3531        DefaultPool::run_with(async |driver| {
3532            let temp_dir = tempfile::tempdir().unwrap();
3533            let kernel_path = temp_dir.path().join("kernel");
3534            File::create(&kernel_path).unwrap();
3535            let initrd_path = temp_dir.path().join("initrd");
3536            File::create(&initrd_path).unwrap();
3537            let socket_path = temp_dir.path().join("vsock");
3538            let opt = Options::try_parse_from([
3539                "openvmm",
3540                "--kernel",
3541                kernel_path.to_str().unwrap(),
3542                "--initrd",
3543                initrd_path.to_str().unwrap(),
3544                "--virtio-vsock-path",
3545                socket_path.to_str().unwrap(),
3546                "--virtio-vsock-bus",
3547                "pcie:custom",
3548                "--single-process",
3549            ])
3550            .unwrap();
3551            let mesh = VmmMesh::new(&driver, true).unwrap();
3552
3553            let (config, _resources) = vm_config_from_command_line(driver, &mesh, &opt)
3554                .await
3555                .unwrap();
3556
3557            assert_eq!(config.pcie_devices.len(), 1);
3558            assert_eq!(config.pcie_devices[0].port_name, "custom");
3559            mesh.shutdown().await;
3560        });
3561    }
3562
3563    #[test]
3564    fn maps_virtio_fs_and_rng_to_named_pcie_ports() {
3565        DefaultPool::run_with(async |driver| {
3566            let temp_dir = tempfile::tempdir().unwrap();
3567            let kernel_path = temp_dir.path().join("kernel");
3568            File::create(&kernel_path).unwrap();
3569            let initrd_path = temp_dir.path().join("initrd");
3570            File::create(&initrd_path).unwrap();
3571            let root_path = temp_dir.path().to_str().unwrap();
3572            let opt = Options::try_parse_from([
3573                "openvmm",
3574                "--kernel",
3575                kernel_path.to_str().unwrap(),
3576                "--initrd",
3577                initrd_path.to_str().unwrap(),
3578                "--virtio-fs",
3579                &format!("fs,{root_path}"),
3580                "--virtio-fs-bus",
3581                "pcie:fs",
3582                "--virtio-rng",
3583                "--virtio-rng-bus",
3584                "pcie:rng",
3585                "--single-process",
3586            ])
3587            .unwrap();
3588            let mesh = VmmMesh::new(&driver, true).unwrap();
3589
3590            let (config, _resources) = vm_config_from_command_line(driver, &mesh, &opt)
3591                .await
3592                .unwrap();
3593
3594            let port_names: Vec<_> = config
3595                .pcie_devices
3596                .iter()
3597                .map(|device| device.port_name.as_str())
3598                .collect();
3599            assert_eq!(port_names, ["fs", "rng"]);
3600            mesh.shutdown().await;
3601        });
3602    }
3603
3604    #[test]
3605    fn rejects_duplicate_pcie_port_assignments() {
3606        DefaultPool::run_with(async |driver| {
3607            let temp_dir = tempfile::tempdir().unwrap();
3608            let kernel_path = temp_dir.path().join("kernel");
3609            File::create(&kernel_path).unwrap();
3610            let initrd_path = temp_dir.path().join("initrd");
3611            File::create(&initrd_path).unwrap();
3612            let root_path = temp_dir.path().to_str().unwrap();
3613            let opt = Options::try_parse_from([
3614                "openvmm",
3615                "--kernel",
3616                kernel_path.to_str().unwrap(),
3617                "--initrd",
3618                initrd_path.to_str().unwrap(),
3619                "--virtio-fs",
3620                &format!("pcie_port=custom:fs,{root_path}"),
3621                "--virtio-rng",
3622                "--virtio-rng-bus",
3623                "pcie:custom",
3624                "--single-process",
3625            ])
3626            .unwrap();
3627            let mesh = VmmMesh::new(&driver, true).unwrap();
3628
3629            let error = vm_config_from_command_line(driver, &mesh, &opt)
3630                .await
3631                .err()
3632                .unwrap();
3633
3634            assert_eq!(error.to_string(), "multiple devices use PCIe port 'custom'");
3635            mesh.shutdown().await;
3636        });
3637    }
3638
3639    #[test]
3640    fn rejects_duplicate_pcie_port_assignment_from_storage() {
3641        DefaultPool::run_with(async |driver| {
3642            let temp_dir = tempfile::tempdir().unwrap();
3643            let kernel_path = temp_dir.path().join("kernel");
3644            File::create(&kernel_path).unwrap();
3645            let initrd_path = temp_dir.path().join("initrd");
3646            File::create(&initrd_path).unwrap();
3647            let opt = Options::try_parse_from([
3648                "openvmm",
3649                "--kernel",
3650                kernel_path.to_str().unwrap(),
3651                "--initrd",
3652                initrd_path.to_str().unwrap(),
3653                "--nvme-pci",
3654                "id=nvme0,pcie_port=custom",
3655                "--virtio-rng",
3656                "--virtio-rng-bus",
3657                "pcie:custom",
3658                "--single-process",
3659            ])
3660            .unwrap();
3661            let mesh = VmmMesh::new(&driver, true).unwrap();
3662
3663            let error = vm_config_from_command_line(driver, &mesh, &opt)
3664                .await
3665                .err()
3666                .unwrap();
3667
3668            assert_eq!(error.to_string(), "multiple devices use PCIe port 'custom'");
3669            mesh.shutdown().await;
3670        });
3671    }
3672}