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    if opt.restore_snapshot.is_some() {
1332        // Snapshot restore: skip firmware loading entirely. Device state and
1333        // memory come from the snapshot directory.
1334        load_mode = LoadMode::None;
1335        with_hv = true;
1336    } else if let Some(path) = &opt.igvm {
1337        let file = fs_err::File::open(path)
1338            .context("failed to open igvm file")?
1339            .into();
1340        let cmdline = opt.cmdline.join(" ");
1341        with_hv = match opt.igvm_personality {
1342            None | Some(IgvmPersonalityCli::Uefi) => true,
1343            Some(IgvmPersonalityCli::LinuxDirect) => opt.hv,
1344        };
1345
1346        load_mode = LoadMode::Igvm {
1347            file,
1348            cmdline,
1349            vtl2_base_address: if opt.vtl2 {
1350                opt.igvm_vtl2_relocation_type
1351            } else {
1352                Vtl2BaseAddressType::File
1353            },
1354            com_serial: has_com3.then(|| SerialInformation {
1355                io_port: ComPort::Com3.io_port(),
1356                irq: ComPort::Com3.irq().into(),
1357            }),
1358        };
1359
1360        // An IGVM launch carries no SMBIOS field of its own; the identity is
1361        // only delivered over the GET/GED channel, which is absent here. Reject
1362        // overrides that would otherwise be silently dropped.
1363        let smbios_requested = !opt.smbios.is_empty();
1364        let smbios_delivered_via_get = with_get && with_hv;
1365        if smbios_requested && !smbios_delivered_via_get {
1366            anyhow::bail!(
1367                "--smbios is not supported for IGVM launches without an OpenHCL GET channel"
1368            );
1369        }
1370    } else if opt.pcat {
1371        // Emit a nice error early instead of complaining about missing firmware.
1372        if arch != MachineArch::X86_64 {
1373            anyhow::bail!("pcat not supported on this architecture");
1374        }
1375        with_hv = true;
1376
1377        let firmware = openvmm_pcat_locator::find_pcat_bios(opt.pcat_firmware.as_deref())?;
1378        load_mode = LoadMode::Pcat {
1379            firmware,
1380            boot_order: opt
1381                .pcat_boot_order
1382                .map(|x| x.0)
1383                .unwrap_or(DEFAULT_PCAT_BOOT_ORDER),
1384            hibernation_enabled: opt.hibernation,
1385            smbios,
1386        };
1387    } else if opt.uefi {
1388        use openvmm_defs::config::UefiConsoleMode;
1389
1390        if opt.no_hv && cfg!(guest_arch = "x86_64") {
1391            anyhow::bail!("--no-hv is not supported on x86_64");
1392        }
1393
1394        with_hv = !opt.no_hv;
1395
1396        let firmware = fs_err::File::open(
1397            (opt.uefi_firmware.0)
1398                .as_ref()
1399                .context("must provide uefi firmware when booting with uefi")?,
1400        )
1401        .context("failed to open uefi firmware")?;
1402
1403        // TODO: It would be better to default memory protections to on, but currently Linux does not boot via UEFI due to what
1404        //       appears to be a GRUB memory protection fault. Memory protections are therefore only enabled if configured.
1405        load_mode = LoadMode::Uefi {
1406            firmware: firmware.into(),
1407            enable_debugging: opt.uefi_debug,
1408            enable_memory_protections: opt.uefi_enable_memory_protections,
1409            disable_frontpage: opt.disable_frontpage,
1410            enable_tpm: opt.tpm.is_some(),
1411            enable_battery: opt.battery,
1412            enable_serial: any_serial_configured,
1413            enable_vpci_boot: false,
1414            uefi_console_mode: opt.uefi_console_mode.map(|m| match m {
1415                UefiConsoleModeCli::Default => UefiConsoleMode::Default,
1416                UefiConsoleModeCli::Com1 => UefiConsoleMode::Com1,
1417                UefiConsoleModeCli::Com2 => UefiConsoleMode::Com2,
1418                UefiConsoleModeCli::None => UefiConsoleMode::None,
1419            }),
1420            default_boot_always_attempt: opt.default_boot_always_attempt,
1421            smbios,
1422            enable_vmbus: !opt.no_vmbus,
1423            force_dma_bounce: opt.uefi_force_dma_bounce,
1424            enable_hv: !opt.no_hv,
1425            hibernation_enabled: opt.hibernation,
1426        };
1427    } else {
1428        // Linux Direct
1429        let mut cmdline = "panic=-1 debug".to_string();
1430
1431        with_hv = opt.hv;
1432        if with_hv && opt.pcie_root_complex.is_empty() {
1433            cmdline += " pci=off";
1434        }
1435
1436        if !console_str.is_empty() {
1437            let _ = write!(&mut cmdline, " console={}", console_str);
1438        }
1439
1440        if opt.gfx {
1441            cmdline += " console=tty";
1442        }
1443        for extra in &opt.cmdline {
1444            let _ = write!(&mut cmdline, " {}", extra);
1445        }
1446
1447        let kernel = fs_err::File::open(
1448            (opt.kernel.0)
1449                .as_ref()
1450                .context("must provide kernel when booting with linux direct")?,
1451        )
1452        .context("failed to open kernel")?;
1453        let initrd = (opt.initrd.0)
1454            .as_ref()
1455            .map(fs_err::File::open)
1456            .transpose()
1457            .context("failed to open initrd")?;
1458
1459        load_mode = LoadMode::Linux {
1460            kernel: kernel.into(),
1461            initrd: initrd.map(Into::into),
1462            cmdline,
1463            enable_serial: any_serial_configured,
1464            isolation: if matches!(opt.isolation, Some(cli_args::IsolationCli::Snp)) {
1465                openvmm_defs::config::LinuxIsolationConfig::Snp {
1466                    restricted_injection: opt.snp_restricted_injection,
1467                }
1468            } else {
1469                openvmm_defs::config::LinuxIsolationConfig::None
1470            },
1471            boot_mode: if opt.device_tree {
1472                openvmm_defs::config::LinuxDirectBootMode::DeviceTree
1473            } else {
1474                openvmm_defs::config::LinuxDirectBootMode::Acpi
1475            },
1476            smbios,
1477        };
1478    }
1479
1480    let mut vmgs = Some(if let Some(VmgsCli { kind, provision }) = &opt.vmgs {
1481        let disk = VmgsDisk {
1482            disk: disk_open(kind, false)
1483                .await
1484                .context("failed to open vmgs disk")?,
1485            encryption_policy: if opt.test_gsp_by_id {
1486                GuestStateEncryptionPolicy::GspById(true)
1487            } else {
1488                GuestStateEncryptionPolicy::None(true)
1489            },
1490        };
1491        match provision {
1492            ProvisionVmgs::OnEmpty => VmgsResource::Disk(disk),
1493            ProvisionVmgs::OnFailure => VmgsResource::ReprovisionOnFailure(disk),
1494            ProvisionVmgs::True => VmgsResource::Reprovision(disk),
1495        }
1496    } else {
1497        VmgsResource::Ephemeral
1498    });
1499
1500    if with_get && with_hv {
1501        let has_vtl0_nvme = storage.has_vtl0_nvme();
1502        let vtl2_settings = vtl2_settings_proto::Vtl2Settings {
1503            version: vtl2_settings_proto::vtl2_settings_base::Version::V1.into(),
1504            fixed: Some(Default::default()),
1505            dynamic: Some(vtl2_settings_proto::Vtl2SettingsDynamic {
1506                storage_controllers: storage.build_openhcl_settings(opt.vmbus_redirect),
1507                nic_devices: underhill_nics,
1508            }),
1509            namespace_settings: Vec::default(),
1510        };
1511
1512        // Cache the VTL2 settings for later modification via the interactive console.
1513        resources.vtl2_settings = Some(vtl2_settings.clone());
1514
1515        let (send, guest_request_recv) = mesh::channel();
1516        resources.ged_rpc = Some(send);
1517
1518        let vmgs = vmgs.take().unwrap();
1519
1520        vmbus_devices.extend([
1521            (
1522                openhcl_vtl,
1523                get_resources::gel::GuestEmulationLogHandle.into_resource(),
1524            ),
1525            (
1526                openhcl_vtl,
1527                get_resources::ged::GuestEmulationDeviceHandle {
1528                    firmware: if opt.pcat {
1529                        get_resources::ged::GuestFirmwareConfig::Pcat {
1530                            boot_order: opt
1531                                .pcat_boot_order
1532                                .map_or(DEFAULT_PCAT_BOOT_ORDER, |x| x.0)
1533                                .map(|x| match x {
1534                                    openvmm_defs::config::PcatBootDevice::Floppy => {
1535                                        get_resources::ged::PcatBootDevice::Floppy
1536                                    }
1537                                    openvmm_defs::config::PcatBootDevice::HardDrive => {
1538                                        get_resources::ged::PcatBootDevice::HardDrive
1539                                    }
1540                                    openvmm_defs::config::PcatBootDevice::Optical => {
1541                                        get_resources::ged::PcatBootDevice::Optical
1542                                    }
1543                                    openvmm_defs::config::PcatBootDevice::Network => {
1544                                        get_resources::ged::PcatBootDevice::Network
1545                                    }
1546                                }),
1547                        }
1548                    } else {
1549                        use get_resources::ged::UefiConsoleMode;
1550
1551                        get_resources::ged::GuestFirmwareConfig::Uefi {
1552                            enable_vpci_boot: has_vtl0_nvme,
1553                            firmware_debug: opt.uefi_debug,
1554                            disable_frontpage: opt.disable_frontpage,
1555                            console_mode: match opt.uefi_console_mode.unwrap_or(UefiConsoleModeCli::Default) {
1556                                UefiConsoleModeCli::Default => UefiConsoleMode::Default,
1557                                UefiConsoleModeCli::Com1 => UefiConsoleMode::COM1,
1558                                UefiConsoleModeCli::Com2 => UefiConsoleMode::COM2,
1559                                UefiConsoleModeCli::None => UefiConsoleMode::None,
1560                            },
1561                            default_boot_always_attempt: opt.default_boot_always_attempt,
1562                        }
1563                    },
1564                    com1: with_vmbus_com1_serial,
1565                    com2: with_vmbus_com2_serial,
1566                    serial_tx_only: opt.serial_tx_only,
1567                    vtl2_settings: Some(prost::Message::encode_to_vec(&vtl2_settings)),
1568                    vmbus_redirection: opt.vmbus_redirect,
1569                    vmgs,
1570                    framebuffer: opt
1571                        .vtl2_gfx
1572                        .then(|| SharedFramebufferHandle.into_resource()),
1573                    guest_request_recv,
1574                    tpm_version: opt.tpm.map(|v| match v {
1575                        TpmVersionCli::V138 => get_resources::ged::GedTpmVersion::V138,
1576                        TpmVersionCli::V185 => get_resources::ged::GedTpmVersion::V185,
1577                    }),
1578                    firmware_event_send: None,
1579                    secure_boot_enabled: opt.secure_boot,
1580                    secure_boot_template: match opt.secure_boot_template {
1581                        Some(SecureBootTemplateCli::Windows) => {
1582                            get_resources::ged::GuestSecureBootTemplateType::MicrosoftWindows
1583                        },
1584                        Some(SecureBootTemplateCli::UefiCa) => {
1585                            get_resources::ged::GuestSecureBootTemplateType::MicrosoftUefiCertificateAuthority
1586                        }
1587                        None => {
1588                            get_resources::ged::GuestSecureBootTemplateType::None
1589                        },
1590                    },
1591                    enable_battery: opt.battery,
1592                    enable_hibernation: opt.hibernation,
1593                    no_persistent_secrets: true,
1594                    igvm_attest_test_config: None,
1595                    test_gsp_by_id: opt.test_gsp_by_id,
1596                    efi_diagnostics_log_level: {
1597                        match opt.efi_diagnostics_log_level.unwrap_or_default() {
1598                            EfiDiagnosticsLogLevelCli::Default => get_resources::ged::EfiDiagnosticsLogLevelType::Default,
1599                            EfiDiagnosticsLogLevelCli::Info => get_resources::ged::EfiDiagnosticsLogLevelType::Info,
1600                            EfiDiagnosticsLogLevelCli::Full => get_resources::ged::EfiDiagnosticsLogLevelType::Full,
1601                        }
1602                    },
1603                    force_dma_bounce_enabled: opt.uefi_force_dma_bounce,
1604                    smbios: ged_smbios,
1605                }
1606                .into_resource(),
1607            ),
1608        ]);
1609    }
1610
1611    if let Some(tpm_version) = opt.tpm
1612        && !opt.vtl2
1613    {
1614        let register_layout = if cfg!(guest_arch = "x86_64") {
1615            TpmRegisterLayout::IoPort
1616        } else {
1617            TpmRegisterLayout::Mmio
1618        };
1619
1620        let tpm_version = match tpm_version {
1621            TpmVersionCli::V138 => TpmVersion::V138,
1622            TpmVersionCli::V185 => TpmVersion::V185,
1623        };
1624
1625        let (ppi_store, nvram_store) = if opt.vmgs.is_some() {
1626            (
1627                VmgsFileHandle::new(vmgs_format::FileId::TPM_PPI, true).into_resource(),
1628                VmgsFileHandle::new(tpm_version.to_nvram_vmgs_file_id(), true).into_resource(),
1629            )
1630        } else {
1631            (
1632                EphemeralNonVolatileStoreHandle.into_resource(),
1633                EphemeralNonVolatileStoreHandle.into_resource(),
1634            )
1635        };
1636
1637        chipset_devices.push(ChipsetDeviceHandle {
1638            name: "tpm".to_string(),
1639            resource: chipset_device_worker_defs::RemoteChipsetDeviceHandle {
1640                device: TpmDeviceHandle {
1641                    version: tpm_version,
1642                    ppi_store,
1643                    nvram_store,
1644                    nvram_size: None,
1645                    refresh_tpm_seeds: false,
1646                    ak_cert_type: tpm_resources::TpmAkCertTypeResource::None,
1647                    register_layout,
1648                    guest_secret_key: None,
1649                    logger: None,
1650                    is_confidential_vm: false,
1651                    bios_guid,
1652                }
1653                .into_resource(),
1654                worker_host: mesh.make_host("tpm", None).await?,
1655            }
1656            .into_resource(),
1657        });
1658    }
1659
1660    let vga_firmware = if opt.pcat {
1661        Some(openvmm_pcat_locator::find_svga_bios(
1662            opt.vga_firmware.as_deref(),
1663        )?)
1664    } else {
1665        None
1666    };
1667
1668    if opt.gfx {
1669        // Channel for the video device to report dirty rectangles to the VNC worker.
1670        let (dirt_send, dirt_recv) = mesh::channel();
1671        resources.dirty_rect_recv = Some(dirt_recv);
1672
1673        vmbus_devices.extend([
1674            (
1675                DeviceVtl::Vtl0,
1676                SynthVideoHandle {
1677                    framebuffer: SharedFramebufferHandle.into_resource(),
1678                    dirt_send: Some(dirt_send),
1679                }
1680                .into_resource(),
1681            ),
1682            (
1683                DeviceVtl::Vtl0,
1684                SynthKeyboardHandle {
1685                    source: MultiplexedInputHandle {
1686                        // Save 0 for PS/2
1687                        elevation: 1,
1688                    }
1689                    .into_resource(),
1690                }
1691                .into_resource(),
1692            ),
1693            (
1694                DeviceVtl::Vtl0,
1695                SynthMouseHandle {
1696                    source: MultiplexedInputHandle {
1697                        // Save 0 for PS/2
1698                        elevation: 1,
1699                    }
1700                    .into_resource(),
1701                }
1702                .into_resource(),
1703            ),
1704        ]);
1705    }
1706
1707    let vsock_listener = |path: Option<&str>| -> anyhow::Result<_> {
1708        if let Some(path) = path {
1709            cleanup_socket(path.as_ref());
1710            let listener = unix_socket::UnixListener::bind(path)
1711                .with_context(|| format!("failed to bind to hybrid vsock path: {}", path))?;
1712            Ok(Some(listener))
1713        } else {
1714            Ok(None)
1715        }
1716    };
1717
1718    let vtl0_vsock_listener = vsock_listener(opt.vmbus_vsock_path.as_deref())?;
1719    let vtl2_vsock_listener = vsock_listener(opt.vmbus_vtl2_vsock_path.as_deref())?;
1720
1721    if let Some(path) = &opt.openhcl_dump_path {
1722        let (resource, task) = spawn_dump_handler(&spawner, path.clone(), None);
1723        task.detach();
1724        vmbus_devices.push((openhcl_vtl, resource));
1725    }
1726
1727    #[cfg(guest_arch = "aarch64")]
1728    let topology_arch = openvmm_defs::config::ArchTopologyConfig::Aarch64(
1729        openvmm_defs::config::Aarch64TopologyConfig {
1730            // TODO: allow this to be configured from the command line
1731            gic_config: None,
1732            pmu_gsiv: openvmm_defs::config::PmuGsivConfig::Platform,
1733            gic_msi: match opt.gic_msi {
1734                cli_args::GicMsiCli::Auto => openvmm_defs::config::GicMsiConfig::Auto,
1735                cli_args::GicMsiCli::Its => openvmm_defs::config::GicMsiConfig::Its,
1736                cli_args::GicMsiCli::V2m => {
1737                    openvmm_defs::config::GicMsiConfig::V2m { spi_count: None }
1738                }
1739            },
1740        },
1741    );
1742    #[cfg(guest_arch = "x86_64")]
1743    let topology_arch =
1744        openvmm_defs::config::ArchTopologyConfig::X86(openvmm_defs::config::X86TopologyConfig {
1745            apic_id_offset: opt.apic_id_offset,
1746            x2apic: opt.x2apic,
1747        });
1748
1749    let with_isolation = if let Some(isolation) = &opt.isolation {
1750        match isolation {
1751            cli_args::IsolationCli::Vbs => {
1752                // TODO: For now, VBS isolation is only supported with VTL2.
1753                if !opt.vtl2 {
1754                    anyhow::bail!("VBS isolation is only currently supported with vtl2");
1755                }
1756
1757                // TODO: Alias map support is not yet implemented with isolation.
1758                if !opt.no_alias_map {
1759                    anyhow::bail!("alias map not supported with isolation");
1760                }
1761
1762                Some(openvmm_defs::config::IsolationType::Vbs)
1763            }
1764            cli_args::IsolationCli::Snp => Some(openvmm_defs::config::IsolationType::Snp),
1765        }
1766    } else {
1767        None
1768    };
1769
1770    if with_hv && !opt.no_vmbus {
1771        let (shutdown_send, shutdown_recv) = mesh::channel();
1772        resources.shutdown_ic = Some(shutdown_send);
1773        let (kvp_send, kvp_recv) = mesh::channel();
1774        resources.kvp_ic = Some(kvp_send);
1775        vmbus_devices.extend(
1776            [
1777                hyperv_ic_resources::shutdown::ShutdownIcHandle {
1778                    recv: shutdown_recv,
1779                }
1780                .into_resource(),
1781                hyperv_ic_resources::kvp::KvpIcHandle { recv: kvp_recv }.into_resource(),
1782                hyperv_ic_resources::timesync::TimesyncIcHandle.into_resource(),
1783            ]
1784            .map(|r| (DeviceVtl::Vtl0, r)),
1785        );
1786    }
1787
1788    if let Some(hive_path) = &opt.imc {
1789        let file = fs_err::File::open(hive_path).context("failed to open imc hive")?;
1790        vmbus_devices.push((
1791            DeviceVtl::Vtl0,
1792            vmbfs_resources::VmbfsImcDeviceHandle { file: file.into() }.into_resource(),
1793        ));
1794    }
1795
1796    let mut virtio_devices = Vec::new();
1797    let mut add_virtio_device = |bus, resource: Resource<VirtioDeviceHandle>| {
1798        let bus = match bus {
1799            VirtioBusCli::Auto => {
1800                // Use VPCI when possible (currently only on Windows and macOS due
1801                // to KVM backend limitations).
1802                if with_hv && (cfg!(windows) || cfg!(target_os = "macos")) {
1803                    None
1804                } else {
1805                    Some(VirtioBus::Pci)
1806                }
1807            }
1808            VirtioBusCli::Mmio => Some(VirtioBus::Mmio),
1809            VirtioBusCli::Pci => Some(VirtioBus::Pci),
1810            VirtioBusCli::Vpci => None,
1811        };
1812        if let Some(bus) = bus {
1813            virtio_devices.push((bus, resource));
1814        } else {
1815            vpci_devices.push(VpciDeviceConfig {
1816                vtl: DeviceVtl::Vtl0,
1817                instance_id: Guid::new_random(),
1818                resource: VirtioPciDeviceHandle(resource).into_resource(),
1819                vnode: None,
1820            });
1821        }
1822    };
1823
1824    for cli_cfg in &opt.virtio_net {
1825        if cli_cfg.underhill {
1826            anyhow::bail!("use --net uh:[...] to add underhill NICs")
1827        }
1828        let vport = parse_endpoint(cli_cfg, &mut nic_index, &mut resources)?;
1829        let resource = virtio_resources::net::VirtioNetHandle {
1830            max_queues: vport.max_queues,
1831            mac_address: vport.mac_address,
1832            endpoint: vport.endpoint,
1833        }
1834        .into_resource();
1835        if let Some(pcie_port) = &cli_cfg.pcie_port {
1836            pcie_devices.push(PcieDeviceConfig {
1837                port_name: pcie_port.clone(),
1838                resource: VirtioPciDeviceHandle(resource).into_resource(),
1839            });
1840        } else {
1841            add_virtio_device(VirtioBusCli::Auto, resource);
1842        }
1843    }
1844
1845    for args in &opt.virtio_fs {
1846        let resource: Resource<VirtioDeviceHandle> = virtio_resources::fs::VirtioFsHandle {
1847            tag: args.tag.clone(),
1848            fs: virtio_resources::fs::VirtioFsBackend::HostFs {
1849                root_path: args.path.clone(),
1850                mount_options: args.options.clone(),
1851            },
1852        }
1853        .into_resource();
1854        if let Some(pcie_port) = &args.pcie_port {
1855            pcie_devices.push(PcieDeviceConfig {
1856                port_name: pcie_port.clone(),
1857                resource: VirtioPciDeviceHandle(resource).into_resource(),
1858            });
1859        } else {
1860            add_virtio_device(opt.virtio_fs_bus, resource);
1861        }
1862    }
1863
1864    for args in &opt.virtio_fs_shmem {
1865        let resource: Resource<VirtioDeviceHandle> = virtio_resources::fs::VirtioFsHandle {
1866            tag: args.tag.clone(),
1867            fs: virtio_resources::fs::VirtioFsBackend::SectionFs {
1868                root_path: args.path.clone(),
1869            },
1870        }
1871        .into_resource();
1872        if let Some(pcie_port) = &args.pcie_port {
1873            pcie_devices.push(PcieDeviceConfig {
1874                port_name: pcie_port.clone(),
1875                resource: VirtioPciDeviceHandle(resource).into_resource(),
1876            });
1877        } else {
1878            add_virtio_device(opt.virtio_fs_bus, resource);
1879        }
1880    }
1881
1882    for args in &opt.virtio_9p {
1883        let resource: Resource<VirtioDeviceHandle> = virtio_resources::p9::VirtioPlan9Handle {
1884            tag: args.tag.clone(),
1885            root_path: args.path.clone(),
1886            debug: opt.virtio_9p_debug,
1887        }
1888        .into_resource();
1889        if let Some(pcie_port) = &args.pcie_port {
1890            pcie_devices.push(PcieDeviceConfig {
1891                port_name: pcie_port.clone(),
1892                resource: VirtioPciDeviceHandle(resource).into_resource(),
1893            });
1894        } else {
1895            add_virtio_device(VirtioBusCli::Auto, resource);
1896        }
1897    }
1898
1899    if let Some(pmem_args) = &opt.virtio_pmem {
1900        let resource: Resource<VirtioDeviceHandle> = virtio_resources::pmem::VirtioPmemHandle {
1901            path: pmem_args.path.clone(),
1902        }
1903        .into_resource();
1904        if let Some(pcie_port) = &pmem_args.pcie_port {
1905            pcie_devices.push(PcieDeviceConfig {
1906                port_name: pcie_port.clone(),
1907                resource: VirtioPciDeviceHandle(resource).into_resource(),
1908            });
1909        } else {
1910            add_virtio_device(VirtioBusCli::Auto, resource);
1911        }
1912    }
1913
1914    if opt.virtio_rng {
1915        let resource: Resource<VirtioDeviceHandle> =
1916            virtio_resources::rng::VirtioRngHandle.into_resource();
1917        if let Some(pcie_port) = &opt.virtio_rng_pcie_port {
1918            pcie_devices.push(PcieDeviceConfig {
1919                port_name: pcie_port.clone(),
1920                resource: VirtioPciDeviceHandle(resource).into_resource(),
1921            });
1922        } else {
1923            add_virtio_device(opt.virtio_rng_bus, resource);
1924        }
1925    }
1926
1927    if let Some(backend) = virtio_console_backend {
1928        let resource: Resource<VirtioDeviceHandle> =
1929            virtio_resources::console::VirtioConsoleHandle { backend }.into_resource();
1930        if let Some(pcie_port) = &opt.virtio_console_pcie_port {
1931            pcie_devices.push(PcieDeviceConfig {
1932                port_name: pcie_port.clone(),
1933                resource: VirtioPciDeviceHandle(resource).into_resource(),
1934            });
1935        } else {
1936            add_virtio_device(VirtioBusCli::Auto, resource);
1937        }
1938    }
1939
1940    // Handle --vhost-user arguments.
1941    #[cfg(target_os = "linux")]
1942    for vhost_cli in &opt.vhost_user {
1943        let stream =
1944            unix_socket::UnixStream::connect(&vhost_cli.socket_path).with_context(|| {
1945                format!(
1946                    "failed to connect to vhost-user socket: {}",
1947                    vhost_cli.socket_path
1948                )
1949            })?;
1950
1951        use crate::cli_args::VhostUserDeviceTypeCli;
1952        let resource: Resource<VirtioDeviceHandle> = match vhost_cli.device_type {
1953            VhostUserDeviceTypeCli::Fs {
1954                ref tag,
1955                num_queues,
1956                queue_size,
1957            } => virtio_resources::vhost_user::VhostUserFsHandle {
1958                socket: stream.into(),
1959                tag: tag.clone(),
1960                num_queues,
1961                queue_size,
1962            }
1963            .into_resource(),
1964            VhostUserDeviceTypeCli::Blk {
1965                num_queues,
1966                queue_size,
1967            } => virtio_resources::vhost_user::VhostUserBlkHandle {
1968                socket: stream.into(),
1969                num_queues,
1970                queue_size,
1971            }
1972            .into_resource(),
1973            VhostUserDeviceTypeCli::Other {
1974                device_id,
1975                ref queue_sizes,
1976            } => virtio_resources::vhost_user::VhostUserGenericHandle {
1977                socket: stream.into(),
1978                device_id,
1979                queue_sizes: queue_sizes.clone(),
1980            }
1981            .into_resource(),
1982        };
1983        if let Some(pcie_port) = &vhost_cli.pcie_port {
1984            pcie_devices.push(PcieDeviceConfig {
1985                port_name: pcie_port.clone(),
1986                resource: VirtioPciDeviceHandle(resource).into_resource(),
1987            });
1988        } else {
1989            add_virtio_device(VirtioBusCli::Auto, resource);
1990        }
1991    }
1992
1993    let virtio_vsock_bus = opt.virtio_vsock_bus.unwrap_or(VirtioBusCli::Auto);
1994
1995    if let Some(vsock_path) = &opt.virtio_vsock_path {
1996        let listener = vsock_listener(Some(vsock_path))?.unwrap();
1997        add_virtio_device(
1998            virtio_vsock_bus,
1999            virtio_resources::vsock::VirtioVsockHandle {
2000                // The guest CID does not matter since the UDS relay does not use it. It just needs
2001                // to be some non-reserved value for the guest to use.
2002                guest_cid: 0x3,
2003                base_path: vsock_path.clone(),
2004                listener,
2005            }
2006            .into_resource(),
2007        );
2008    }
2009
2010    #[cfg(target_os = "linux")]
2011    if let Some(guest_cid) = opt.virtio_vsock_vhost_cid {
2012        let vhost = std::fs::OpenOptions::new()
2013            .read(true)
2014            .write(true)
2015            .open("/dev/vhost-vsock")
2016            .context("failed to open /dev/vhost-vsock")?
2017            .into();
2018        add_virtio_device(
2019            virtio_vsock_bus,
2020            virtio_resources::vsock::VirtioVsockVhostHandle { vhost, guest_cid }.into_resource(),
2021        );
2022    }
2023
2024    let mut cfg = Config {
2025        chipset,
2026        load_mode,
2027        floppy_disks,
2028        pcie_root_complexes,
2029        pcie_ecam_below_4gb: opt.pcie_ecam_below_4gb,
2030        #[cfg(target_os = "linux")]
2031        pcie_devices: {
2032            let mut devs = pcie_devices;
2033            devs.extend(vfio_pcie_devices);
2034            devs
2035        },
2036        #[cfg(not(target_os = "linux"))]
2037        pcie_devices,
2038        pcie_switches,
2039        pcie_generic_initiators,
2040        vpci_devices,
2041        ide_disks: Vec::new(),
2042        numa: {
2043            if let Some(ref nodes) = opt.numa {
2044                // --numa mode: each --numa flag defines a node.
2045                NumaTopology {
2046                    nodes: nodes
2047                        .iter()
2048                        .map(|n| {
2049                            let vps = match &n.vps {
2050                                Some(vps) if vps.0.is_empty() => VpAssignment::Empty,
2051                                Some(vps) => {
2052                                    VpAssignment::Explicit(vps.expand_below(opt.processors)?)
2053                                }
2054                                None => VpAssignment::FromTopology,
2055                            };
2056                            Ok(NumaNode {
2057                                mem: Some(MemoryConfig {
2058                                    mem_size: n
2059                                        .memory
2060                                        .size
2061                                        .expect("NUMA memory size was validated")
2062                                        .0,
2063                                    prefetch_memory: n.memory.prefetch,
2064                                    private_memory: n.memory.shared == Some(false),
2065                                    transparent_hugepages: n
2066                                        .memory
2067                                        .transparent_hugepages
2068                                        .unwrap_or(!n.memory.hugepages),
2069                                    hugepages: n.memory.hugepages,
2070                                    hugepage_size: n.memory.hugepage_size.map(|m| m.0),
2071                                    host_numa_node: n.host_numa_node,
2072                                }),
2073                                vps,
2074                            })
2075                        })
2076                        .collect::<anyhow::Result<Vec<_>>>()?,
2077                    distances: opt
2078                        .numa_distance
2079                        .as_deref()
2080                        .unwrap_or(&[])
2081                        .iter()
2082                        .map(|d| NumaDistance {
2083                            src: d.src,
2084                            dst: d.dst,
2085                            distance: d.distance,
2086                        })
2087                        .collect(),
2088                }
2089            } else {
2090                // Single-node default from --memory.
2091                NumaTopology {
2092                    nodes: vec![NumaNode {
2093                        mem: Some(MemoryConfig {
2094                            mem_size: opt.memory_size(),
2095                            prefetch_memory: opt.prefetch_memory(),
2096                            private_memory: opt.private_memory(),
2097                            transparent_hugepages: opt.transparent_hugepages(),
2098                            hugepages: opt.memory.hugepages,
2099                            hugepage_size: opt.memory.hugepage_size.map(|m| m.0),
2100                            host_numa_node: None,
2101                        }),
2102                        vps: VpAssignment::FromTopology,
2103                    }],
2104                    distances: vec![],
2105                }
2106            }
2107        },
2108        processor_topology: ProcessorTopologyConfig {
2109            proc_count: opt.processors,
2110            vps_per_socket: opt.vps_per_socket,
2111            enable_smt: match opt.smt {
2112                cli_args::SmtConfigCli::Auto => None,
2113                cli_args::SmtConfigCli::Force => Some(true),
2114                cli_args::SmtConfigCli::Off => Some(false),
2115            },
2116            arch: Some(topology_arch),
2117        },
2118        hypervisor: HypervisorConfig {
2119            with_hv,
2120            with_vtl2: opt.vtl2.then_some(Vtl2Config {
2121                vtl0_alias_map: !opt.no_alias_map,
2122                late_map_vtl0_memory: match opt.late_map_vtl0_policy {
2123                    cli_args::Vtl0LateMapPolicyCli::Off => None,
2124                    cli_args::Vtl0LateMapPolicyCli::Log => Some(LateMapVtl0MemoryPolicy::Log),
2125                    cli_args::Vtl0LateMapPolicyCli::Halt => Some(LateMapVtl0MemoryPolicy::Halt),
2126                    cli_args::Vtl0LateMapPolicyCli::Exception => {
2127                        Some(LateMapVtl0MemoryPolicy::InjectException)
2128                    }
2129                },
2130            }),
2131            with_isolation,
2132            nested_virt: opt.nested_virt,
2133        },
2134        #[cfg(windows)]
2135        kernel_vmnics,
2136        input: mesh::Receiver::new(),
2137        framebuffer,
2138        vga_firmware,
2139        vtl2_gfx: opt.vtl2_gfx,
2140        virtio_devices,
2141        vmbus: (with_hv && !opt.no_vmbus).then_some(VmbusConfig {
2142            vsock_listener: vtl0_vsock_listener,
2143            vsock_path: opt.vmbus_vsock_path.clone(),
2144            vtl2_redirect: opt.vmbus_redirect,
2145            vmbus_max_version: opt.vmbus_max_version,
2146            #[cfg(windows)]
2147            vmbusproxy_handle,
2148        }),
2149        vtl2_vmbus: (with_hv && opt.vtl2).then_some(VmbusConfig {
2150            vsock_listener: vtl2_vsock_listener,
2151            vsock_path: opt.vmbus_vtl2_vsock_path.clone(),
2152            ..Default::default()
2153        }),
2154        vmbus_devices,
2155        chipset_devices,
2156        pci_chipset_devices,
2157        isa_dma_controller,
2158        chipset_capabilities: capabilities,
2159        layout: layout_config,
2160        #[cfg(windows)]
2161        vpci_resources,
2162        vmgs,
2163        firmware_event_send: None,
2164        debugger_rpc: None,
2165        rtc_delta_milliseconds: 0,
2166    };
2167
2168    storage.build_config(&mut cfg, &mut resources, opt.scsi_sub_channels)?;
2169    resources.serial_driver = Some(serial_driver);
2170    validate_snp_config(&cfg)?;
2171    Ok((cfg, resources))
2172}
2173
2174fn validate_snp_config(cfg: &Config) -> anyhow::Result<()> {
2175    if cfg.hypervisor.with_isolation != Some(openvmm_defs::config::IsolationType::Snp) {
2176        return Ok(());
2177    }
2178
2179    if !matches!(
2180        cfg.load_mode,
2181        LoadMode::Linux { .. } | LoadMode::Igvm { .. }
2182    ) {
2183        anyhow::bail!("SNP isolation currently only supports Linux direct or IGVM boot");
2184    }
2185    if cfg.hypervisor.with_hv {
2186        anyhow::bail!("SNP isolation currently does not support Hyper-V enlightenments");
2187    }
2188    if cfg.hypervisor.with_vtl2.is_some() {
2189        anyhow::bail!("SNP isolation currently does not support VTL2");
2190    }
2191    if cfg.vmbus.is_some() || cfg.vtl2_vmbus.is_some() || !cfg.vmbus_devices.is_empty() {
2192        anyhow::bail!("SNP isolation currently does not support VMBus devices");
2193    }
2194
2195    let only_supported_chipset_devices = cfg.chipset_devices.iter().all(|device| {
2196        matches!(
2197            device.resource.id(),
2198            "serial_16550"
2199                | "pic"
2200                | "pit"
2201                | "generic-ioapic"
2202                | "hyperv_power_management"
2203                | "missing-dev"
2204        )
2205    });
2206    let only_virtio_pcie_devices = cfg
2207        .pcie_devices
2208        .iter()
2209        .all(|device| device.resource.id() == "virtio");
2210    if !cfg.floppy_disks.is_empty()
2211        || !cfg.ide_disks.is_empty()
2212        || !cfg.virtio_devices.is_empty()
2213        || !only_virtio_pcie_devices
2214        || !cfg.vpci_devices.is_empty()
2215        || !only_supported_chipset_devices
2216        || !cfg.pci_chipset_devices.is_empty()
2217    {
2218        anyhow::bail!("SNP isolation currently only supports virtio devices");
2219    }
2220    if cfg.framebuffer.is_some() || cfg.vga_firmware.is_some() || cfg.debugger_rpc.is_some() {
2221        anyhow::bail!("SNP isolation currently does not support this VM configuration");
2222    }
2223
2224    Ok(())
2225}
2226
2227/// Gets the terminal to use for externally launched console windows.
2228pub(crate) fn openvmm_terminal_app() -> Option<PathBuf> {
2229    std::env::var_os("OPENVMM_TERM")
2230        .or_else(|| std::env::var_os("HVLITE_TERM"))
2231        .map(Into::into)
2232}
2233
2234// Tries to remove `path` if it is confirmed to be a Unix socket.
2235fn cleanup_socket(path: &Path) {
2236    #[cfg(windows)]
2237    let is_socket = pal::windows::fs::is_unix_socket(path).unwrap_or(false);
2238    #[cfg(not(windows))]
2239    let is_socket = path
2240        .metadata()
2241        .is_ok_and(|meta| std::os::unix::fs::FileTypeExt::is_socket(&meta.file_type()));
2242
2243    if is_socket {
2244        let _ = std::fs::remove_file(path);
2245    }
2246}
2247
2248#[cfg(windows)]
2249fn new_switch_port(
2250    switch_id: Option<&str>,
2251) -> anyhow::Result<(
2252    openvmm_defs::config::SwitchPortId,
2253    vmswitch::kernel::SwitchPort,
2254)> {
2255    let id = vmswitch::kernel::SwitchPortId {
2256        switch: match switch_id {
2257            Some(s) => s.parse().context("invalid switch id")?,
2258            None => vmswitch::hcn::DEFAULT_SWITCH,
2259        },
2260        port: Guid::new_random(),
2261    };
2262    let _ = vmswitch::hcn::Network::open(&id.switch)
2263        .with_context(|| format!("could not find switch {}", id.switch))?;
2264
2265    let port = vmswitch::kernel::SwitchPort::new(&id).context("failed to create switch port")?;
2266
2267    let id = openvmm_defs::config::SwitchPortId {
2268        switch: id.switch,
2269        port: id.port,
2270    };
2271    Ok((id, port))
2272}
2273
2274fn parse_endpoint(
2275    cli_cfg: &NicConfigCli,
2276    index: &mut usize,
2277    resources: &mut VmResources,
2278) -> anyhow::Result<NicConfig> {
2279    let _ = resources;
2280    let endpoint = match &cli_cfg.endpoint {
2281        EndpointConfigCli::Consomme { cidr, host_fwd } => {
2282            let ports = host_fwd
2283                .iter()
2284                .map(|fwd| {
2285                    use net_backend_resources::consomme::HostPortProtocol;
2286                    net_backend_resources::consomme::HostPortConfig {
2287                        protocol: match fwd.protocol {
2288                            cli_args::HostPortProtocolCli::Tcp => HostPortProtocol::Tcp,
2289                            cli_args::HostPortProtocolCli::Udp => HostPortProtocol::Udp,
2290                        },
2291                        host_address: fwd
2292                            .host_address
2293                            .map(net_backend_resources::consomme::HostIpAddress::from),
2294                        host_port: net_backend_resources::consomme::HostPort::Fixed(fwd.host_port),
2295                        guest_port: fwd.guest_port,
2296                    }
2297                })
2298                .collect();
2299            // Only wire the bind/unbind RPC channel to the first consomme
2300            // endpoint. Additional consomme NICs work normally but cannot be
2301            // targeted by runtime bind/unbind commands.
2302            let recv = if resources.consomme_rpc.is_none() {
2303                let (send, recv) = mesh::channel();
2304                resources.consomme_rpc = Some(send);
2305                Some(recv)
2306            } else {
2307                None
2308            };
2309            net_backend_resources::consomme::ConsommeHandle {
2310                cidr: cidr.clone(),
2311                ports,
2312                recv,
2313            }
2314            .into_resource()
2315        }
2316        EndpointConfigCli::None => net_backend_resources::null::NullHandle.into_resource(),
2317        EndpointConfigCli::Dio { id } => {
2318            #[cfg(windows)]
2319            {
2320                let (port_id, port) = new_switch_port(id.as_deref())?;
2321                resources.switch_ports.push(port);
2322                net_backend_resources::dio::WindowsDirectIoHandle {
2323                    switch_port_id: net_backend_resources::dio::SwitchPortId {
2324                        switch: port_id.switch,
2325                        port: port_id.port,
2326                    },
2327                }
2328                .into_resource()
2329            }
2330
2331            #[cfg(not(windows))]
2332            {
2333                let _ = id;
2334                bail!("cannot use dio on non-windows platforms")
2335            }
2336        }
2337        EndpointConfigCli::Tap { name } => {
2338            #[cfg(target_os = "linux")]
2339            {
2340                let fd = net_tap::tap::open_tap(name)
2341                    .with_context(|| format!("failed to open TAP device '{name}'"))?;
2342                net_backend_resources::tap::TapHandle { fd }.into_resource()
2343            }
2344
2345            #[cfg(not(target_os = "linux"))]
2346            {
2347                let _ = name;
2348                bail!("TAP backend is only supported on Linux")
2349            }
2350        }
2351    };
2352
2353    // Pick a random MAC address.
2354    let mut mac_address = [0x00, 0x15, 0x5D, 0, 0, 0];
2355    getrandom::fill(&mut mac_address[3..]).expect("rng failure");
2356
2357    // Pick a fixed instance ID based on the index.
2358    const BASE_INSTANCE_ID: Guid = guid::guid!("00000000-da43-11ed-936a-00155d6db52f");
2359    let instance_id = Guid {
2360        data1: *index as u32,
2361        ..BASE_INSTANCE_ID
2362    };
2363    *index += 1;
2364
2365    Ok(NicConfig {
2366        vtl: cli_cfg.vtl,
2367        instance_id,
2368        endpoint,
2369        mac_address: mac_address.into(),
2370        max_queues: cli_cfg.max_queues,
2371        pcie_port: cli_cfg.pcie_port.clone(),
2372    })
2373}
2374
2375#[derive(Debug)]
2376struct NicConfig {
2377    vtl: DeviceVtl,
2378    instance_id: Guid,
2379    mac_address: MacAddress,
2380    endpoint: Resource<NetEndpointHandleKind>,
2381    max_queues: Option<u16>,
2382    pcie_port: Option<String>,
2383}
2384
2385impl NicConfig {
2386    fn into_netvsp_handle(self) -> (DeviceVtl, Resource<VmbusDeviceHandleKind>) {
2387        (
2388            self.vtl,
2389            netvsp_resources::NetvspHandle {
2390                instance_id: self.instance_id,
2391                mac_address: self.mac_address,
2392                endpoint: self.endpoint,
2393                max_queues: self.max_queues,
2394            }
2395            .into_resource(),
2396        )
2397    }
2398}
2399
2400enum LayerOrDisk {
2401    Layer(DiskLayerDescription),
2402    Disk(Resource<DiskHandleKind>),
2403}
2404
2405async fn disk_open(
2406    disk_cli: &DiskCliKind,
2407    read_only: bool,
2408) -> anyhow::Result<Resource<DiskHandleKind>> {
2409    let mut layers = Vec::new();
2410    disk_open_inner(disk_cli, read_only, &mut layers).await?;
2411    if layers.len() == 1 && matches!(layers[0], LayerOrDisk::Disk(_)) {
2412        let LayerOrDisk::Disk(disk) = layers.pop().unwrap() else {
2413            unreachable!()
2414        };
2415        Ok(disk)
2416    } else {
2417        Ok(Resource::new(disk_backend_resources::LayeredDiskHandle {
2418            layers: layers
2419                .into_iter()
2420                .map(|layer| match layer {
2421                    LayerOrDisk::Layer(layer) => layer,
2422                    LayerOrDisk::Disk(disk) => DiskLayerDescription {
2423                        layer: DiskLayerHandle(disk).into_resource(),
2424                        read_cache: false,
2425                        write_through: false,
2426                    },
2427                })
2428                .collect(),
2429        }))
2430    }
2431}
2432
2433fn disk_open_inner<'a>(
2434    disk_cli: &'a DiskCliKind,
2435    read_only: bool,
2436    layers: &'a mut Vec<LayerOrDisk>,
2437) -> futures::future::BoxFuture<'a, anyhow::Result<()>> {
2438    Box::pin(async move {
2439        fn layer<T: IntoResource<DiskLayerHandleKind>>(layer: T) -> LayerOrDisk {
2440            LayerOrDisk::Layer(layer.into_resource().into())
2441        }
2442        fn disk<T: IntoResource<DiskHandleKind>>(disk: T) -> LayerOrDisk {
2443            LayerOrDisk::Disk(disk.into_resource())
2444        }
2445        match disk_cli {
2446            &DiskCliKind::Memory(len) => {
2447                layers.push(layer(RamDiskLayerHandle {
2448                    len: Some(len),
2449                    sector_size: None,
2450                }));
2451            }
2452            DiskCliKind::File {
2453                path,
2454                create_with_len,
2455                direct,
2456            } => layers.push(LayerOrDisk::Disk(if let Some(size) = create_with_len {
2457                create_disk_type(
2458                    path,
2459                    *size,
2460                    OpenDiskOptions {
2461                        read_only: false,
2462                        direct: *direct,
2463                    },
2464                )
2465                .with_context(|| format!("failed to create {}", path.display()))?
2466            } else {
2467                open_disk_type(
2468                    path,
2469                    OpenDiskOptions {
2470                        read_only,
2471                        direct: *direct,
2472                    },
2473                )
2474                .await
2475                .with_context(|| format!("failed to open {}", path.display()))?
2476            })),
2477            DiskCliKind::Blob { kind, url } => {
2478                layers.push(disk(disk_backend_resources::BlobDiskHandle {
2479                    url: url.to_owned(),
2480                    format: match kind {
2481                        cli_args::BlobKind::Flat => disk_backend_resources::BlobDiskFormat::Flat,
2482                        cli_args::BlobKind::Vhd1 => {
2483                            disk_backend_resources::BlobDiskFormat::FixedVhd1
2484                        }
2485                    },
2486                }))
2487            }
2488            DiskCliKind::MemoryDiff(inner) => {
2489                layers.push(layer(RamDiskLayerHandle {
2490                    len: None,
2491                    sector_size: None,
2492                }));
2493                disk_open_inner(inner, true, layers).await?;
2494            }
2495            DiskCliKind::PersistentReservationsWrapper(inner) => {
2496                layers.push(disk(disk_backend_resources::DiskWithReservationsHandle(
2497                    disk_open(inner, read_only).await?,
2498                )))
2499            }
2500            DiskCliKind::DelayDiskWrapper {
2501                delay_ms,
2502                disk: inner,
2503            } => layers.push(disk(DelayDiskHandle {
2504                delay: CellUpdater::new(Duration::from_millis(*delay_ms)).cell(),
2505                disk: disk_open(inner, read_only).await?,
2506            })),
2507            DiskCliKind::Crypt {
2508                disk: inner,
2509                cipher,
2510                key_file,
2511            } => layers.push(disk(disk_crypt_resources::DiskCryptHandle {
2512                disk: disk_open(inner, read_only).await?,
2513                cipher: match cipher {
2514                    cli_args::DiskCipher::XtsAes256 => disk_crypt_resources::Cipher::XtsAes256,
2515                },
2516                key: fs_err::read(key_file).context("failed to read key file")?,
2517            })),
2518            DiskCliKind::Sqlite {
2519                path,
2520                create_with_len,
2521            } => {
2522                // FUTURE: this code should be responsible for opening
2523                // file-handle(s) itself, and passing them into sqlite via a custom
2524                // vfs. For now though - simply check if the file exists or not, and
2525                // perform early validation of filesystem-level create options.
2526                match (create_with_len.is_some(), path.exists()) {
2527                    (true, true) => anyhow::bail!(
2528                        "cannot create new sqlite disk at {} - file already exists",
2529                        path.display()
2530                    ),
2531                    (false, false) => anyhow::bail!(
2532                        "cannot open sqlite disk at {} - file not found",
2533                        path.display()
2534                    ),
2535                    _ => {}
2536                }
2537
2538                layers.push(layer(SqliteDiskLayerHandle {
2539                    dbhd_path: path.display().to_string(),
2540                    format_dbhd: create_with_len.map(|len| {
2541                        disk_backend_resources::layer::SqliteDiskLayerFormatParams {
2542                            logically_read_only: false,
2543                            len: Some(len),
2544                        }
2545                    }),
2546                }));
2547            }
2548            DiskCliKind::SqliteDiff { path, create, disk } => {
2549                // FUTURE: this code should be responsible for opening
2550                // file-handle(s) itself, and passing them into sqlite via a custom
2551                // vfs. For now though - simply check if the file exists or not, and
2552                // perform early validation of filesystem-level create options.
2553                match (create, path.exists()) {
2554                    (true, true) => anyhow::bail!(
2555                        "cannot create new sqlite disk at {} - file already exists",
2556                        path.display()
2557                    ),
2558                    (false, false) => anyhow::bail!(
2559                        "cannot open sqlite disk at {} - file not found",
2560                        path.display()
2561                    ),
2562                    _ => {}
2563                }
2564
2565                layers.push(layer(SqliteDiskLayerHandle {
2566                    dbhd_path: path.display().to_string(),
2567                    format_dbhd: create.then_some(
2568                        disk_backend_resources::layer::SqliteDiskLayerFormatParams {
2569                            logically_read_only: false,
2570                            len: None,
2571                        },
2572                    ),
2573                }));
2574                disk_open_inner(disk, true, layers).await?;
2575            }
2576            DiskCliKind::AutoCacheSqlite {
2577                cache_path,
2578                key,
2579                disk,
2580            } => {
2581                layers.push(LayerOrDisk::Layer(DiskLayerDescription {
2582                    read_cache: true,
2583                    write_through: false,
2584                    layer: SqliteAutoCacheDiskLayerHandle {
2585                        cache_path: cache_path.clone(),
2586                        cache_key: key.clone(),
2587                    }
2588                    .into_resource(),
2589                }));
2590                disk_open_inner(disk, read_only, layers).await?;
2591            }
2592        }
2593        Ok(())
2594    })
2595}
2596
2597/// Get the system page size.
2598pub(crate) fn system_page_size() -> u32 {
2599    sparse_mmap::SparseMapping::page_size() as u32
2600}
2601
2602/// The guest architecture string, derived from the compile-time `guest_arch` cfg.
2603pub(crate) const GUEST_ARCH: &str = if cfg!(guest_arch = "x86_64") {
2604    "x86_64"
2605} else {
2606    "aarch64"
2607};
2608
2609/// Open a snapshot directory and validate it against the current VM config.
2610/// Returns the shared memory fd (from memory.bin) and the saved device state.
2611fn prepare_snapshot_restore(
2612    snapshot_dir: &Path,
2613    opt: &Options,
2614) -> anyhow::Result<(
2615    openvmm_defs::worker::SharedMemoryFd,
2616    mesh::payload::message::ProtobufMessage,
2617)> {
2618    let (manifest, state_bytes) = openvmm_helpers::snapshot::read_snapshot(snapshot_dir)?;
2619
2620    // Validate manifest against current VM config.
2621    openvmm_helpers::snapshot::validate_manifest(
2622        &manifest,
2623        GUEST_ARCH,
2624        opt.memory_size(),
2625        opt.processors,
2626        system_page_size(),
2627    )?;
2628
2629    // Open memory.bin (existing file, no create, no resize).
2630    let memory_file = fs_err::OpenOptions::new()
2631        .read(true)
2632        .write(true)
2633        .open(snapshot_dir.join("memory.bin"))?;
2634
2635    // Validate file size matches expected memory size.
2636    let file_size = memory_file.metadata()?.len();
2637    if file_size != manifest.memory_size_bytes {
2638        anyhow::bail!(
2639            "memory.bin size ({file_size} bytes) doesn't match manifest ({} bytes)",
2640            manifest.memory_size_bytes,
2641        );
2642    }
2643
2644    let shared_memory_fd =
2645        openvmm_helpers::shared_memory::file_to_shared_memory_fd(memory_file.into())?;
2646
2647    // Reconstruct ProtobufMessage from the saved state bytes.
2648    // The save side wrote mesh::payload::encode(ProtobufMessage), so we decode
2649    // back to ProtobufMessage.
2650    let state_msg: mesh::payload::message::ProtobufMessage = mesh::payload::decode(&state_bytes)
2651        .context("failed to decode saved state from snapshot")?;
2652
2653    Ok((shared_memory_fd, state_msg))
2654}
2655
2656fn do_main(pidfile_guard: &mut Option<pidfile::Pidfile>) -> anyhow::Result<i32> {
2657    #[cfg(windows)]
2658    pal::windows::disable_hard_error_dialog();
2659
2660    tracing_init::enable_tracing()?;
2661
2662    // Try to run as a worker host.
2663    // On success the worker runs to completion and then exits the process (does
2664    // not return). Any worker host setup errors are return and bubbled up.
2665    meshworker::run_vmm_mesh_host()?;
2666
2667    let opt = cli_args::parse_options();
2668    if let Some(path) = &opt.write_saved_state_proto {
2669        mesh::payload::protofile::DescriptorWriter::new(vmcore::save_restore::saved_state_roots())
2670            .write_to_path(path)
2671            .context("failed to write protobuf descriptors")?;
2672        return Ok(0);
2673    }
2674
2675    if let Some(ref path) = opt.pidfile {
2676        *pidfile_guard = Some(pidfile::Pidfile::new(path).context("failed to create pidfile")?);
2677    }
2678
2679    if let Some(path) = opt.relay_console_path {
2680        let console_title = opt.relay_console_title.unwrap_or_default();
2681        return console_relay::relay_console(&path, console_title.as_str()).map(|()| 0);
2682    }
2683
2684    #[cfg(any(feature = "grpc", feature = "ttrpc"))]
2685    {
2686        let rpc = opt
2687            .rpc
2688            .as_ref()
2689            .map(|rpc| {
2690                let transport = match rpc.transport {
2691                    cli_args::RpcTransportCli::Auto => ttrpc::RpcTransport::Auto,
2692                    cli_args::RpcTransportCli::Ttrpc => ttrpc::RpcTransport::Ttrpc,
2693                    cli_args::RpcTransportCli::Grpc => ttrpc::RpcTransport::Grpc,
2694                };
2695                (rpc.path.as_path(), transport)
2696            })
2697            .or_else(|| {
2698                opt.ttrpc
2699                    .as_deref()
2700                    .map(|p| (p, ttrpc::RpcTransport::Ttrpc))
2701            })
2702            .or_else(|| opt.grpc.as_deref().map(|p| (p, ttrpc::RpcTransport::Grpc)));
2703
2704        if let Some((path, transport)) = rpc {
2705            return block_on(async {
2706                let _ = std::fs::remove_file(path);
2707                let listener =
2708                    unix_socket::UnixListener::bind(path).context("failed to bind to socket")?;
2709
2710                // This is a local launch
2711                let mut handle =
2712                    mesh_worker::launch_local_worker::<ttrpc::TtrpcWorker>(ttrpc::Parameters {
2713                        listener,
2714                        transport,
2715                    })
2716                    .await?;
2717
2718                tracing::info!(%transport, path = %path.display(), "listening");
2719
2720                // Signal the parent process that the server is ready.
2721                pal::close_stdout().context("failed to close stdout")?;
2722
2723                handle.join().await?;
2724
2725                Ok(0)
2726            });
2727        }
2728    }
2729
2730    DefaultPool::run_with(async |driver| run_control(&driver, opt).await)
2731}
2732
2733fn new_hvsock_service_id(port: u32) -> Guid {
2734    // This GUID is an embedding of the AF_VSOCK port into an
2735    // AF_HYPERV service ID.
2736    Guid {
2737        data1: port,
2738        .."00000000-facb-11e6-bd58-64006a7986d3".parse().unwrap()
2739    }
2740}
2741
2742async fn run_control(driver: &DefaultDriver, opt: Options) -> anyhow::Result<i32> {
2743    let mut mesh = Some(VmmMesh::new(&driver, opt.single_process)?);
2744    let result = run_control_inner(driver, &mut mesh, opt).await;
2745    // If setup failed before the mesh was handed to the controller, shut it
2746    // down so the child host process exits cleanly without noisy logs.
2747    if let Some(mesh) = mesh {
2748        mesh.shutdown().await;
2749    }
2750    result
2751}
2752
2753async fn run_control_inner(
2754    driver: &DefaultDriver,
2755    mesh_slot: &mut Option<VmmMesh>,
2756    opt: Options,
2757) -> anyhow::Result<i32> {
2758    let mesh = mesh_slot.as_ref().unwrap();
2759    let (mut vm_config, mut resources) = vm_config_from_command_line(driver, mesh, &opt).await?;
2760
2761    let mut vnc_worker = None;
2762    if opt.gfx || opt.vnc.vnc {
2763        // Parse the listen address. Try as a full SocketAddr (host:port) first;
2764        // fall back to a bare IP, using the configured port.
2765        let addr: std::net::SocketAddr = if let Ok(sa) =
2766            opt.vnc.vnc_listen.parse::<std::net::SocketAddr>()
2767        {
2768            sa
2769        } else {
2770            let ip: std::net::IpAddr = opt.vnc.vnc_listen.parse().with_context(|| {
2771                format!(
2772                    "invalid VNC listen address: {} (expected IP address or socket address like [::1]:5900)",
2773                    opt.vnc.vnc_listen
2774                )
2775            })?;
2776            std::net::SocketAddr::new(ip, opt.vnc.vnc_port)
2777        };
2778
2779        let socket = socket2::Socket::new(
2780            if addr.is_ipv6() {
2781                socket2::Domain::IPV6
2782            } else {
2783                socket2::Domain::IPV4
2784            },
2785            socket2::Type::STREAM,
2786            None,
2787        )
2788        .with_context(|| format!("creating VNC socket for {}", addr))?;
2789
2790        if addr.is_ipv6() {
2791            if let Err(e) = socket.set_only_v6(false) {
2792                tracing::warn!(
2793                    error = %e,
2794                    "failed to enable dual-stack on IPv6 VNC socket, IPv4 clients may not be able to connect"
2795                );
2796            }
2797        }
2798        socket.set_reuse_address(true)?;
2799        socket
2800            .bind(&addr.into())
2801            .with_context(|| format!("binding VNC socket to {}", addr))?;
2802        socket
2803            .listen(128)
2804            .with_context(|| format!("listening on VNC socket {}", addr))?;
2805        let listener: TcpListener = socket.into();
2806
2807        if !addr.ip().is_loopback() {
2808            tracing::warn!(
2809                address = %addr,
2810                "VNC server listening on non-localhost address without authentication"
2811            );
2812        }
2813
2814        let input_send = vm_config.input.sender();
2815        let framebuffer = resources
2816            .framebuffer_access
2817            .take()
2818            .expect("synth video enabled");
2819
2820        let vnc_host = mesh
2821            .make_host("vnc", None)
2822            .await
2823            .context("spawning vnc process failed")?;
2824
2825        vnc_worker = Some(
2826            vnc_host
2827                .launch_worker(
2828                    vnc_worker_defs::VNC_WORKER_TCP,
2829                    VncParameters {
2830                        listener,
2831                        framebuffer,
2832                        input_send,
2833                        dirty_recv: resources.dirty_rect_recv.take(),
2834                        max_clients: opt.vnc.vnc_max_clients,
2835                        evict_oldest: opt.vnc.vnc_evict_oldest,
2836                    },
2837                )
2838                .await?,
2839        )
2840    }
2841
2842    // spin up the debug worker
2843    let gdb_worker = if let Some(port) = opt.gdb {
2844        let listener = TcpListener::bind(format!("127.0.0.1:{}", port))
2845            .with_context(|| format!("binding to gdb port {}", port))?;
2846
2847        let (req_tx, req_rx) = mesh::channel();
2848        vm_config.debugger_rpc = Some(req_rx);
2849
2850        let gdb_host = mesh
2851            .make_host("gdb", None)
2852            .await
2853            .context("spawning gdbstub process failed")?;
2854
2855        Some(
2856            gdb_host
2857                .launch_worker(
2858                    debug_worker_defs::DEBUGGER_WORKER,
2859                    debug_worker_defs::DebuggerParameters {
2860                        listener,
2861                        req_chan: req_tx,
2862                        vp_count: vm_config.processor_topology.proc_count,
2863                        target_arch: if cfg!(guest_arch = "x86_64") {
2864                            debug_worker_defs::TargetArch::X86_64
2865                        } else {
2866                            debug_worker_defs::TargetArch::Aarch64
2867                        },
2868                    },
2869                )
2870                .await
2871                .context("failed to launch gdbstub worker")?,
2872        )
2873    } else {
2874        None
2875    };
2876
2877    // spin up the VM
2878    let (vm_rpc, rpc_recv) = mesh::channel();
2879    let (notify_send, notify_recv) = mesh::channel();
2880    let vm_worker = {
2881        let vm_host = mesh.make_host("vm", opt.log_file.clone()).await?;
2882
2883        let (shared_memory, saved_state) = if let Some(snapshot_dir) = &opt.restore_snapshot {
2884            let (fd, state_msg) = prepare_snapshot_restore(snapshot_dir, &opt)?;
2885            (Some(fd), Some(state_msg))
2886        } else {
2887            let shared_memory = opt
2888                .memory_backing_file()
2889                .map(|path| {
2890                    openvmm_helpers::shared_memory::open_memory_backing_file(
2891                        path,
2892                        opt.memory_size(),
2893                    )
2894                })
2895                .transpose()?;
2896            (shared_memory, None)
2897        };
2898
2899        let params = VmWorkerParameters {
2900            hypervisor: match &opt.hypervisor {
2901                Some(name) => openvmm_helpers::hypervisor::hypervisor_resource(name)?,
2902                None => openvmm_helpers::hypervisor::choose_hypervisor()?,
2903            },
2904            cfg: vm_config,
2905            saved_state,
2906            shared_memory,
2907            rpc: rpc_recv,
2908            notify: notify_send,
2909        };
2910        vm_host
2911            .launch_worker(VM_WORKER, params)
2912            .await
2913            .context("failed to launch vm worker")?
2914    };
2915
2916    if opt.restore_snapshot.is_some() {
2917        tracing::info!("restoring VM from snapshot");
2918    }
2919
2920    if !opt.paused {
2921        vm_rpc.call(VmRpc::Resume, ()).await?;
2922    }
2923
2924    let paravisor_diag = Arc::new(diag_client::DiagClient::from_dialer(
2925        driver.clone(),
2926        DiagDialer {
2927            driver: driver.clone(),
2928            vm_rpc: vm_rpc.clone(),
2929            openhcl_vtl: if opt.vtl2 {
2930                DeviceVtl::Vtl2
2931            } else {
2932                DeviceVtl::Vtl0
2933            },
2934        },
2935    ));
2936
2937    let diag_inspector = DiagInspector::new(driver.clone(), paravisor_diag.clone());
2938
2939    // Create channels between the REPL and VmController.
2940    let (vm_controller_send, vm_controller_recv) = mesh::channel();
2941    let (vm_controller_event_send, vm_controller_event_recv) = mesh::channel();
2942
2943    let has_vtl2 = resources.vtl2_settings.is_some();
2944    let serial_driver = resources
2945        .serial_driver
2946        .take()
2947        .expect("serial driver must outlive serial resources");
2948
2949    // Build the VmController with exclusive resources.
2950    let controller = vm_controller::VmController {
2951        mesh: mesh_slot.take().unwrap(),
2952        vm_worker,
2953        vnc_worker,
2954        gdb_worker,
2955        diag_inspector: Some(diag_inspector),
2956        vtl2_settings: resources.vtl2_settings,
2957        ged_rpc: resources.ged_rpc.clone(),
2958        vm_rpc: vm_rpc.clone(),
2959        paravisor_diag: Some(paravisor_diag),
2960        igvm_path: opt.igvm.clone(),
2961        memory_backing_file: opt.memory_backing_file().cloned(),
2962        memory: opt.memory_size(),
2963        processors: opt.processors,
2964        log_file: opt.log_file.clone(),
2965        crash_dump_path: opt.crash_dump_path.clone(),
2966        guest_power_actions: vm_controller::GuestPowerActions {
2967            shutdown: opt.guest_shutdown_action,
2968            reset: opt.guest_reset_action,
2969            crash: opt.guest_crash_action,
2970            watchdog: opt.guest_watchdog_action,
2971        },
2972    };
2973
2974    // Spawn the VmController as a task.
2975    let controller_task = driver.spawn(
2976        "vm-controller",
2977        controller.run(vm_controller_recv, vm_controller_event_send, notify_recv),
2978    );
2979
2980    // Run the REPL with shareable resources.
2981    let repl_result = repl::run_repl(
2982        driver,
2983        repl::ReplResources {
2984            vm_rpc,
2985            vm_controller: vm_controller_send,
2986            vm_controller_events: vm_controller_event_recv,
2987            scsi_rpc: resources.scsi_rpc,
2988            nvme_vtl2_rpc: resources.nvme_vtl2_rpc,
2989            consomme_rpc: resources.consomme_rpc,
2990            shutdown_ic: resources.shutdown_ic,
2991            kvp_ic: resources.kvp_ic,
2992            console_in: resources.console_in,
2993            has_vtl2,
2994        },
2995    )
2996    .await;
2997
2998    // Wait for the controller task to finish (it stops the VM worker and
2999    // shuts down the mesh).
3000    controller_task.await;
3001    drop(serial_driver);
3002
3003    // run_repl returns the exit status: the code the guest drove via an opt-in
3004    // exit (VmControllerEvent::ExitRequested), or 0 when the VM stopped normally.
3005    repl_result
3006}
3007
3008struct DiagDialer {
3009    driver: DefaultDriver,
3010    vm_rpc: mesh::Sender<VmRpc>,
3011    openhcl_vtl: DeviceVtl,
3012}
3013
3014impl mesh_rpc::client::Dial for DiagDialer {
3015    type Stream = PolledSocket<unix_socket::UnixStream>;
3016
3017    async fn dial(&mut self) -> io::Result<Self::Stream> {
3018        let service_id = new_hvsock_service_id(1);
3019        let socket = self
3020            .vm_rpc
3021            .call_failable(
3022                VmRpc::ConnectHvsock,
3023                (
3024                    CancelContext::new().with_timeout(Duration::from_secs(2)),
3025                    service_id,
3026                    self.openhcl_vtl,
3027                ),
3028            )
3029            .await
3030            .map_err(io::Error::other)?;
3031
3032        PolledSocket::new(&self.driver, socket)
3033    }
3034}
3035
3036/// An object that implements [`InspectMut`] by sending an inspect request over
3037/// TTRPC to the guest (typically the paravisor running in VTL2), then stitching
3038/// the response back into the inspect tree.
3039///
3040/// This also caches the TTRPC connection to the guest so that only the first
3041/// inspect request has to wait for the connection to be established.
3042pub(crate) struct DiagInspector(DiagInspectorInner);
3043
3044enum DiagInspectorInner {
3045    NotStarted(DefaultDriver, Arc<diag_client::DiagClient>),
3046    Started {
3047        send: mesh::Sender<inspect::Deferred>,
3048        _task: Task<()>,
3049    },
3050    Invalid,
3051}
3052
3053impl DiagInspector {
3054    pub fn new(driver: DefaultDriver, diag_client: Arc<diag_client::DiagClient>) -> Self {
3055        Self(DiagInspectorInner::NotStarted(driver, diag_client))
3056    }
3057
3058    fn start(&mut self) -> &mesh::Sender<inspect::Deferred> {
3059        loop {
3060            match self.0 {
3061                DiagInspectorInner::NotStarted { .. } => {
3062                    let DiagInspectorInner::NotStarted(driver, client) =
3063                        std::mem::replace(&mut self.0, DiagInspectorInner::Invalid)
3064                    else {
3065                        unreachable!()
3066                    };
3067                    let (send, recv) = mesh::channel();
3068                    let task = driver.clone().spawn("diag-inspect", async move {
3069                        Self::run(&client, recv).await
3070                    });
3071
3072                    self.0 = DiagInspectorInner::Started { send, _task: task };
3073                }
3074                DiagInspectorInner::Started { ref send, .. } => break send,
3075                DiagInspectorInner::Invalid => unreachable!(),
3076            }
3077        }
3078    }
3079
3080    async fn run(
3081        diag_client: &diag_client::DiagClient,
3082        mut recv: mesh::Receiver<inspect::Deferred>,
3083    ) {
3084        while let Some(deferred) = recv.next().await {
3085            let info = deferred.external_request();
3086            let result = match info.request_type {
3087                inspect::ExternalRequestType::Inspect { depth } => {
3088                    if depth == 0 {
3089                        Ok(inspect::Node::Unevaluated)
3090                    } else {
3091                        // TODO: Support taking timeouts from the command line
3092                        diag_client
3093                            .inspect(info.path, Some(depth - 1), Some(Duration::from_secs(1)))
3094                            .await
3095                    }
3096                }
3097                inspect::ExternalRequestType::Update { value } => {
3098                    (diag_client.update(info.path, value).await).map(inspect::Node::Value)
3099                }
3100            };
3101            deferred.complete_external(
3102                result.unwrap_or_else(|err| {
3103                    inspect::Node::Failed(inspect::Error::Mesh(format!("{err:#}")))
3104                }),
3105                inspect::SensitivityLevel::Unspecified,
3106            )
3107        }
3108    }
3109}
3110
3111impl InspectMut for DiagInspector {
3112    fn inspect_mut(&mut self, req: inspect::Request<'_>) {
3113        self.start().send(req.defer());
3114    }
3115}
3116
3117#[cfg(test)]
3118mod tests {
3119    use super::*;
3120    use clap::Parser;
3121    use test_with_tracing::test;
3122
3123    #[test]
3124    fn maps_igvm_personalities_to_chipsets() {
3125        for (args, expected) in [
3126            (
3127                vec![
3128                    "openvmm",
3129                    "--igvm",
3130                    "guest.igvm",
3131                    "--igvm-personality",
3132                    "uefi",
3133                ],
3134                BaseChipsetType::HypervGen2Uefi,
3135            ),
3136            (
3137                vec![
3138                    "openvmm",
3139                    "--igvm",
3140                    "guest.igvm",
3141                    "--igvm-personality",
3142                    "linux-direct",
3143                ],
3144                BaseChipsetType::UnenlightenedLinuxDirect,
3145            ),
3146            (
3147                vec![
3148                    "openvmm",
3149                    "--igvm",
3150                    "guest.igvm",
3151                    "--igvm-personality",
3152                    "linux-direct",
3153                    "--hv",
3154                ],
3155                BaseChipsetType::HyperVGen2LinuxDirect,
3156            ),
3157            (
3158                vec![
3159                    "openvmm",
3160                    "--igvm",
3161                    "guest.igvm",
3162                    "--igvm-personality",
3163                    "linux-direct",
3164                    "--isolation",
3165                    "snp",
3166                ],
3167                BaseChipsetType::EnlightenedLinuxDirect,
3168            ),
3169            (
3170                vec!["openvmm", "--igvm", "guest.igvm", "--hv", "--vtl2"],
3171                BaseChipsetType::HclHost,
3172            ),
3173        ] {
3174            let opt = Options::try_parse_from(args).unwrap();
3175            assert!(
3176                std::mem::discriminant(&base_chipset_type(&opt))
3177                    == std::mem::discriminant(&expected)
3178            );
3179        }
3180    }
3181}