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