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