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