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