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