Skip to main content

openvmm_entry/
lib.rs

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