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