Skip to main content

openvmm_entry/
lib.rs

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