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