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