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