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 topology_arch = openvmm_defs::config::ArchTopologyConfig::Aarch64(
1379        openvmm_defs::config::Aarch64TopologyConfig {
1380            // TODO: allow this to be configured from the command line
1381            gic_config: None,
1382            pmu_gsiv: openvmm_defs::config::PmuGsivConfig::Platform,
1383            gic_msi: match opt.gic_msi {
1384                cli_args::GicMsiCli::Auto => openvmm_defs::config::GicMsiConfig::Auto,
1385                cli_args::GicMsiCli::Its => openvmm_defs::config::GicMsiConfig::Its,
1386                cli_args::GicMsiCli::V2m => {
1387                    openvmm_defs::config::GicMsiConfig::V2m { spi_count: None }
1388                }
1389            },
1390        },
1391    );
1392    #[cfg(guest_arch = "x86_64")]
1393    let topology_arch =
1394        openvmm_defs::config::ArchTopologyConfig::X86(openvmm_defs::config::X86TopologyConfig {
1395            apic_id_offset: opt.apic_id_offset,
1396            x2apic: opt.x2apic,
1397        });
1398
1399    let with_isolation = if let Some(isolation) = &opt.isolation {
1400        // TODO: For now, isolation is only supported with VTL2.
1401        if !opt.vtl2 {
1402            anyhow::bail!("isolation is only currently supported with vtl2");
1403        }
1404
1405        // TODO: Alias map support is not yet implement with isolation.
1406        if !opt.no_alias_map {
1407            anyhow::bail!("alias map not supported with isolation");
1408        }
1409
1410        match isolation {
1411            cli_args::IsolationCli::Vbs => Some(openvmm_defs::config::IsolationType::Vbs),
1412        }
1413    } else {
1414        None
1415    };
1416
1417    if with_hv {
1418        let (shutdown_send, shutdown_recv) = mesh::channel();
1419        resources.shutdown_ic = Some(shutdown_send);
1420        let (kvp_send, kvp_recv) = mesh::channel();
1421        resources.kvp_ic = Some(kvp_send);
1422        vmbus_devices.extend(
1423            [
1424                hyperv_ic_resources::shutdown::ShutdownIcHandle {
1425                    recv: shutdown_recv,
1426                }
1427                .into_resource(),
1428                hyperv_ic_resources::kvp::KvpIcHandle { recv: kvp_recv }.into_resource(),
1429                hyperv_ic_resources::timesync::TimesyncIcHandle.into_resource(),
1430            ]
1431            .map(|r| (DeviceVtl::Vtl0, r)),
1432        );
1433    }
1434
1435    if let Some(hive_path) = &opt.imc {
1436        let file = fs_err::File::open(hive_path).context("failed to open imc hive")?;
1437        vmbus_devices.push((
1438            DeviceVtl::Vtl0,
1439            vmbfs_resources::VmbfsImcDeviceHandle { file: file.into() }.into_resource(),
1440        ));
1441    }
1442
1443    let mut virtio_devices = Vec::new();
1444    let mut add_virtio_device = |bus, resource: Resource<VirtioDeviceHandle>| {
1445        let bus = match bus {
1446            VirtioBusCli::Auto => {
1447                // Use VPCI when possible (currently only on Windows and macOS due
1448                // to KVM backend limitations).
1449                if with_hv && (cfg!(windows) || cfg!(target_os = "macos")) {
1450                    None
1451                } else {
1452                    Some(VirtioBus::Pci)
1453                }
1454            }
1455            VirtioBusCli::Mmio => Some(VirtioBus::Mmio),
1456            VirtioBusCli::Pci => Some(VirtioBus::Pci),
1457            VirtioBusCli::Vpci => None,
1458        };
1459        if let Some(bus) = bus {
1460            virtio_devices.push((bus, resource));
1461        } else {
1462            vpci_devices.push(VpciDeviceConfig {
1463                vtl: DeviceVtl::Vtl0,
1464                instance_id: Guid::new_random(),
1465                resource: VirtioPciDeviceHandle(resource).into_resource(),
1466            });
1467        }
1468    };
1469
1470    for cli_cfg in &opt.virtio_net {
1471        if cli_cfg.underhill {
1472            anyhow::bail!("use --net uh:[...] to add underhill NICs")
1473        }
1474        let vport = parse_endpoint(cli_cfg, &mut nic_index, &mut resources)?;
1475        let resource = virtio_resources::net::VirtioNetHandle {
1476            max_queues: vport.max_queues,
1477            mac_address: vport.mac_address,
1478            endpoint: vport.endpoint,
1479        }
1480        .into_resource();
1481        if let Some(pcie_port) = &cli_cfg.pcie_port {
1482            pcie_devices.push(PcieDeviceConfig {
1483                port_name: pcie_port.clone(),
1484                resource: VirtioPciDeviceHandle(resource).into_resource(),
1485            });
1486        } else {
1487            add_virtio_device(VirtioBusCli::Auto, resource);
1488        }
1489    }
1490
1491    for args in &opt.virtio_fs {
1492        let resource: Resource<VirtioDeviceHandle> = virtio_resources::fs::VirtioFsHandle {
1493            tag: args.tag.clone(),
1494            fs: virtio_resources::fs::VirtioFsBackend::HostFs {
1495                root_path: args.path.clone(),
1496                mount_options: args.options.clone(),
1497            },
1498        }
1499        .into_resource();
1500        if let Some(pcie_port) = &args.pcie_port {
1501            pcie_devices.push(PcieDeviceConfig {
1502                port_name: pcie_port.clone(),
1503                resource: VirtioPciDeviceHandle(resource).into_resource(),
1504            });
1505        } else {
1506            add_virtio_device(opt.virtio_fs_bus, resource);
1507        }
1508    }
1509
1510    for args in &opt.virtio_fs_shmem {
1511        let resource: Resource<VirtioDeviceHandle> = virtio_resources::fs::VirtioFsHandle {
1512            tag: args.tag.clone(),
1513            fs: virtio_resources::fs::VirtioFsBackend::SectionFs {
1514                root_path: args.path.clone(),
1515            },
1516        }
1517        .into_resource();
1518        if let Some(pcie_port) = &args.pcie_port {
1519            pcie_devices.push(PcieDeviceConfig {
1520                port_name: pcie_port.clone(),
1521                resource: VirtioPciDeviceHandle(resource).into_resource(),
1522            });
1523        } else {
1524            add_virtio_device(opt.virtio_fs_bus, resource);
1525        }
1526    }
1527
1528    for args in &opt.virtio_9p {
1529        let resource: Resource<VirtioDeviceHandle> = virtio_resources::p9::VirtioPlan9Handle {
1530            tag: args.tag.clone(),
1531            root_path: args.path.clone(),
1532            debug: opt.virtio_9p_debug,
1533        }
1534        .into_resource();
1535        if let Some(pcie_port) = &args.pcie_port {
1536            pcie_devices.push(PcieDeviceConfig {
1537                port_name: pcie_port.clone(),
1538                resource: VirtioPciDeviceHandle(resource).into_resource(),
1539            });
1540        } else {
1541            add_virtio_device(VirtioBusCli::Auto, resource);
1542        }
1543    }
1544
1545    if let Some(pmem_args) = &opt.virtio_pmem {
1546        let resource: Resource<VirtioDeviceHandle> = virtio_resources::pmem::VirtioPmemHandle {
1547            path: pmem_args.path.clone(),
1548        }
1549        .into_resource();
1550        if let Some(pcie_port) = &pmem_args.pcie_port {
1551            pcie_devices.push(PcieDeviceConfig {
1552                port_name: pcie_port.clone(),
1553                resource: VirtioPciDeviceHandle(resource).into_resource(),
1554            });
1555        } else {
1556            add_virtio_device(VirtioBusCli::Auto, resource);
1557        }
1558    }
1559
1560    if opt.virtio_rng {
1561        let resource: Resource<VirtioDeviceHandle> =
1562            virtio_resources::rng::VirtioRngHandle.into_resource();
1563        if let Some(pcie_port) = &opt.virtio_rng_pcie_port {
1564            pcie_devices.push(PcieDeviceConfig {
1565                port_name: pcie_port.clone(),
1566                resource: VirtioPciDeviceHandle(resource).into_resource(),
1567            });
1568        } else {
1569            add_virtio_device(opt.virtio_rng_bus, resource);
1570        }
1571    }
1572
1573    if let Some(backend) = virtio_console_backend {
1574        let resource: Resource<VirtioDeviceHandle> =
1575            virtio_resources::console::VirtioConsoleHandle { backend }.into_resource();
1576        if let Some(pcie_port) = &opt.virtio_console_pcie_port {
1577            pcie_devices.push(PcieDeviceConfig {
1578                port_name: pcie_port.clone(),
1579                resource: VirtioPciDeviceHandle(resource).into_resource(),
1580            });
1581        } else {
1582            add_virtio_device(VirtioBusCli::Auto, resource);
1583        }
1584    }
1585
1586    // Handle --vhost-user arguments.
1587    #[cfg(target_os = "linux")]
1588    for vhost_cli in &opt.vhost_user {
1589        let stream =
1590            unix_socket::UnixStream::connect(&vhost_cli.socket_path).with_context(|| {
1591                format!(
1592                    "failed to connect to vhost-user socket: {}",
1593                    vhost_cli.socket_path
1594                )
1595            })?;
1596
1597        use crate::cli_args::VhostUserDeviceTypeCli;
1598        let resource: Resource<VirtioDeviceHandle> = match vhost_cli.device_type {
1599            VhostUserDeviceTypeCli::Fs {
1600                ref tag,
1601                num_queues,
1602                queue_size,
1603            } => virtio_resources::vhost_user::VhostUserFsHandle {
1604                socket: stream.into(),
1605                tag: tag.clone(),
1606                num_queues,
1607                queue_size,
1608            }
1609            .into_resource(),
1610            VhostUserDeviceTypeCli::Blk {
1611                num_queues,
1612                queue_size,
1613            } => virtio_resources::vhost_user::VhostUserBlkHandle {
1614                socket: stream.into(),
1615                num_queues,
1616                queue_size,
1617            }
1618            .into_resource(),
1619            VhostUserDeviceTypeCli::Other {
1620                device_id,
1621                ref queue_sizes,
1622            } => virtio_resources::vhost_user::VhostUserGenericHandle {
1623                socket: stream.into(),
1624                device_id,
1625                queue_sizes: queue_sizes.clone(),
1626            }
1627            .into_resource(),
1628        };
1629        if let Some(pcie_port) = &vhost_cli.pcie_port {
1630            pcie_devices.push(PcieDeviceConfig {
1631                port_name: pcie_port.clone(),
1632                resource: VirtioPciDeviceHandle(resource).into_resource(),
1633            });
1634        } else {
1635            add_virtio_device(VirtioBusCli::Auto, resource);
1636        }
1637    }
1638
1639    if let Some(vsock_path) = &opt.virtio_vsock_path {
1640        let listener = vsock_listener(Some(vsock_path))?.unwrap();
1641        add_virtio_device(
1642            VirtioBusCli::Auto,
1643            virtio_resources::vsock::VirtioVsockHandle {
1644                // The guest CID does not matter since the UDS relay does not use it. It just needs
1645                // to be some non-reserved value for the guest to use.
1646                guest_cid: 0x3,
1647                base_path: vsock_path.clone(),
1648                listener,
1649            }
1650            .into_resource(),
1651        );
1652    }
1653
1654    let mut cfg = Config {
1655        chipset,
1656        load_mode,
1657        floppy_disks,
1658        pcie_root_complexes,
1659        #[cfg(target_os = "linux")]
1660        pcie_devices: {
1661            let mut devs = pcie_devices;
1662            devs.extend(vfio_pcie_devices);
1663            devs
1664        },
1665        #[cfg(not(target_os = "linux"))]
1666        pcie_devices,
1667        pcie_switches,
1668        vpci_devices,
1669        ide_disks: Vec::new(),
1670        memory: MemoryConfig {
1671            mem_size: if let Some(ref sizes) = opt.numa_memory {
1672                sizes
1673                    .iter()
1674                    .try_fold(0u64, |acc, &s| acc.checked_add(s))
1675                    .context("numa memory sizes overflow")?
1676            } else {
1677                opt.memory_size()
1678            },
1679            prefetch_memory: opt.prefetch_memory(),
1680            private_memory: opt.private_memory(),
1681            transparent_hugepages: opt.transparent_hugepages(),
1682            hugepages: opt.memory.hugepages,
1683            hugepage_size: opt.memory.hugepage_size,
1684            numa_mem_sizes: opt.numa_memory.clone(),
1685        },
1686        processor_topology: ProcessorTopologyConfig {
1687            proc_count: opt.processors,
1688            vps_per_socket: opt.vps_per_socket,
1689            enable_smt: match opt.smt {
1690                cli_args::SmtConfigCli::Auto => None,
1691                cli_args::SmtConfigCli::Force => Some(true),
1692                cli_args::SmtConfigCli::Off => Some(false),
1693            },
1694            arch: Some(topology_arch),
1695        },
1696        hypervisor: HypervisorConfig {
1697            with_hv,
1698            with_vtl2: opt.vtl2.then_some(Vtl2Config {
1699                vtl0_alias_map: !opt.no_alias_map,
1700                late_map_vtl0_memory: match opt.late_map_vtl0_policy {
1701                    cli_args::Vtl0LateMapPolicyCli::Off => None,
1702                    cli_args::Vtl0LateMapPolicyCli::Log => Some(LateMapVtl0MemoryPolicy::Log),
1703                    cli_args::Vtl0LateMapPolicyCli::Halt => Some(LateMapVtl0MemoryPolicy::Halt),
1704                    cli_args::Vtl0LateMapPolicyCli::Exception => {
1705                        Some(LateMapVtl0MemoryPolicy::InjectException)
1706                    }
1707                },
1708            }),
1709            with_isolation,
1710        },
1711        #[cfg(windows)]
1712        kernel_vmnics,
1713        input: mesh::Receiver::new(),
1714        framebuffer,
1715        vga_firmware,
1716        vtl2_gfx: opt.vtl2_gfx,
1717        virtio_devices,
1718        vmbus: with_hv.then_some(VmbusConfig {
1719            vsock_listener: vtl0_vsock_listener,
1720            vsock_path: opt.vmbus_vsock_path.clone(),
1721            vtl2_redirect: opt.vmbus_redirect,
1722            vmbus_max_version: opt.vmbus_max_version,
1723            #[cfg(windows)]
1724            vmbusproxy_handle,
1725        }),
1726        vtl2_vmbus: (with_hv && opt.vtl2).then_some(VmbusConfig {
1727            vsock_listener: vtl2_vsock_listener,
1728            vsock_path: opt.vmbus_vtl2_vsock_path.clone(),
1729            ..Default::default()
1730        }),
1731        vmbus_devices,
1732        chipset_devices,
1733        pci_chipset_devices,
1734        chipset_capabilities: capabilities,
1735        layout: layout_config,
1736        #[cfg(windows)]
1737        vpci_resources,
1738        vmgs,
1739        secure_boot_enabled: opt.secure_boot,
1740        custom_uefi_vars,
1741        firmware_event_send: None,
1742        debugger_rpc: None,
1743        generation_id_recv: None,
1744        rtc_delta_milliseconds: 0,
1745        automatic_guest_reset: !opt.halt_on_reset,
1746        efi_diagnostics_log_level: {
1747            match opt.efi_diagnostics_log_level.unwrap_or_default() {
1748                EfiDiagnosticsLogLevelCli::Default => EfiDiagnosticsLogLevelType::Default,
1749                EfiDiagnosticsLogLevelCli::Info => EfiDiagnosticsLogLevelType::Info,
1750                EfiDiagnosticsLogLevelCli::Full => EfiDiagnosticsLogLevelType::Full,
1751            }
1752        },
1753    };
1754
1755    storage.build_config(&mut cfg, &mut resources, opt.scsi_sub_channels)?;
1756    Ok((cfg, resources))
1757}
1758
1759/// Gets the terminal to use for externally launched console windows.
1760pub(crate) fn openvmm_terminal_app() -> Option<PathBuf> {
1761    std::env::var_os("OPENVMM_TERM")
1762        .or_else(|| std::env::var_os("HVLITE_TERM"))
1763        .map(Into::into)
1764}
1765
1766// Tries to remove `path` if it is confirmed to be a Unix socket.
1767fn cleanup_socket(path: &Path) {
1768    #[cfg(windows)]
1769    let is_socket = pal::windows::fs::is_unix_socket(path).unwrap_or(false);
1770    #[cfg(not(windows))]
1771    let is_socket = path
1772        .metadata()
1773        .is_ok_and(|meta| std::os::unix::fs::FileTypeExt::is_socket(&meta.file_type()));
1774
1775    if is_socket {
1776        let _ = std::fs::remove_file(path);
1777    }
1778}
1779
1780#[cfg(windows)]
1781const DEFAULT_SWITCH: &str = "C08CB7B8-9B3C-408E-8E30-5E16A3AEB444";
1782
1783#[cfg(windows)]
1784fn new_switch_port(
1785    switch_id: &str,
1786) -> anyhow::Result<(
1787    openvmm_defs::config::SwitchPortId,
1788    vmswitch::kernel::SwitchPort,
1789)> {
1790    let id = vmswitch::kernel::SwitchPortId {
1791        switch: switch_id.parse().context("invalid switch id")?,
1792        port: Guid::new_random(),
1793    };
1794    let _ = vmswitch::hcn::Network::open(&id.switch)
1795        .with_context(|| format!("could not find switch {}", id.switch))?;
1796
1797    let port = vmswitch::kernel::SwitchPort::new(&id).context("failed to create switch port")?;
1798
1799    let id = openvmm_defs::config::SwitchPortId {
1800        switch: id.switch,
1801        port: id.port,
1802    };
1803    Ok((id, port))
1804}
1805
1806fn parse_endpoint(
1807    cli_cfg: &NicConfigCli,
1808    index: &mut usize,
1809    resources: &mut VmResources,
1810) -> anyhow::Result<NicConfig> {
1811    let _ = resources;
1812    let endpoint = match &cli_cfg.endpoint {
1813        EndpointConfigCli::Consomme { cidr, host_fwd } => {
1814            let ports = host_fwd
1815                .iter()
1816                .map(|fwd| {
1817                    use net_backend_resources::consomme::HostPortProtocol;
1818                    net_backend_resources::consomme::HostPortConfig {
1819                        protocol: match fwd.protocol {
1820                            cli_args::HostPortProtocolCli::Tcp => HostPortProtocol::Tcp,
1821                            cli_args::HostPortProtocolCli::Udp => HostPortProtocol::Udp,
1822                        },
1823                        host_address: fwd
1824                            .host_address
1825                            .map(net_backend_resources::consomme::HostIpAddress::from),
1826                        host_port: fwd.host_port,
1827                        guest_port: fwd.guest_port,
1828                    }
1829                })
1830                .collect();
1831            net_backend_resources::consomme::ConsommeHandle {
1832                cidr: cidr.clone(),
1833                ports,
1834            }
1835            .into_resource()
1836        }
1837        EndpointConfigCli::None => net_backend_resources::null::NullHandle.into_resource(),
1838        EndpointConfigCli::Dio { id } => {
1839            #[cfg(windows)]
1840            {
1841                let (port_id, port) = new_switch_port(id.as_deref().unwrap_or(DEFAULT_SWITCH))?;
1842                resources.switch_ports.push(port);
1843                net_backend_resources::dio::WindowsDirectIoHandle {
1844                    switch_port_id: net_backend_resources::dio::SwitchPortId {
1845                        switch: port_id.switch,
1846                        port: port_id.port,
1847                    },
1848                }
1849                .into_resource()
1850            }
1851
1852            #[cfg(not(windows))]
1853            {
1854                let _ = id;
1855                bail!("cannot use dio on non-windows platforms")
1856            }
1857        }
1858        EndpointConfigCli::Tap { name } => {
1859            #[cfg(target_os = "linux")]
1860            {
1861                let fd = net_tap::tap::open_tap(name)
1862                    .with_context(|| format!("failed to open TAP device '{name}'"))?;
1863                net_backend_resources::tap::TapHandle { fd }.into_resource()
1864            }
1865
1866            #[cfg(not(target_os = "linux"))]
1867            {
1868                let _ = name;
1869                bail!("TAP backend is only supported on Linux")
1870            }
1871        }
1872    };
1873
1874    // Pick a random MAC address.
1875    let mut mac_address = [0x00, 0x15, 0x5D, 0, 0, 0];
1876    getrandom::fill(&mut mac_address[3..]).expect("rng failure");
1877
1878    // Pick a fixed instance ID based on the index.
1879    const BASE_INSTANCE_ID: Guid = guid::guid!("00000000-da43-11ed-936a-00155d6db52f");
1880    let instance_id = Guid {
1881        data1: *index as u32,
1882        ..BASE_INSTANCE_ID
1883    };
1884    *index += 1;
1885
1886    Ok(NicConfig {
1887        vtl: cli_cfg.vtl,
1888        instance_id,
1889        endpoint,
1890        mac_address: mac_address.into(),
1891        max_queues: cli_cfg.max_queues,
1892        pcie_port: cli_cfg.pcie_port.clone(),
1893    })
1894}
1895
1896#[derive(Debug)]
1897struct NicConfig {
1898    vtl: DeviceVtl,
1899    instance_id: Guid,
1900    mac_address: MacAddress,
1901    endpoint: Resource<NetEndpointHandleKind>,
1902    max_queues: Option<u16>,
1903    pcie_port: Option<String>,
1904}
1905
1906impl NicConfig {
1907    fn into_netvsp_handle(self) -> (DeviceVtl, Resource<VmbusDeviceHandleKind>) {
1908        (
1909            self.vtl,
1910            netvsp_resources::NetvspHandle {
1911                instance_id: self.instance_id,
1912                mac_address: self.mac_address,
1913                endpoint: self.endpoint,
1914                max_queues: self.max_queues,
1915            }
1916            .into_resource(),
1917        )
1918    }
1919}
1920
1921enum LayerOrDisk {
1922    Layer(DiskLayerDescription),
1923    Disk(Resource<DiskHandleKind>),
1924}
1925
1926async fn disk_open(
1927    disk_cli: &DiskCliKind,
1928    read_only: bool,
1929) -> anyhow::Result<Resource<DiskHandleKind>> {
1930    let mut layers = Vec::new();
1931    disk_open_inner(disk_cli, read_only, &mut layers).await?;
1932    if layers.len() == 1 && matches!(layers[0], LayerOrDisk::Disk(_)) {
1933        let LayerOrDisk::Disk(disk) = layers.pop().unwrap() else {
1934            unreachable!()
1935        };
1936        Ok(disk)
1937    } else {
1938        Ok(Resource::new(disk_backend_resources::LayeredDiskHandle {
1939            layers: layers
1940                .into_iter()
1941                .map(|layer| match layer {
1942                    LayerOrDisk::Layer(layer) => layer,
1943                    LayerOrDisk::Disk(disk) => DiskLayerDescription {
1944                        layer: DiskLayerHandle(disk).into_resource(),
1945                        read_cache: false,
1946                        write_through: false,
1947                    },
1948                })
1949                .collect(),
1950        }))
1951    }
1952}
1953
1954fn disk_open_inner<'a>(
1955    disk_cli: &'a DiskCliKind,
1956    read_only: bool,
1957    layers: &'a mut Vec<LayerOrDisk>,
1958) -> futures::future::BoxFuture<'a, anyhow::Result<()>> {
1959    Box::pin(async move {
1960        fn layer<T: IntoResource<DiskLayerHandleKind>>(layer: T) -> LayerOrDisk {
1961            LayerOrDisk::Layer(layer.into_resource().into())
1962        }
1963        fn disk<T: IntoResource<DiskHandleKind>>(disk: T) -> LayerOrDisk {
1964            LayerOrDisk::Disk(disk.into_resource())
1965        }
1966        match disk_cli {
1967            &DiskCliKind::Memory(len) => {
1968                layers.push(layer(RamDiskLayerHandle {
1969                    len: Some(len),
1970                    sector_size: None,
1971                }));
1972            }
1973            DiskCliKind::File {
1974                path,
1975                create_with_len,
1976                direct,
1977            } => layers.push(LayerOrDisk::Disk(if let Some(size) = create_with_len {
1978                create_disk_type(
1979                    path,
1980                    *size,
1981                    OpenDiskOptions {
1982                        read_only: false,
1983                        direct: *direct,
1984                    },
1985                )
1986                .with_context(|| format!("failed to create {}", path.display()))?
1987            } else {
1988                open_disk_type(
1989                    path,
1990                    OpenDiskOptions {
1991                        read_only,
1992                        direct: *direct,
1993                    },
1994                )
1995                .await
1996                .with_context(|| format!("failed to open {}", path.display()))?
1997            })),
1998            DiskCliKind::Blob { kind, url } => {
1999                layers.push(disk(disk_backend_resources::BlobDiskHandle {
2000                    url: url.to_owned(),
2001                    format: match kind {
2002                        cli_args::BlobKind::Flat => disk_backend_resources::BlobDiskFormat::Flat,
2003                        cli_args::BlobKind::Vhd1 => {
2004                            disk_backend_resources::BlobDiskFormat::FixedVhd1
2005                        }
2006                    },
2007                }))
2008            }
2009            DiskCliKind::MemoryDiff(inner) => {
2010                layers.push(layer(RamDiskLayerHandle {
2011                    len: None,
2012                    sector_size: None,
2013                }));
2014                disk_open_inner(inner, true, layers).await?;
2015            }
2016            DiskCliKind::PersistentReservationsWrapper(inner) => {
2017                layers.push(disk(disk_backend_resources::DiskWithReservationsHandle(
2018                    disk_open(inner, read_only).await?,
2019                )))
2020            }
2021            DiskCliKind::DelayDiskWrapper {
2022                delay_ms,
2023                disk: inner,
2024            } => layers.push(disk(DelayDiskHandle {
2025                delay: CellUpdater::new(Duration::from_millis(*delay_ms)).cell(),
2026                disk: disk_open(inner, read_only).await?,
2027            })),
2028            DiskCliKind::Crypt {
2029                disk: inner,
2030                cipher,
2031                key_file,
2032            } => layers.push(disk(disk_crypt_resources::DiskCryptHandle {
2033                disk: disk_open(inner, read_only).await?,
2034                cipher: match cipher {
2035                    cli_args::DiskCipher::XtsAes256 => disk_crypt_resources::Cipher::XtsAes256,
2036                },
2037                key: fs_err::read(key_file).context("failed to read key file")?,
2038            })),
2039            DiskCliKind::Sqlite {
2040                path,
2041                create_with_len,
2042            } => {
2043                // FUTURE: this code should be responsible for opening
2044                // file-handle(s) itself, and passing them into sqlite via a custom
2045                // vfs. For now though - simply check if the file exists or not, and
2046                // perform early validation of filesystem-level create options.
2047                match (create_with_len.is_some(), path.exists()) {
2048                    (true, true) => anyhow::bail!(
2049                        "cannot create new sqlite disk at {} - file already exists",
2050                        path.display()
2051                    ),
2052                    (false, false) => anyhow::bail!(
2053                        "cannot open sqlite disk at {} - file not found",
2054                        path.display()
2055                    ),
2056                    _ => {}
2057                }
2058
2059                layers.push(layer(SqliteDiskLayerHandle {
2060                    dbhd_path: path.display().to_string(),
2061                    format_dbhd: create_with_len.map(|len| {
2062                        disk_backend_resources::layer::SqliteDiskLayerFormatParams {
2063                            logically_read_only: false,
2064                            len: Some(len),
2065                        }
2066                    }),
2067                }));
2068            }
2069            DiskCliKind::SqliteDiff { path, create, disk } => {
2070                // FUTURE: this code should be responsible for opening
2071                // file-handle(s) itself, and passing them into sqlite via a custom
2072                // vfs. For now though - simply check if the file exists or not, and
2073                // perform early validation of filesystem-level create options.
2074                match (create, path.exists()) {
2075                    (true, true) => anyhow::bail!(
2076                        "cannot create new sqlite disk at {} - file already exists",
2077                        path.display()
2078                    ),
2079                    (false, false) => anyhow::bail!(
2080                        "cannot open sqlite disk at {} - file not found",
2081                        path.display()
2082                    ),
2083                    _ => {}
2084                }
2085
2086                layers.push(layer(SqliteDiskLayerHandle {
2087                    dbhd_path: path.display().to_string(),
2088                    format_dbhd: create.then_some(
2089                        disk_backend_resources::layer::SqliteDiskLayerFormatParams {
2090                            logically_read_only: false,
2091                            len: None,
2092                        },
2093                    ),
2094                }));
2095                disk_open_inner(disk, true, layers).await?;
2096            }
2097            DiskCliKind::AutoCacheSqlite {
2098                cache_path,
2099                key,
2100                disk,
2101            } => {
2102                layers.push(LayerOrDisk::Layer(DiskLayerDescription {
2103                    read_cache: true,
2104                    write_through: false,
2105                    layer: SqliteAutoCacheDiskLayerHandle {
2106                        cache_path: cache_path.clone(),
2107                        cache_key: key.clone(),
2108                    }
2109                    .into_resource(),
2110                }));
2111                disk_open_inner(disk, read_only, layers).await?;
2112            }
2113        }
2114        Ok(())
2115    })
2116}
2117
2118/// Get the system page size.
2119pub(crate) fn system_page_size() -> u32 {
2120    sparse_mmap::SparseMapping::page_size() as u32
2121}
2122
2123/// The guest architecture string, derived from the compile-time `guest_arch` cfg.
2124pub(crate) const GUEST_ARCH: &str = if cfg!(guest_arch = "x86_64") {
2125    "x86_64"
2126} else {
2127    "aarch64"
2128};
2129
2130/// Open a snapshot directory and validate it against the current VM config.
2131/// Returns the shared memory fd (from memory.bin) and the saved device state.
2132fn prepare_snapshot_restore(
2133    snapshot_dir: &Path,
2134    opt: &Options,
2135) -> anyhow::Result<(
2136    openvmm_defs::worker::SharedMemoryFd,
2137    mesh::payload::message::ProtobufMessage,
2138)> {
2139    let (manifest, state_bytes) = openvmm_helpers::snapshot::read_snapshot(snapshot_dir)?;
2140
2141    // Validate manifest against current VM config.
2142    openvmm_helpers::snapshot::validate_manifest(
2143        &manifest,
2144        GUEST_ARCH,
2145        opt.memory_size(),
2146        opt.processors,
2147        system_page_size(),
2148    )?;
2149
2150    // Open memory.bin (existing file, no create, no resize).
2151    let memory_file = fs_err::OpenOptions::new()
2152        .read(true)
2153        .write(true)
2154        .open(snapshot_dir.join("memory.bin"))?;
2155
2156    // Validate file size matches expected memory size.
2157    let file_size = memory_file.metadata()?.len();
2158    if file_size != manifest.memory_size_bytes {
2159        anyhow::bail!(
2160            "memory.bin size ({file_size} bytes) doesn't match manifest ({} bytes)",
2161            manifest.memory_size_bytes,
2162        );
2163    }
2164
2165    let shared_memory_fd =
2166        openvmm_helpers::shared_memory::file_to_shared_memory_fd(memory_file.into())?;
2167
2168    // Reconstruct ProtobufMessage from the saved state bytes.
2169    // The save side wrote mesh::payload::encode(ProtobufMessage), so we decode
2170    // back to ProtobufMessage.
2171    let state_msg: mesh::payload::message::ProtobufMessage = mesh::payload::decode(&state_bytes)
2172        .context("failed to decode saved state from snapshot")?;
2173
2174    Ok((shared_memory_fd, state_msg))
2175}
2176
2177fn do_main(pidfile_path: &mut Option<PathBuf>) -> anyhow::Result<()> {
2178    #[cfg(windows)]
2179    pal::windows::disable_hard_error_dialog();
2180
2181    tracing_init::enable_tracing()?;
2182
2183    // Try to run as a worker host.
2184    // On success the worker runs to completion and then exits the process (does
2185    // not return). Any worker host setup errors are return and bubbled up.
2186    meshworker::run_vmm_mesh_host()?;
2187
2188    let opt = Options::parse();
2189    if let Some(path) = &opt.write_saved_state_proto {
2190        mesh::payload::protofile::DescriptorWriter::new(vmcore::save_restore::saved_state_roots())
2191            .write_to_path(path)
2192            .context("failed to write protobuf descriptors")?;
2193        return Ok(());
2194    }
2195
2196    if let Some(ref path) = opt.pidfile {
2197        std::fs::write(path, format!("{}\n", std::process::id()))
2198            .context("failed to write pidfile")?;
2199        *pidfile_path = Some(path.clone());
2200    }
2201
2202    if let Some(path) = opt.relay_console_path {
2203        let console_title = opt.relay_console_title.unwrap_or_default();
2204        return console_relay::relay_console(&path, console_title.as_str());
2205    }
2206
2207    #[cfg(any(feature = "grpc", feature = "ttrpc"))]
2208    if let Some(path) = opt.ttrpc.as_ref().or(opt.grpc.as_ref()) {
2209        return block_on(async {
2210            let _ = std::fs::remove_file(path);
2211            let listener =
2212                unix_socket::UnixListener::bind(path).context("failed to bind to socket")?;
2213
2214            let transport = if opt.ttrpc.is_some() {
2215                ttrpc::RpcTransport::Ttrpc
2216            } else {
2217                ttrpc::RpcTransport::Grpc
2218            };
2219
2220            // This is a local launch
2221            let mut handle =
2222                mesh_worker::launch_local_worker::<ttrpc::TtrpcWorker>(ttrpc::Parameters {
2223                    listener,
2224                    transport,
2225                })
2226                .await?;
2227
2228            tracing::info!(%transport, path = %path.display(), "listening");
2229
2230            // Signal the the parent process that the server is ready.
2231            pal::close_stdout().context("failed to close stdout")?;
2232
2233            handle.join().await?;
2234
2235            Ok(())
2236        });
2237    }
2238
2239    DefaultPool::run_with(async |driver| run_control(&driver, opt).await)
2240}
2241
2242fn new_hvsock_service_id(port: u32) -> Guid {
2243    // This GUID is an embedding of the AF_VSOCK port into an
2244    // AF_HYPERV service ID.
2245    Guid {
2246        data1: port,
2247        .."00000000-facb-11e6-bd58-64006a7986d3".parse().unwrap()
2248    }
2249}
2250
2251async fn run_control(driver: &DefaultDriver, opt: Options) -> anyhow::Result<()> {
2252    let mut mesh = Some(VmmMesh::new(&driver, opt.single_process)?);
2253    let result = run_control_inner(driver, &mut mesh, opt).await;
2254    // If setup failed before the mesh was handed to the controller, shut it
2255    // down so the child host process exits cleanly without noisy logs.
2256    if let Some(mesh) = mesh {
2257        mesh.shutdown().await;
2258    }
2259    result
2260}
2261
2262async fn run_control_inner(
2263    driver: &DefaultDriver,
2264    mesh_slot: &mut Option<VmmMesh>,
2265    opt: Options,
2266) -> anyhow::Result<()> {
2267    let mesh = mesh_slot.as_ref().unwrap();
2268    let (mut vm_config, mut resources) = vm_config_from_command_line(driver, mesh, &opt).await?;
2269
2270    let mut vnc_worker = None;
2271    if opt.gfx || opt.vnc {
2272        let listener = TcpListener::bind(format!("127.0.0.1:{}", opt.vnc_port))
2273            .with_context(|| format!("binding to VNC port {}", opt.vnc_port))?;
2274
2275        let input_send = vm_config.input.sender();
2276        let framebuffer = resources
2277            .framebuffer_access
2278            .take()
2279            .expect("synth video enabled");
2280
2281        let vnc_host = mesh
2282            .make_host("vnc", None)
2283            .await
2284            .context("spawning vnc process failed")?;
2285
2286        vnc_worker = Some(
2287            vnc_host
2288                .launch_worker(
2289                    vnc_worker_defs::VNC_WORKER_TCP,
2290                    VncParameters {
2291                        listener,
2292                        framebuffer,
2293                        input_send,
2294                    },
2295                )
2296                .await?,
2297        )
2298    }
2299
2300    // spin up the debug worker
2301    let gdb_worker = if let Some(port) = opt.gdb {
2302        let listener = TcpListener::bind(format!("127.0.0.1:{}", port))
2303            .with_context(|| format!("binding to gdb port {}", port))?;
2304
2305        let (req_tx, req_rx) = mesh::channel();
2306        vm_config.debugger_rpc = Some(req_rx);
2307
2308        let gdb_host = mesh
2309            .make_host("gdb", None)
2310            .await
2311            .context("spawning gdbstub process failed")?;
2312
2313        Some(
2314            gdb_host
2315                .launch_worker(
2316                    debug_worker_defs::DEBUGGER_WORKER,
2317                    debug_worker_defs::DebuggerParameters {
2318                        listener,
2319                        req_chan: req_tx,
2320                        vp_count: vm_config.processor_topology.proc_count,
2321                        target_arch: if cfg!(guest_arch = "x86_64") {
2322                            debug_worker_defs::TargetArch::X86_64
2323                        } else {
2324                            debug_worker_defs::TargetArch::Aarch64
2325                        },
2326                    },
2327                )
2328                .await
2329                .context("failed to launch gdbstub worker")?,
2330        )
2331    } else {
2332        None
2333    };
2334
2335    // spin up the VM
2336    let (vm_rpc, rpc_recv) = mesh::channel();
2337    let (notify_send, notify_recv) = mesh::channel();
2338    let vm_worker = {
2339        let vm_host = mesh.make_host("vm", opt.log_file.clone()).await?;
2340
2341        let (shared_memory, saved_state) = if let Some(snapshot_dir) = &opt.restore_snapshot {
2342            let (fd, state_msg) = prepare_snapshot_restore(snapshot_dir, &opt)?;
2343            (Some(fd), Some(state_msg))
2344        } else {
2345            let shared_memory = opt
2346                .memory_backing_file()
2347                .map(|path| {
2348                    openvmm_helpers::shared_memory::open_memory_backing_file(
2349                        path,
2350                        opt.memory_size(),
2351                    )
2352                })
2353                .transpose()?;
2354            (shared_memory, None)
2355        };
2356
2357        let params = VmWorkerParameters {
2358            hypervisor: match &opt.hypervisor {
2359                Some(name) => openvmm_helpers::hypervisor::hypervisor_resource(name)?,
2360                None => openvmm_helpers::hypervisor::choose_hypervisor()?,
2361            },
2362            cfg: vm_config,
2363            saved_state,
2364            shared_memory,
2365            rpc: rpc_recv,
2366            notify: notify_send,
2367        };
2368        vm_host
2369            .launch_worker(VM_WORKER, params)
2370            .await
2371            .context("failed to launch vm worker")?
2372    };
2373
2374    if opt.restore_snapshot.is_some() {
2375        tracing::info!("restoring VM from snapshot");
2376    }
2377
2378    if !opt.paused {
2379        vm_rpc.call(VmRpc::Resume, ()).await?;
2380    }
2381
2382    let paravisor_diag = Arc::new(diag_client::DiagClient::from_dialer(
2383        driver.clone(),
2384        DiagDialer {
2385            driver: driver.clone(),
2386            vm_rpc: vm_rpc.clone(),
2387            openhcl_vtl: if opt.vtl2 {
2388                DeviceVtl::Vtl2
2389            } else {
2390                DeviceVtl::Vtl0
2391            },
2392        },
2393    ));
2394
2395    let diag_inspector = DiagInspector::new(driver.clone(), paravisor_diag.clone());
2396
2397    // Create channels between the REPL and VmController.
2398    let (vm_controller_send, vm_controller_recv) = mesh::channel();
2399    let (vm_controller_event_send, vm_controller_event_recv) = mesh::channel();
2400
2401    let has_vtl2 = resources.vtl2_settings.is_some();
2402
2403    // Build the VmController with exclusive resources.
2404    let controller = vm_controller::VmController {
2405        mesh: mesh_slot.take().unwrap(),
2406        vm_worker,
2407        vnc_worker,
2408        gdb_worker,
2409        diag_inspector: Some(diag_inspector),
2410        vtl2_settings: resources.vtl2_settings,
2411        ged_rpc: resources.ged_rpc.clone(),
2412        vm_rpc: vm_rpc.clone(),
2413        paravisor_diag: Some(paravisor_diag),
2414        igvm_path: opt.igvm.clone(),
2415        memory_backing_file: opt.memory_backing_file().cloned(),
2416        memory: opt.memory_size(),
2417        processors: opt.processors,
2418        log_file: opt.log_file.clone(),
2419    };
2420
2421    // Spawn the VmController as a task.
2422    let controller_task = driver.spawn(
2423        "vm-controller",
2424        controller.run(vm_controller_recv, vm_controller_event_send, notify_recv),
2425    );
2426
2427    // Run the REPL with shareable resources.
2428    let repl_result = repl::run_repl(
2429        driver,
2430        repl::ReplResources {
2431            vm_rpc,
2432            vm_controller: vm_controller_send,
2433            vm_controller_events: vm_controller_event_recv,
2434            scsi_rpc: resources.scsi_rpc,
2435            nvme_vtl2_rpc: resources.nvme_vtl2_rpc,
2436            shutdown_ic: resources.shutdown_ic,
2437            kvp_ic: resources.kvp_ic,
2438            console_in: resources.console_in,
2439            has_vtl2,
2440        },
2441    )
2442    .await;
2443
2444    // Wait for the controller task to finish (it stops the VM worker and
2445    // shuts down the mesh).
2446    controller_task.await;
2447
2448    repl_result
2449}
2450
2451struct DiagDialer {
2452    driver: DefaultDriver,
2453    vm_rpc: mesh::Sender<VmRpc>,
2454    openhcl_vtl: DeviceVtl,
2455}
2456
2457impl mesh_rpc::client::Dial for DiagDialer {
2458    type Stream = PolledSocket<unix_socket::UnixStream>;
2459
2460    async fn dial(&mut self) -> io::Result<Self::Stream> {
2461        let service_id = new_hvsock_service_id(1);
2462        let socket = self
2463            .vm_rpc
2464            .call_failable(
2465                VmRpc::ConnectHvsock,
2466                (
2467                    CancelContext::new().with_timeout(Duration::from_secs(2)),
2468                    service_id,
2469                    self.openhcl_vtl,
2470                ),
2471            )
2472            .await
2473            .map_err(io::Error::other)?;
2474
2475        PolledSocket::new(&self.driver, socket)
2476    }
2477}
2478
2479/// An object that implements [`InspectMut`] by sending an inspect request over
2480/// TTRPC to the guest (typically the paravisor running in VTL2), then stitching
2481/// the response back into the inspect tree.
2482///
2483/// This also caches the TTRPC connection to the guest so that only the first
2484/// inspect request has to wait for the connection to be established.
2485pub(crate) struct DiagInspector(DiagInspectorInner);
2486
2487enum DiagInspectorInner {
2488    NotStarted(DefaultDriver, Arc<diag_client::DiagClient>),
2489    Started {
2490        send: mesh::Sender<inspect::Deferred>,
2491        _task: Task<()>,
2492    },
2493    Invalid,
2494}
2495
2496impl DiagInspector {
2497    pub fn new(driver: DefaultDriver, diag_client: Arc<diag_client::DiagClient>) -> Self {
2498        Self(DiagInspectorInner::NotStarted(driver, diag_client))
2499    }
2500
2501    fn start(&mut self) -> &mesh::Sender<inspect::Deferred> {
2502        loop {
2503            match self.0 {
2504                DiagInspectorInner::NotStarted { .. } => {
2505                    let DiagInspectorInner::NotStarted(driver, client) =
2506                        std::mem::replace(&mut self.0, DiagInspectorInner::Invalid)
2507                    else {
2508                        unreachable!()
2509                    };
2510                    let (send, recv) = mesh::channel();
2511                    let task = driver.clone().spawn("diag-inspect", async move {
2512                        Self::run(&client, recv).await
2513                    });
2514
2515                    self.0 = DiagInspectorInner::Started { send, _task: task };
2516                }
2517                DiagInspectorInner::Started { ref send, .. } => break send,
2518                DiagInspectorInner::Invalid => unreachable!(),
2519            }
2520        }
2521    }
2522
2523    async fn run(
2524        diag_client: &diag_client::DiagClient,
2525        mut recv: mesh::Receiver<inspect::Deferred>,
2526    ) {
2527        while let Some(deferred) = recv.next().await {
2528            let info = deferred.external_request();
2529            let result = match info.request_type {
2530                inspect::ExternalRequestType::Inspect { depth } => {
2531                    if depth == 0 {
2532                        Ok(inspect::Node::Unevaluated)
2533                    } else {
2534                        // TODO: Support taking timeouts from the command line
2535                        diag_client
2536                            .inspect(info.path, Some(depth - 1), Some(Duration::from_secs(1)))
2537                            .await
2538                    }
2539                }
2540                inspect::ExternalRequestType::Update { value } => {
2541                    (diag_client.update(info.path, value).await).map(inspect::Node::Value)
2542                }
2543            };
2544            deferred.complete_external(
2545                result.unwrap_or_else(|err| {
2546                    inspect::Node::Failed(inspect::Error::Mesh(format!("{err:#}")))
2547                }),
2548                inspect::SensitivityLevel::Unspecified,
2549            )
2550        }
2551    }
2552}
2553
2554impl InspectMut for DiagInspector {
2555    fn inspect_mut(&mut self, req: inspect::Request<'_>) {
2556        self.start().send(req.defer());
2557    }
2558}