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