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