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