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