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