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