Skip to main content

openvmm_entry/
lib.rs

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