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