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