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