Skip to main content

openvmm_entry/
lib.rs

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