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