Skip to main content

openvmm_entry/
lib.rs

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