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