blob: f0dfdd09d6f44c9add606f6fe77add6f47d18af3 [file] [log] [blame]
Zach Reizner39aa26b2017-12-12 18:03:23 -08001// Copyright 2017 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Chuanxiao Dongcb03ec62022-01-20 08:25:38 +08005use std::cmp::{max, Reverse};
Daniel Verkamp5586ff52022-02-24 16:34:55 -08006use std::collections::{BTreeMap, BTreeSet};
Anton Romanov5acc0f52022-01-28 00:18:11 +00007use std::convert::TryInto;
Dylan Reid059a1882018-07-23 17:58:09 -07008use std::fs::{File, OpenOptions};
Vineeth Pillai2b6855e2022-01-12 16:57:22 +00009use std::io::prelude::*;
Federico 'Morg' Pareschia1184822021-09-09 10:52:58 +090010use std::io::stdin;
Steven Richmanf32d0b42020-06-20 21:45:32 -070011use std::iter;
Daniel Verkamp94c35272019-09-12 13:31:30 -070012use std::mem;
Haiwei Li09b7b8e2022-02-18 18:16:05 +080013use std::ops::RangeInclusive;
Anton Romanovd43ae3c2022-01-31 17:32:54 +000014#[cfg(feature = "gpu")]
15use std::os::unix::net::UnixStream;
16use std::os::unix::prelude::OpenOptionsExt;
Xiong Zhang626f0142022-03-12 16:05:17 +080017use std::path::Path;
Dylan Reidb0492662019-05-17 14:50:13 -070018use std::sync::{mpsc, Arc, Barrier};
Hikaru Nishida584e52c2021-04-27 17:37:08 +090019use std::time::Duration;
Dylan Reidb0492662019-05-17 14:50:13 -070020
Vineeth Pillai2b6855e2022-01-12 16:57:22 +000021use std::process;
Anton Romanov5acc0f52022-01-28 00:18:11 +000022#[cfg(all(target_arch = "x86_64", feature = "gdb"))]
Zach Reizner39aa26b2017-12-12 18:03:23 -080023use std::thread;
Zach Reizner39aa26b2017-12-12 18:03:23 -080024
Alexandre Courbotc6ad83f2022-02-07 19:45:31 +090025use devices::virtio::vhost::vsock::{VhostVsockConfig, VhostVsockDeviceParameter};
Anton Romanov5acc0f52022-01-28 00:18:11 +000026use libc;
Zach Reizner39aa26b2017-12-12 18:03:23 -080027
Tomasz Jeznach42644642020-05-20 23:27:59 -070028use acpi_tables::sdt::SDT;
29
Daniel Verkamp6b298582021-08-16 15:37:11 -070030use anyhow::{anyhow, bail, Context, Result};
Zach Reiznerd49bcdb2021-01-07 08:30:28 -080031use base::*;
Daniel Verkamp578e7cc2022-03-01 22:34:52 -080032use base::{UnixSeqpacket, UnixSeqpacketListener, UnlinkUnixSeqpacketListener};
Anton Romanov5acc0f52022-01-28 00:18:11 +000033use devices::serial_device::SerialHardware;
Zide Chenafdb9382021-06-17 12:04:43 -070034use devices::vfio::{VfioCommonSetup, VfioCommonTrait};
Woody Chow055b81b2022-01-25 18:34:29 +090035use devices::virtio::memory_mapper::MemoryMapperTrait;
Anton Romanovd43ae3c2022-01-31 17:32:54 +000036#[cfg(feature = "gpu")]
Anton Romanov5acc0f52022-01-28 00:18:11 +000037use devices::virtio::{self, EventDevice};
paulhsiace17e6e2020-08-28 18:37:45 +080038#[cfg(feature = "audio")]
39use devices::Ac97Dev;
Xiong Zhang17b0daf2019-04-23 17:14:50 +080040use devices::{
Anton Romanov5acc0f52022-01-28 00:18:11 +000041 self, BusDeviceObj, HostHotPlugKey, HotPlugBus, IrqEventIndex, KvmKernelIrqChip, PciAddress,
Xiong Zhang626f0142022-03-12 16:05:17 +080042 PciDevice, PvPanicCode, PvPanicPciDevice, StubPciDevice, VirtioPciDevice,
Xiong Zhang17b0daf2019-04-23 17:14:50 +080043};
Chuanxiao Donga8d427b2022-01-07 10:26:24 +080044use devices::{CoIommuDev, IommuDevType};
Daniel Verkampf1439d42021-05-21 13:55:10 -070045#[cfg(feature = "usb")]
46use devices::{HostBackendDeviceProvider, XhciController};
Steven Richmanf32d0b42020-06-20 21:45:32 -070047use hypervisor::kvm::{Kvm, KvmVcpu, KvmVm};
Anton Romanov5acc0f52022-01-28 00:18:11 +000048use hypervisor::{HypervisorCap, ProtectionType, Vm, VmCap};
Allen Webbf3024c82020-06-19 07:19:48 -070049use minijail::{self, Minijail};
Anton Romanov5acc0f52022-01-28 00:18:11 +000050use resources::{Alloc, SystemAllocator};
Gurchetan Singh293913c2020-12-09 10:44:13 -080051use rutabaga_gfx::RutabagaGralloc;
Dylan Reidb0492662019-05-17 14:50:13 -070052use sync::Mutex;
Zach Reiznerd49bcdb2021-01-07 08:30:28 -080053use vm_control::*;
Sergey Senozhatskyd78d05b2021-04-13 20:59:58 +090054use vm_memory::{GuestAddress, GuestMemory, MemoryPolicy};
Zach Reizner39aa26b2017-12-12 18:03:23 -080055
Keiichi Watanabec5262e92020-10-21 15:57:33 +090056#[cfg(all(target_arch = "x86_64", feature = "gdb"))]
57use crate::gdb::{gdb_thread, GdbStub};
Daniel Verkamp5586ff52022-02-24 16:34:55 -080058use crate::{Config, Executable, FileBackedMappingParameters, SharedDir, SharedDirKind, VfioType};
Daniel Verkampa7b6a1c2020-03-09 13:16:46 -070059use arch::{
Keiichi Watanabe553d2192021-08-16 16:42:27 +090060 self, LinuxArch, RunnableLinuxVm, VcpuAffinity, VirtioDeviceStub, VmComponents, VmImage,
Daniel Verkampa7b6a1c2020-03-09 13:16:46 -070061};
Sonny Raoed517d12018-02-13 22:09:43 -080062
Xiong Zhang626f0142022-03-12 16:05:17 +080063#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
64use {
65 crate::HostPcieRootPortParameters,
66 devices::{
67 IrqChipX86_64 as IrqChipArch, KvmSplitIrqChip, PciBridge, PcieHostRootPort, PcieRootPort,
68 },
69 hypervisor::{VcpuX86_64 as VcpuArch, VmX86_64 as VmArch},
70 x86_64::X8664arch as Arch,
71};
Sonny Rao2ffa0cb2018-02-26 17:27:40 -080072#[cfg(any(target_arch = "arm", target_arch = "aarch64"))]
Steven Richmanf32d0b42020-06-20 21:45:32 -070073use {
74 aarch64::AArch64 as Arch,
Steven Richman11dc6712020-09-02 15:39:14 -070075 devices::IrqChipAArch64 as IrqChipArch,
Steven Richmanf32d0b42020-06-20 21:45:32 -070076 hypervisor::{VcpuAArch64 as VcpuArch, VmAArch64 as VmArch},
77};
Zach Reizner39aa26b2017-12-12 18:03:23 -080078
Anton Romanov5acc0f52022-01-28 00:18:11 +000079mod device_helpers;
80use device_helpers::*;
Anton Romanovdb0f4d62022-03-23 21:24:29 +000081pub(crate) mod jail_helpers;
Anton Romanov5acc0f52022-01-28 00:18:11 +000082use jail_helpers::*;
83mod vcpu;
Chirantan Ekbote2ee9dcd2021-05-26 18:21:44 +090084
David Tolnay2b089fc2019-03-04 15:33:22 -080085#[cfg(feature = "gpu")]
Anton Romanovdb0f4d62022-03-23 21:24:29 +000086pub(crate) mod gpu;
Chirantan Ekbote44292f52021-06-25 18:31:41 +090087#[cfg(feature = "gpu")]
Dmitry Torokhove464a7a2022-01-26 13:29:36 -080088pub use gpu::GpuRenderServerParameters;
89#[cfg(feature = "gpu")]
Anton Romanov5acc0f52022-01-28 00:18:11 +000090use gpu::*;
Jorge E. Moreirad4562d02021-06-28 16:21:12 -070091
Zach Reiznerd49bcdb2021-01-07 08:30:28 -080092// gpu_device_tube is not used when GPU support is disabled.
Dmitry Torokhovee42b8c2019-05-27 11:14:20 -070093#[cfg_attr(not(feature = "gpu"), allow(unused_variables))]
David Tolnay2b089fc2019-03-04 15:33:22 -080094fn create_virtio_devices(
95 cfg: &Config,
Steven Richmanf32d0b42020-06-20 21:45:32 -070096 vm: &mut impl Vm,
Jakub Starona3411ea2019-04-24 10:55:25 -070097 resources: &mut SystemAllocator,
Michael Hoyle685316f2020-09-16 15:29:20 -070098 _exit_evt: &Event,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -080099 wayland_device_tube: Tube,
100 gpu_device_tube: Tube,
Alexandre Courbote55b7912022-03-04 16:54:38 +0900101 vhost_user_gpu_tubes: Vec<(Tube, Tube, Tube)>,
Andrew Walbran3cd93602022-01-25 13:59:23 +0000102 balloon_device_tube: Option<Tube>,
Chuanxiao Dong146a13b2021-12-09 12:59:54 +0800103 balloon_inflate_tube: Option<Tube>,
David Stevens06d157a2022-01-13 23:44:48 +0900104 init_balloon_size: u64,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800105 disk_device_tubes: &mut Vec<Tube>,
106 pmem_device_tubes: &mut Vec<Tube>,
Lingfeng Yangd6ac1ab2020-01-31 13:55:35 -0800107 map_request: Arc<Mutex<Option<ExternalMapping>>>,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800108 fs_device_tubes: &mut Vec<Tube>,
Dmitry Torokhov9cbe5432022-01-25 19:17:07 -0800109 #[cfg(feature = "gpu")] render_server_fd: Option<SafeDescriptor>,
Abhishek Bhardwaj90fd1642021-11-24 18:26:37 -0800110 vvu_proxy_device_tubes: &mut Vec<Tube>,
David Tolnay2b089fc2019-03-04 15:33:22 -0800111) -> DeviceResult<Vec<VirtioDeviceStub>> {
Dylan Reid059a1882018-07-23 17:58:09 -0700112 let mut devs = Vec::new();
Zach Reizner39aa26b2017-12-12 18:03:23 -0800113
Chirantan Ekbote44292f52021-06-25 18:31:41 +0900114 #[cfg(feature = "gpu")]
Alexandre Courbote55b7912022-03-04 16:54:38 +0900115 for (opt, (host_gpu_tube, device_gpu_tube, device_control_tube)) in
116 cfg.vhost_user_gpu.iter().zip(vhost_user_gpu_tubes)
117 {
Chirantan Ekbote44292f52021-06-25 18:31:41 +0900118 devs.push(create_vhost_user_gpu_device(
119 cfg,
120 opt,
Alexandre Courbote55b7912022-03-04 16:54:38 +0900121 (host_gpu_tube, device_gpu_tube),
122 device_control_tube,
Chirantan Ekbote44292f52021-06-25 18:31:41 +0900123 )?);
124 }
125
Abhishek Bhardwaj103c1b72021-11-01 15:52:23 -0700126 for opt in &cfg.vvu_proxy {
Abhishek Bhardwaj90fd1642021-11-24 18:26:37 -0800127 devs.push(create_vvu_proxy_device(
128 cfg,
129 opt,
130 vvu_proxy_device_tubes.remove(0),
131 )?);
Abhishek Bhardwaj103c1b72021-11-01 15:52:23 -0700132 }
133
David Tolnayfa701712019-02-13 16:42:54 -0800134 #[cfg_attr(not(feature = "gpu"), allow(unused_mut))]
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800135 let mut resource_bridges = Vec::<Tube>::new();
Chirantan Ekbotedd11d432019-06-11 21:50:46 +0900136
Ryo Hashimoto0b788de2019-12-10 17:14:13 +0900137 if !cfg.wayland_socket_paths.is_empty() {
Chirantan Ekbotedd11d432019-06-11 21:50:46 +0900138 #[cfg_attr(not(feature = "gpu"), allow(unused_mut))]
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800139 let mut wl_resource_bridge = None::<Tube>;
Chirantan Ekbotedd11d432019-06-11 21:50:46 +0900140
141 #[cfg(feature = "gpu")]
142 {
Jason Macnakcc7070b2019-11-06 14:48:12 -0800143 if cfg.gpu_parameters.is_some() {
Daniel Verkamp6b298582021-08-16 15:37:11 -0700144 let (wl_socket, gpu_socket) = Tube::pair().context("failed to create tube")?;
Chirantan Ekbotedd11d432019-06-11 21:50:46 +0900145 resource_bridges.push(gpu_socket);
146 wl_resource_bridge = Some(wl_socket);
147 }
148 }
149
150 devs.push(create_wayland_device(
151 cfg,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800152 wayland_device_tube,
Chirantan Ekbotedd11d432019-06-11 21:50:46 +0900153 wl_resource_bridge,
154 )?);
155 }
David Tolnayfa701712019-02-13 16:42:54 -0800156
Keiichi Watanabe57df6a02019-12-06 22:24:40 +0900157 #[cfg(feature = "video-decoder")]
Alexandre Courbotb42b3e52021-07-09 23:38:57 +0900158 let video_dec_cfg = if let Some(backend) = cfg.video_dec {
Daniel Verkamp6b298582021-08-16 15:37:11 -0700159 let (video_tube, gpu_tube) = Tube::pair().context("failed to create tube")?;
Daniel Verkampffb59122021-03-18 14:06:15 -0700160 resource_bridges.push(gpu_tube);
Alexandre Courbotb42b3e52021-07-09 23:38:57 +0900161 Some((video_tube, backend))
Daniel Verkampffb59122021-03-18 14:06:15 -0700162 } else {
163 None
164 };
Keiichi Watanabe57df6a02019-12-06 22:24:40 +0900165
166 #[cfg(feature = "video-encoder")]
Alexandre Courbotb42b3e52021-07-09 23:38:57 +0900167 let video_enc_cfg = if let Some(backend) = cfg.video_enc {
Daniel Verkamp6b298582021-08-16 15:37:11 -0700168 let (video_tube, gpu_tube) = Tube::pair().context("failed to create tube")?;
Daniel Verkampffb59122021-03-18 14:06:15 -0700169 resource_bridges.push(gpu_tube);
Alexandre Courbotb42b3e52021-07-09 23:38:57 +0900170 Some((video_tube, backend))
Daniel Verkampffb59122021-03-18 14:06:15 -0700171 } else {
172 None
173 };
Keiichi Watanabe57df6a02019-12-06 22:24:40 +0900174
Zach Reizner3a8100a2017-09-13 19:15:43 -0700175 #[cfg(feature = "gpu")]
176 {
Noah Golddc7f52b2020-02-01 13:01:58 -0800177 if let Some(gpu_parameters) = &cfg.gpu_parameters {
Anton Romanov5acc0f52022-01-28 00:18:11 +0000178 let mut gpu_display_w = virtio::DEFAULT_DISPLAY_WIDTH;
179 let mut gpu_display_h = virtio::DEFAULT_DISPLAY_HEIGHT;
Jason Macnakd659a0d2021-03-15 15:33:01 -0700180 if !gpu_parameters.displays.is_empty() {
181 gpu_display_w = gpu_parameters.displays[0].width;
182 gpu_display_h = gpu_parameters.displays[0].height;
183 }
184
Zach Reizner65b98f12019-11-22 17:34:58 -0800185 let mut event_devices = Vec::new();
186 if cfg.display_window_mouse {
187 let (event_device_socket, virtio_dev_socket) =
Daniel Verkamp6b298582021-08-16 15:37:11 -0700188 UnixStream::pair().context("failed to create socket")?;
Tristan Muntsinger486cffc2020-09-29 22:05:41 +0000189 let (multi_touch_width, multi_touch_height) = cfg
190 .virtio_multi_touch
Jorge E. Moreira6635ca42021-04-28 13:11:41 -0700191 .first()
Kaiyi Libccb4eb2020-02-06 17:53:11 -0800192 .as_ref()
Tristan Muntsinger486cffc2020-09-29 22:05:41 +0000193 .map(|multi_touch_spec| multi_touch_spec.get_size())
Jason Macnakd659a0d2021-03-15 15:33:01 -0700194 .unwrap_or((gpu_display_w, gpu_display_h));
Tristan Muntsinger486cffc2020-09-29 22:05:41 +0000195 let dev = virtio::new_multi_touch(
Jorge E. Moreira6635ca42021-04-28 13:11:41 -0700196 // u32::MAX is the least likely to collide with the indices generated above for
197 // the multi_touch options, which begin at 0.
198 u32::MAX,
Kaiyi Libccb4eb2020-02-06 17:53:11 -0800199 virtio_dev_socket,
Tristan Muntsinger486cffc2020-09-29 22:05:41 +0000200 multi_touch_width,
201 multi_touch_height,
Noah Goldd4ca29b2020-10-27 12:21:52 -0700202 virtio::base_features(cfg.protected_vm),
Kaiyi Libccb4eb2020-02-06 17:53:11 -0800203 )
Daniel Verkamp6b298582021-08-16 15:37:11 -0700204 .context("failed to set up mouse device")?;
Zach Reizner65b98f12019-11-22 17:34:58 -0800205 devs.push(VirtioDeviceStub {
206 dev: Box::new(dev),
Alexandre Courbot6a8f6562022-03-24 14:43:48 +0900207 jail: simple_jail(&cfg.jail_config, "input_device")?,
Zach Reizner65b98f12019-11-22 17:34:58 -0800208 });
209 event_devices.push(EventDevice::touchscreen(event_device_socket));
210 }
211 if cfg.display_window_keyboard {
212 let (event_device_socket, virtio_dev_socket) =
Daniel Verkamp6b298582021-08-16 15:37:11 -0700213 UnixStream::pair().context("failed to create socket")?;
Noah Goldd4ca29b2020-10-27 12:21:52 -0700214 let dev = virtio::new_keyboard(
Jorge E. Moreira6635ca42021-04-28 13:11:41 -0700215 // u32::MAX is the least likely to collide with the indices generated above for
216 // the multi_touch options, which begin at 0.
217 u32::MAX,
Noah Goldd4ca29b2020-10-27 12:21:52 -0700218 virtio_dev_socket,
219 virtio::base_features(cfg.protected_vm),
220 )
Daniel Verkamp6b298582021-08-16 15:37:11 -0700221 .context("failed to set up keyboard device")?;
Zach Reizner65b98f12019-11-22 17:34:58 -0800222 devs.push(VirtioDeviceStub {
223 dev: Box::new(dev),
Alexandre Courbot6a8f6562022-03-24 14:43:48 +0900224 jail: simple_jail(&cfg.jail_config, "input_device")?,
Zach Reizner65b98f12019-11-22 17:34:58 -0800225 });
226 event_devices.push(EventDevice::keyboard(event_device_socket));
227 }
Chia-I Wu16fb6592021-11-10 11:45:32 -0800228
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700229 devs.push(create_gpu_device(
230 cfg,
231 _exit_evt,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800232 gpu_device_tube,
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700233 resource_bridges,
Ryo Hashimoto0b788de2019-12-10 17:14:13 +0900234 // Use the unnamed socket for GPU display screens.
235 cfg.wayland_socket_paths.get(""),
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700236 cfg.x_display.clone(),
Chia-I Wu16fb6592021-11-10 11:45:32 -0800237 render_server_fd,
Zach Reizner65b98f12019-11-22 17:34:58 -0800238 event_devices,
Lingfeng Yangd6ac1ab2020-01-31 13:55:35 -0800239 map_request,
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700240 )?);
Zach Reizner3a8100a2017-09-13 19:15:43 -0700241 }
242 }
243
Richard Fung08289b12022-02-02 20:46:19 +0000244 for (_, param) in cfg
245 .serial_parameters
246 .iter()
247 .filter(|(_k, v)| v.hardware == SerialHardware::VirtioConsole)
248 {
249 let dev = create_console_device(cfg, param)?;
250 devs.push(dev);
251 }
252
253 for disk in &cfg.disks {
254 let disk_device_tube = disk_device_tubes.remove(0);
255 devs.push(create_block_device(cfg, disk, disk_device_tube)?);
256 }
257
258 for blk in &cfg.vhost_user_blk {
259 devs.push(create_vhost_user_block_device(cfg, blk)?);
260 }
261
262 for console in &cfg.vhost_user_console {
263 devs.push(create_vhost_user_console_device(cfg, console)?);
264 }
265
266 for (index, pmem_disk) in cfg.pmem_devices.iter().enumerate() {
267 let pmem_device_tube = pmem_device_tubes.remove(0);
268 devs.push(create_pmem_device(
269 cfg,
270 vm,
271 resources,
272 pmem_disk,
273 index,
274 pmem_device_tube,
275 )?);
276 }
277
Andrew Walbrana24a7522022-02-09 18:23:00 +0000278 if cfg.rng {
279 devs.push(create_rng_device(cfg)?);
280 }
Richard Fung08289b12022-02-02 20:46:19 +0000281
282 #[cfg(feature = "tpm")]
283 {
284 if cfg.software_tpm {
Daniel Verkamp29950ef2021-10-07 14:56:45 -0700285 devs.push(create_software_tpm_device(cfg)?);
Richard Fung08289b12022-02-02 20:46:19 +0000286 }
287 }
288
289 for (idx, single_touch_spec) in cfg.virtio_single_touch.iter().enumerate() {
290 devs.push(create_single_touch_device(
291 cfg,
292 single_touch_spec,
293 idx as u32,
294 )?);
295 }
296
297 for (idx, multi_touch_spec) in cfg.virtio_multi_touch.iter().enumerate() {
298 devs.push(create_multi_touch_device(
299 cfg,
300 multi_touch_spec,
301 idx as u32,
302 )?);
303 }
304
305 for (idx, trackpad_spec) in cfg.virtio_trackpad.iter().enumerate() {
306 devs.push(create_trackpad_device(cfg, trackpad_spec, idx as u32)?);
307 }
308
309 for (idx, mouse_socket) in cfg.virtio_mice.iter().enumerate() {
310 devs.push(create_mouse_device(cfg, mouse_socket, idx as u32)?);
311 }
312
313 for (idx, keyboard_socket) in cfg.virtio_keyboard.iter().enumerate() {
314 devs.push(create_keyboard_device(cfg, keyboard_socket, idx as u32)?);
315 }
316
317 for (idx, switches_socket) in cfg.virtio_switches.iter().enumerate() {
318 devs.push(create_switches_device(cfg, switches_socket, idx as u32)?);
319 }
320
321 for dev_path in &cfg.virtio_input_evdevs {
322 devs.push(create_vinput_device(cfg, dev_path)?);
323 }
324
325 if let Some(balloon_device_tube) = balloon_device_tube {
326 devs.push(create_balloon_device(
327 cfg,
328 balloon_device_tube,
329 balloon_inflate_tube,
330 init_balloon_size,
331 )?);
332 }
333
334 // We checked above that if the IP is defined, then the netmask is, too.
335 for tap_fd in &cfg.tap_fd {
336 devs.push(create_tap_net_device_from_fd(cfg, *tap_fd)?);
337 }
338
339 if let (Some(host_ip), Some(netmask), Some(mac_address)) =
340 (cfg.host_ip, cfg.netmask, cfg.mac_address)
341 {
342 if !cfg.vhost_user_net.is_empty() {
343 bail!("vhost-user-net cannot be used with any of --host_ip, --netmask or --mac");
344 }
345 devs.push(create_net_device_from_config(
346 cfg,
347 host_ip,
348 netmask,
349 mac_address,
350 )?);
351 }
352
353 for tap_name in &cfg.tap_name {
354 devs.push(create_tap_net_device_from_name(cfg, tap_name.as_bytes())?);
355 }
356
357 for net in &cfg.vhost_user_net {
358 devs.push(create_vhost_user_net_device(cfg, net)?);
359 }
360
361 for vsock in &cfg.vhost_user_vsock {
362 devs.push(create_vhost_user_vsock_device(cfg, vsock)?);
363 }
364
365 for opt in &cfg.vhost_user_wl {
366 devs.push(create_vhost_user_wl_device(cfg, opt)?);
367 }
368
Chih-Yang Hsiae31731c2022-01-05 17:30:28 +0800369 #[cfg(feature = "audio_cras")]
370 {
371 for cras_snd in &cfg.cras_snds {
372 devs.push(create_cras_snd_device(cfg, cras_snd.clone())?);
373 }
374 }
375
Daniel Verkampffb59122021-03-18 14:06:15 -0700376 #[cfg(feature = "video-decoder")]
377 {
Alexandre Courbotb42b3e52021-07-09 23:38:57 +0900378 if let Some((video_dec_tube, video_dec_backend)) = video_dec_cfg {
Daniel Verkampffb59122021-03-18 14:06:15 -0700379 register_video_device(
Alexandre Courbotb42b3e52021-07-09 23:38:57 +0900380 video_dec_backend,
Daniel Verkampffb59122021-03-18 14:06:15 -0700381 &mut devs,
382 video_dec_tube,
383 cfg,
384 devices::virtio::VideoDeviceType::Decoder,
385 )?;
386 }
387 }
388
389 #[cfg(feature = "video-encoder")]
390 {
Alexandre Courbotb42b3e52021-07-09 23:38:57 +0900391 if let Some((video_enc_tube, video_enc_backend)) = video_enc_cfg {
Daniel Verkampffb59122021-03-18 14:06:15 -0700392 register_video_device(
Alexandre Courbotb42b3e52021-07-09 23:38:57 +0900393 video_enc_backend,
Daniel Verkampffb59122021-03-18 14:06:15 -0700394 &mut devs,
395 video_enc_tube,
396 cfg,
397 devices::virtio::VideoDeviceType::Encoder,
398 )?;
399 }
400 }
401
Zach Reizneraa575662018-08-15 10:46:32 -0700402 if let Some(cid) = cfg.cid {
Alexandre Courbotc6ad83f2022-02-07 19:45:31 +0900403 let vhost_config = VhostVsockConfig {
404 device: cfg
405 .vhost_vsock_device
406 .clone()
407 .unwrap_or(VhostVsockDeviceParameter::default()),
408 cid,
409 };
410 devs.push(create_vhost_vsock_device(cfg, &vhost_config)?);
Zach Reizneraa575662018-08-15 10:46:32 -0700411 }
412
Woody Chow5890b702021-02-12 14:57:02 +0900413 for vhost_user_fs in &cfg.vhost_user_fs {
Daniel Verkamp166d1dd2021-08-19 17:05:29 -0700414 devs.push(create_vhost_user_fs_device(cfg, vhost_user_fs)?);
Woody Chow5890b702021-02-12 14:57:02 +0900415 }
416
Woody Chow1b16db12021-04-02 16:59:59 +0900417 #[cfg(feature = "audio")]
418 for vhost_user_snd in &cfg.vhost_user_snd {
419 devs.push(create_vhost_user_snd_device(cfg, vhost_user_snd)?);
420 }
421
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900422 for shared_dir in &cfg.shared_dirs {
423 let SharedDir {
424 src,
425 tag,
426 kind,
427 uid_map,
428 gid_map,
Chirantan Ekbote75ba8752020-10-27 18:33:02 +0900429 fs_cfg,
430 p9_cfg,
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900431 } = shared_dir;
David Tolnay2b089fc2019-03-04 15:33:22 -0800432
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900433 let dev = match kind {
Keiichi Watanabeeefe7fb2020-11-17 17:58:35 +0900434 SharedDirKind::FS => {
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800435 let device_tube = fs_device_tubes.remove(0);
436 create_fs_device(cfg, uid_map, gid_map, src, tag, fs_cfg.clone(), device_tube)?
Keiichi Watanabeeefe7fb2020-11-17 17:58:35 +0900437 }
Chirantan Ekbote75ba8752020-10-27 18:33:02 +0900438 SharedDirKind::P9 => create_9p_device(cfg, uid_map, gid_map, src, tag, p9_cfg.clone())?,
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900439 };
440 devs.push(dev);
David Tolnay2b089fc2019-03-04 15:33:22 -0800441 }
442
JaeMan Parkeb9cc532021-07-02 15:02:59 +0900443 if let Some(vhost_user_mac80211_hwsim) = &cfg.vhost_user_mac80211_hwsim {
444 devs.push(create_vhost_user_mac80211_hwsim_device(
445 cfg,
Daniel Verkamp166d1dd2021-08-19 17:05:29 -0700446 vhost_user_mac80211_hwsim,
JaeMan Parkeb9cc532021-07-02 15:02:59 +0900447 )?);
448 }
449
Jorge E. Moreirad4562d02021-06-28 16:21:12 -0700450 #[cfg(feature = "audio")]
451 if let Some(path) = &cfg.sound {
Daniel Verkamp166d1dd2021-08-19 17:05:29 -0700452 devs.push(create_sound_device(path, cfg)?);
Jorge E. Moreirad4562d02021-06-28 16:21:12 -0700453 }
454
David Tolnay2b089fc2019-03-04 15:33:22 -0800455 Ok(devs)
456}
457
458fn create_devices(
Trent Begin17ccaad2019-04-17 13:51:25 -0600459 cfg: &Config,
Steven Richmanf32d0b42020-06-20 21:45:32 -0700460 vm: &mut impl Vm,
Jakub Starona3411ea2019-04-24 10:55:25 -0700461 resources: &mut SystemAllocator,
Michael Hoyle685316f2020-09-16 15:29:20 -0700462 exit_evt: &Event,
Vineeth Pillai9a3d2dc2022-02-18 14:10:16 +0000463 panic_wrtube: Tube,
Haiwei Li09b7b8e2022-02-18 18:16:05 +0800464 iommu_attached_endpoints: &mut BTreeMap<u32, Arc<Mutex<Box<dyn MemoryMapperTrait>>>>,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800465 control_tubes: &mut Vec<TaggedControlTube>,
466 wayland_device_tube: Tube,
467 gpu_device_tube: Tube,
Alexandre Courbote55b7912022-03-04 16:54:38 +0900468 // Tuple content: (host-side GPU tube, device-side GPU tube, device-side control tube).
469 vhost_user_gpu_tubes: Vec<(Tube, Tube, Tube)>,
Andrew Walbran3cd93602022-01-25 13:59:23 +0000470 balloon_device_tube: Option<Tube>,
David Stevens06d157a2022-01-13 23:44:48 +0900471 init_balloon_size: u64,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800472 disk_device_tubes: &mut Vec<Tube>,
473 pmem_device_tubes: &mut Vec<Tube>,
474 fs_device_tubes: &mut Vec<Tube>,
Daniel Verkampf1439d42021-05-21 13:55:10 -0700475 #[cfg(feature = "usb")] usb_provider: HostBackendDeviceProvider,
Lingfeng Yangd6ac1ab2020-01-31 13:55:35 -0800476 map_request: Arc<Mutex<Option<ExternalMapping>>>,
Dmitry Torokhov9cbe5432022-01-25 19:17:07 -0800477 #[cfg(feature = "gpu")] render_server_fd: Option<SafeDescriptor>,
Abhishek Bhardwaj90fd1642021-11-24 18:26:37 -0800478 vvu_proxy_device_tubes: &mut Vec<Tube>,
Tomasz Nowickiab86d522021-09-22 05:50:46 +0000479) -> DeviceResult<Vec<(Box<dyn BusDeviceObj>, Option<Minijail>)>> {
Chuanxiao Dong146a13b2021-12-09 12:59:54 +0800480 let mut devices: Vec<(Box<dyn BusDeviceObj>, Option<Minijail>)> = Vec::new();
481 let mut balloon_inflate_tube: Option<Tube> = None;
Zide Chen5deee482021-04-19 11:06:01 -0700482 if !cfg.vfio.is_empty() {
Chuanxiao Donga8d427b2022-01-07 10:26:24 +0800483 let mut coiommu_attached_endpoints = Vec::new();
Zide Chendfc4b882021-03-10 16:35:37 -0800484
Tomasz Nowicki71aca792021-06-09 18:53:49 +0000485 for vfio_dev in cfg
486 .vfio
487 .iter()
488 .filter(|dev| dev.get_type() == VfioType::Pci)
489 {
490 let vfio_path = &vfio_dev.vfio_path;
Zide Chen5deee482021-04-19 11:06:01 -0700491 let (vfio_pci_device, jail) = create_vfio_device(
492 cfg,
493 vm,
494 resources,
495 control_tubes,
496 vfio_path.as_path(),
Xiong Zhangf82f2dc2021-05-21 16:54:12 +0800497 None,
Victor Ding3f749592022-03-18 05:44:20 +0000498 vfio_dev.guest_address(),
Haiwei Li09b7b8e2022-02-18 18:16:05 +0800499 iommu_attached_endpoints,
Chuanxiao Donga8d427b2022-01-07 10:26:24 +0800500 Some(&mut coiommu_attached_endpoints),
501 vfio_dev.iommu_dev_type(),
Zide Chen5deee482021-04-19 11:06:01 -0700502 )?;
Zide Chendfc4b882021-03-10 16:35:37 -0800503
Tomasz Nowickiab86d522021-09-22 05:50:46 +0000504 devices.push((vfio_pci_device, jail));
Zide Chen5deee482021-04-19 11:06:01 -0700505 }
Zide Chendfc4b882021-03-10 16:35:37 -0800506
Tomasz Nowicki344eb142021-09-22 05:51:58 +0000507 for vfio_dev in cfg
508 .vfio
509 .iter()
510 .filter(|dev| dev.get_type() == VfioType::Platform)
511 {
512 let vfio_path = &vfio_dev.vfio_path;
513 let (vfio_plat_dev, jail) = create_vfio_platform_device(
514 cfg,
515 vm,
516 resources,
517 control_tubes,
518 vfio_path.as_path(),
Haiwei Li09b7b8e2022-02-18 18:16:05 +0800519 iommu_attached_endpoints,
Chuanxiao Donga8d427b2022-01-07 10:26:24 +0800520 IommuDevType::NoIommu, // Virtio IOMMU is not supported yet
Tomasz Nowicki344eb142021-09-22 05:51:58 +0000521 )?;
522
523 devices.push((Box::new(vfio_plat_dev), jail));
524 }
525
Chuanxiao Dongcb03ec62022-01-20 08:25:38 +0800526 if !coiommu_attached_endpoints.is_empty() || !iommu_attached_endpoints.is_empty() {
527 let mut buf = mem::MaybeUninit::<libc::rlimit>::zeroed();
528 let res = unsafe { libc::getrlimit(libc::RLIMIT_MEMLOCK, buf.as_mut_ptr()) };
529 if res == 0 {
530 let limit = unsafe { buf.assume_init() };
531 let rlim_new = limit
532 .rlim_cur
533 .saturating_add(vm.get_memory().memory_size() as libc::rlim_t);
534 let rlim_max = max(limit.rlim_max, rlim_new);
535 if limit.rlim_cur < rlim_new {
536 let limit_arg = libc::rlimit {
537 rlim_cur: rlim_new as libc::rlim_t,
538 rlim_max: rlim_max as libc::rlim_t,
539 };
540 let res = unsafe { libc::setrlimit(libc::RLIMIT_MEMLOCK, &limit_arg) };
541 if res != 0 {
542 bail!("Set rlimit failed");
543 }
544 }
545 } else {
546 bail!("Get rlimit failed");
547 }
548 }
549
Chuanxiao Donga8d427b2022-01-07 10:26:24 +0800550 if !coiommu_attached_endpoints.is_empty() {
551 let vfio_container =
552 VfioCommonSetup::vfio_get_container(IommuDevType::CoIommu, None as Option<&Path>)
553 .context("failed to get vfio container")?;
554 let (coiommu_host_tube, coiommu_device_tube) =
555 Tube::pair().context("failed to create coiommu tube")?;
556 control_tubes.push(TaggedControlTube::VmMemory(coiommu_host_tube));
557 let vcpu_count = cfg.vcpu_count.unwrap_or(1) as u64;
Chuanxiao Dong146a13b2021-12-09 12:59:54 +0800558 let (coiommu_tube, balloon_tube) =
559 Tube::pair().context("failed to create coiommu tube")?;
560 balloon_inflate_tube = Some(balloon_tube);
Chuanxiao Donga8d427b2022-01-07 10:26:24 +0800561 let dev = CoIommuDev::new(
562 vm.get_memory().clone(),
563 vfio_container,
564 coiommu_device_tube,
Chuanxiao Dong146a13b2021-12-09 12:59:54 +0800565 coiommu_tube,
Chuanxiao Donga8d427b2022-01-07 10:26:24 +0800566 coiommu_attached_endpoints,
567 vcpu_count,
Chuanxiao Dongd4468612022-01-14 14:21:17 +0800568 cfg.coiommu_param.unwrap_or_default(),
Chuanxiao Donga8d427b2022-01-07 10:26:24 +0800569 )
570 .context("failed to create coiommu device")?;
571
Alexandre Courbot6a8f6562022-03-24 14:43:48 +0900572 devices.push((Box::new(dev), simple_jail(&cfg.jail_config, "coiommu")?));
Chuanxiao Donga8d427b2022-01-07 10:26:24 +0800573 }
Xiong Zhang17b0daf2019-04-23 17:14:50 +0800574 }
575
Chuanxiao Dong146a13b2021-12-09 12:59:54 +0800576 let stubs = create_virtio_devices(
577 cfg,
578 vm,
579 resources,
580 exit_evt,
581 wayland_device_tube,
582 gpu_device_tube,
583 vhost_user_gpu_tubes,
584 balloon_device_tube,
585 balloon_inflate_tube,
David Stevens06d157a2022-01-13 23:44:48 +0900586 init_balloon_size,
Chuanxiao Dong146a13b2021-12-09 12:59:54 +0800587 disk_device_tubes,
588 pmem_device_tubes,
589 map_request,
590 fs_device_tubes,
Dmitry Torokhov9cbe5432022-01-25 19:17:07 -0800591 #[cfg(feature = "gpu")]
592 render_server_fd,
Abhishek Bhardwaj90fd1642021-11-24 18:26:37 -0800593 vvu_proxy_device_tubes,
Chuanxiao Dong146a13b2021-12-09 12:59:54 +0800594 )?;
595
596 for stub in stubs {
597 let (msi_host_tube, msi_device_tube) = Tube::pair().context("failed to create tube")?;
598 control_tubes.push(TaggedControlTube::VmIrq(msi_host_tube));
599 let dev = VirtioPciDevice::new(vm.get_memory().clone(), stub.dev, msi_device_tube)
600 .context("failed to create virtio pci dev")?;
601 let dev = Box::new(dev) as Box<dyn BusDeviceObj>;
602 devices.push((dev, stub.jail));
603 }
604
605 #[cfg(feature = "audio")]
606 for ac97_param in &cfg.ac97_parameters {
607 let dev = Ac97Dev::try_new(vm.get_memory().clone(), ac97_param.clone())
608 .context("failed to create ac97 device")?;
Alexandre Courbot6a8f6562022-03-24 14:43:48 +0900609 let jail = simple_jail(&cfg.jail_config, dev.minijail_policy())?;
Chuanxiao Dong146a13b2021-12-09 12:59:54 +0800610 devices.push((Box::new(dev), jail));
611 }
612
613 #[cfg(feature = "usb")]
Sebastian Ene0440d352022-02-04 12:23:56 +0000614 if cfg.usb {
Chuanxiao Dong146a13b2021-12-09 12:59:54 +0800615 // Create xhci controller.
616 let usb_controller = Box::new(XhciController::new(vm.get_memory().clone(), usb_provider));
Alexandre Courbot6a8f6562022-03-24 14:43:48 +0900617 devices.push((usb_controller, simple_jail(&cfg.jail_config, "xhci")?));
Chuanxiao Dong146a13b2021-12-09 12:59:54 +0800618 }
619
Mattias Nisslerde2c6402021-10-21 12:05:29 +0000620 for params in &cfg.stub_pci_devices {
621 // Stub devices don't need jailing since they don't do anything.
622 devices.push((Box::new(StubPciDevice::new(params)), None));
623 }
624
Vineeth Pillai9a3d2dc2022-02-18 14:10:16 +0000625 devices.push((Box::new(PvPanicPciDevice::new(panic_wrtube)), None));
Tomasz Nowickiab86d522021-09-22 05:50:46 +0000626 Ok(devices)
David Tolnay2b089fc2019-03-04 15:33:22 -0800627}
628
Mattias Nisslerbbd91d02021-12-07 08:57:45 +0000629fn create_file_backed_mappings(
630 cfg: &Config,
631 vm: &mut impl Vm,
632 resources: &mut SystemAllocator,
633) -> Result<()> {
634 for mapping in &cfg.file_backed_mappings {
635 let file = OpenOptions::new()
636 .read(true)
637 .write(mapping.writable)
638 .custom_flags(if mapping.sync { libc::O_SYNC } else { 0 })
639 .open(&mapping.path)
640 .context("failed to open file for file-backed mapping")?;
641 let prot = if mapping.writable {
642 Protection::read_write()
643 } else {
644 Protection::read()
645 };
646 let size = mapping
647 .size
648 .try_into()
649 .context("Invalid size for file-backed mapping")?;
650 let memory_mapping = MemoryMappingBuilder::new(size)
651 .from_file(&file)
652 .offset(mapping.offset)
653 .protection(prot)
654 .build()
655 .context("failed to map backing file for file-backed mapping")?;
656
Daniel Verkampde4d7292022-03-01 15:22:38 -0800657 match resources.mmio_allocator_any().allocate_at(
658 mapping.address,
659 mapping.size,
660 Alloc::FileBacked(mapping.address),
661 "file-backed mapping".to_owned(),
662 ) {
663 // OutOfSpace just means that this mapping is not in the MMIO regions at all, so don't
664 // consider it an error.
665 // TODO(b/222769529): Reserve this region in a global memory address space allocator once
666 // we have that so nothing else can accidentally overlap with it.
667 Ok(()) | Err(resources::Error::OutOfSpace) => {}
668 e => e.context("failed to allocate guest address for file-backed mapping")?,
669 }
Mattias Nisslerbbd91d02021-12-07 08:57:45 +0000670
671 vm.add_memory_region(
672 GuestAddress(mapping.address),
673 Box::new(memory_mapping),
674 !mapping.writable,
675 /* log_dirty_pages = */ false,
676 )
677 .context("failed to configure file-backed mapping")?;
678 }
679
680 Ok(())
681}
682
Anton Romanov33334412022-03-22 17:48:18 +0000683#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
Xiong Zhangf7874712021-12-24 10:53:59 +0800684fn create_pcie_root_port(
Xiong Zhang626f0142022-03-12 16:05:17 +0800685 host_pcie_rp: Vec<HostPcieRootPortParameters>,
Xiong Zhangf7874712021-12-24 10:53:59 +0800686 sys_allocator: &mut SystemAllocator,
687 control_tubes: &mut Vec<TaggedControlTube>,
688 devices: &mut Vec<(Box<dyn BusDeviceObj>, Option<Minijail>)>,
689 hp_vec: &mut Vec<Arc<Mutex<dyn HotPlugBus>>>,
Haiwei Li09b7b8e2022-02-18 18:16:05 +0800690 hp_endpoints_ranges: &mut Vec<RangeInclusive<u32>>,
Xiong Zhang626f0142022-03-12 16:05:17 +0800691 gpe_notify_devs: &mut Vec<(u32, Arc<Mutex<dyn GpeNotify>>)>,
Xiong Zhangf7874712021-12-24 10:53:59 +0800692) -> Result<()> {
693 if host_pcie_rp.is_empty() {
694 // user doesn't specify host pcie root port which link to this virtual pcie rp,
695 // find the empty bus and create a total virtual pcie rp
Haiwei Lie35d4652022-02-10 15:39:33 +0800696 let mut hp_sec_bus = 0u8;
697 // Create Pcie Root Port for non-root buses, each non-root bus device will be
698 // connected behind a virtual pcie root port.
699 for i in 1..255 {
700 if sys_allocator.pci_bus_empty(i) {
701 if hp_sec_bus == 0 {
702 hp_sec_bus = i;
703 }
704 continue;
705 }
706 let pcie_root_port = Arc::new(Mutex::new(PcieRootPort::new(i, false)));
707 let (msi_host_tube, msi_device_tube) = Tube::pair().context("failed to create tube")?;
708 control_tubes.push(TaggedControlTube::VmIrq(msi_host_tube));
709 let pci_bridge = Box::new(PciBridge::new(pcie_root_port.clone(), msi_device_tube));
710 // no ipc is used if the root port disables hotplug
711 devices.push((pci_bridge, None));
712 }
713
714 // Create Pcie Root Port for hot-plug
715 if hp_sec_bus == 0 {
716 return Err(anyhow!("no more addresses are available"));
717 }
718 let pcie_root_port = Arc::new(Mutex::new(PcieRootPort::new(hp_sec_bus, true)));
Xiong Zhangf7874712021-12-24 10:53:59 +0800719 let (msi_host_tube, msi_device_tube) = Tube::pair().context("failed to create tube")?;
720 control_tubes.push(TaggedControlTube::VmIrq(msi_host_tube));
721 let pci_bridge = Box::new(PciBridge::new(pcie_root_port.clone(), msi_device_tube));
722
Haiwei Li09b7b8e2022-02-18 18:16:05 +0800723 hp_endpoints_ranges.push(RangeInclusive::new(
724 PciAddress {
725 bus: pci_bridge.get_secondary_num(),
726 dev: 0,
727 func: 0,
728 }
729 .to_u32(),
730 PciAddress {
731 bus: pci_bridge.get_subordinate_num(),
732 dev: 32,
733 func: 8,
734 }
735 .to_u32(),
736 ));
737
Xiong Zhangf7874712021-12-24 10:53:59 +0800738 devices.push((pci_bridge, None));
739 hp_vec.push(pcie_root_port as Arc<Mutex<dyn HotPlugBus>>);
740 } else {
741 // user specify host pcie root port which link to this virtual pcie rp,
742 // reserve the host pci BDF and create a virtual pcie RP with some attrs same as host
Xiong Zhang626f0142022-03-12 16:05:17 +0800743 for host_pcie in host_pcie_rp.iter() {
Xiong Zhangcdffe492021-12-24 15:13:30 +0800744 let (vm_host_tube, vm_device_tube) = Tube::pair().context("failed to create tube")?;
Xiong Zhang626f0142022-03-12 16:05:17 +0800745 let pcie_host = PcieHostRootPort::new(host_pcie.host_path.as_path(), vm_device_tube)?;
Xiong Zhangd6de3192022-02-16 13:24:06 +0800746 let bus_range = pcie_host.get_bus_range();
747 let mut slot_implemented = true;
748 for i in bus_range.secondary..=bus_range.subordinate {
749 // if this bus is occupied by one vfio-pci device, this vfio-pci device is
750 // connected to a pci bridge on host statically, then it should be connected
751 // to a virtual pci bridge in guest statically, this bridge won't have
752 // hotplug capability and won't use slot.
753 if !sys_allocator.pci_bus_empty(i) {
754 slot_implemented = false;
Haiwei Lie4a9e822022-03-24 14:18:32 +0800755 break;
Xiong Zhangd6de3192022-02-16 13:24:06 +0800756 }
757 }
Xiong Zhang626f0142022-03-12 16:05:17 +0800758
Xiong Zhangd6de3192022-02-16 13:24:06 +0800759 let pcie_root_port = Arc::new(Mutex::new(PcieRootPort::new_from_host(
760 pcie_host,
761 slot_implemented,
762 )?));
Xiong Zhangcdffe492021-12-24 15:13:30 +0800763 control_tubes.push(TaggedControlTube::Vm(vm_host_tube));
Xiong Zhangf7874712021-12-24 10:53:59 +0800764
765 let (msi_host_tube, msi_device_tube) = Tube::pair().context("failed to create tube")?;
766 control_tubes.push(TaggedControlTube::VmIrq(msi_host_tube));
767 let mut pci_bridge = Box::new(PciBridge::new(pcie_root_port.clone(), msi_device_tube));
768 // early reservation for host pcie root port devices.
769 let rootport_addr = pci_bridge.allocate_address(sys_allocator);
770 if rootport_addr.is_err() {
771 warn!(
772 "address reservation failed for hot pcie root port {}",
773 pci_bridge.debug_label()
774 );
775 }
776
Haiwei Lie4a9e822022-03-24 14:18:32 +0800777 // Only append the sub pci range of a hot-pluggable root port to virtio-iommu
778 if slot_implemented {
779 hp_endpoints_ranges.push(RangeInclusive::new(
780 PciAddress {
781 bus: pci_bridge.get_secondary_num(),
782 dev: 0,
783 func: 0,
784 }
785 .to_u32(),
786 PciAddress {
787 bus: pci_bridge.get_subordinate_num(),
788 dev: 32,
789 func: 8,
790 }
791 .to_u32(),
792 ));
793 }
Haiwei Li09b7b8e2022-02-18 18:16:05 +0800794
Xiong Zhangf7874712021-12-24 10:53:59 +0800795 devices.push((pci_bridge, None));
Xiong Zhang626f0142022-03-12 16:05:17 +0800796 if slot_implemented {
797 if let Some(gpe) = host_pcie.hp_gpe {
798 gpe_notify_devs
799 .push((gpe, pcie_root_port.clone() as Arc<Mutex<dyn GpeNotify>>));
800 }
801 hp_vec.push(pcie_root_port as Arc<Mutex<dyn HotPlugBus>>);
802 }
Xiong Zhangf7874712021-12-24 10:53:59 +0800803 }
804 }
805
806 Ok(())
807}
808
Zach Reiznera90649a2021-03-31 12:56:08 -0700809fn setup_vm_components(cfg: &Config) -> Result<VmComponents> {
David Tolnay2b089fc2019-03-04 15:33:22 -0800810 let initrd_image = if let Some(initrd_path) = &cfg.initrd_path {
Andrew Walbranbc55e302021-07-13 17:35:10 +0100811 Some(
Daniel Verkamped6b27a2022-03-25 14:06:05 -0700812 open_file(initrd_path, OpenOptions::new().read(true))
813 .with_context(|| format!("failed to open initrd {}", initrd_path.display()))?,
Andrew Walbranbc55e302021-07-13 17:35:10 +0100814 )
Daniel Verkampe403f5c2018-12-11 16:29:26 -0800815 } else {
816 None
817 };
818
Cody Schuffelen6d1ab502019-05-21 12:12:38 -0700819 let vm_image = match cfg.executable_path {
Andrew Walbranbc55e302021-07-13 17:35:10 +0100820 Some(Executable::Kernel(ref kernel_path)) => VmImage::Kernel(
Daniel Verkamped6b27a2022-03-25 14:06:05 -0700821 open_file(kernel_path, OpenOptions::new().read(true)).with_context(|| {
822 format!("failed to open kernel image {}", kernel_path.display())
823 })?,
Andrew Walbranbc55e302021-07-13 17:35:10 +0100824 ),
825 Some(Executable::Bios(ref bios_path)) => VmImage::Bios(
Daniel Verkamped6b27a2022-03-25 14:06:05 -0700826 open_file(bios_path, OpenOptions::new().read(true))
Daniel Verkamp6b298582021-08-16 15:37:11 -0700827 .with_context(|| format!("failed to open bios {}", bios_path.display()))?,
Andrew Walbranbc55e302021-07-13 17:35:10 +0100828 ),
Cody Schuffelen6d1ab502019-05-21 12:12:38 -0700829 _ => panic!("Did not receive a bios or kernel, should be impossible."),
830 };
831
Will Deaconc48e7832021-07-30 19:03:06 +0100832 let swiotlb = if let Some(size) = cfg.swiotlb {
833 Some(
834 size.checked_mul(1024 * 1024)
Daniel Verkamp6b298582021-08-16 15:37:11 -0700835 .ok_or_else(|| anyhow!("requested swiotlb size too large"))?,
Will Deaconc48e7832021-07-30 19:03:06 +0100836 )
837 } else {
838 match cfg.protected_vm {
Andrew Walbran0bbbb682021-12-13 13:42:07 +0000839 ProtectionType::Protected | ProtectionType::ProtectedWithoutFirmware => {
840 Some(64 * 1024 * 1024)
841 }
Will Deaconc48e7832021-07-30 19:03:06 +0100842 ProtectionType::Unprotected => None,
843 }
844 };
845
Zach Reiznera90649a2021-03-31 12:56:08 -0700846 Ok(VmComponents {
Daniel Verkamp6a847062019-11-26 13:16:35 -0800847 memory_size: cfg
848 .memory
849 .unwrap_or(256)
850 .checked_mul(1024 * 1024)
Daniel Verkamp6b298582021-08-16 15:37:11 -0700851 .ok_or_else(|| anyhow!("requested memory size too large"))?,
Will Deaconc48e7832021-07-30 19:03:06 +0100852 swiotlb,
Dylan Reid059a1882018-07-23 17:58:09 -0700853 vcpu_count: cfg.vcpu_count.unwrap_or(1),
Daniel Verkamp107edb32019-04-05 09:58:48 -0700854 vcpu_affinity: cfg.vcpu_affinity.clone(),
Daniel Verkamp8a72afc2021-03-15 17:55:52 -0700855 cpu_clusters: cfg.cpu_clusters.clone(),
856 cpu_capacity: cfg.cpu_capacity.clone(),
Dmytro Maluka74031b42022-02-25 18:00:17 +0000857 #[cfg(feature = "direct")]
Dmytro Maluka6cea2c72022-02-25 18:22:17 +0000858 direct_gpe: cfg.direct_gpe.clone(),
Suleiman Souhlal015c3c12020-10-07 14:15:41 +0900859 no_smt: cfg.no_smt,
Sergey Senozhatsky1e369c52021-04-13 20:23:51 +0900860 hugepages: cfg.hugepages,
Cody Schuffelen6d1ab502019-05-21 12:12:38 -0700861 vm_image,
Tristan Muntsinger4133b012018-12-21 16:01:56 -0800862 android_fstab: cfg
863 .android_fstab
864 .as_ref()
Daniel Verkamp6b298582021-08-16 15:37:11 -0700865 .map(|x| {
866 File::open(x)
867 .with_context(|| format!("failed to open android fstab file {}", x.display()))
868 })
Tristan Muntsinger4133b012018-12-21 16:01:56 -0800869 .map_or(Ok(None), |v| v.map(Some))?,
Kansho Nishida282115b2019-12-18 13:13:14 +0900870 pstore: cfg.pstore.clone(),
Daniel Verkampe403f5c2018-12-11 16:29:26 -0800871 initrd_image,
Daniel Verkampaac28132018-10-15 14:58:48 -0700872 extra_kernel_params: cfg.params.clone(),
Tomasz Jeznach42644642020-05-20 23:27:59 -0700873 acpi_sdts: cfg
874 .acpi_tables
875 .iter()
Daniel Verkamp6b298582021-08-16 15:37:11 -0700876 .map(|path| {
877 SDT::from_file(path)
878 .with_context(|| format!("failed to open ACPI file {}", path.display()))
879 })
Tomasz Jeznach42644642020-05-20 23:27:59 -0700880 .collect::<Result<Vec<SDT>>>()?,
Kansho Nishidaab205af2020-08-13 18:17:50 +0900881 rt_cpus: cfg.rt_cpus.clone(),
Suleiman Souhlal63630e82021-02-18 11:53:11 +0900882 delay_rt: cfg.delay_rt,
Will Deacon7d2b8ac2020-10-06 18:51:12 +0100883 protected_vm: cfg.protected_vm,
Keiichi Watanabec5262e92020-10-21 15:57:33 +0900884 #[cfg(all(target_arch = "x86_64", feature = "gdb"))]
Zach Reiznera90649a2021-03-31 12:56:08 -0700885 gdb: None,
Tomasz Jeznachccb26942021-03-30 22:44:11 -0700886 dmi_path: cfg.dmi_path.clone(),
Tomasz Jeznachd93c29f2021-04-12 11:00:24 -0700887 no_legacy: cfg.no_legacy,
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +0800888 host_cpu_topology: cfg.host_cpu_topology,
Grzegorz Jaszczykd33874e2022-02-11 18:27:29 +0000889 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
890 force_s2idle: cfg.force_s2idle,
Zach Reiznera90649a2021-03-31 12:56:08 -0700891 })
892}
893
Andrew Walbranb28ae8e2022-01-17 14:33:10 +0000894#[derive(Copy, Clone, Debug, Eq, PartialEq)]
Dmitry Torokhovf75699f2021-12-03 11:19:13 -0800895pub enum ExitState {
896 Reset,
897 Stop,
Andrew Walbran1a19c672022-01-24 17:24:10 +0000898 Crash,
Vineeth Pillai9a3d2dc2022-02-18 14:10:16 +0000899 GuestPanic,
Dmitry Torokhovf75699f2021-12-03 11:19:13 -0800900}
901
Daniel Verkamp5586ff52022-02-24 16:34:55 -0800902// Remove ranges in `guest_mem_layout` that overlap with ranges in `file_backed_mappings`.
903// Returns the updated guest memory layout.
904fn punch_holes_in_guest_mem_layout_for_mappings(
905 guest_mem_layout: Vec<(GuestAddress, u64)>,
906 file_backed_mappings: &[FileBackedMappingParameters],
907) -> Vec<(GuestAddress, u64)> {
908 // Create a set containing (start, end) pairs with exclusive end (end = start + size; the byte
909 // at end is not included in the range).
910 let mut layout_set = BTreeSet::new();
911 for (addr, size) in &guest_mem_layout {
912 layout_set.insert((addr.offset(), addr.offset() + size));
913 }
914
915 for mapping in file_backed_mappings {
916 let mapping_start = mapping.address;
917 let mapping_end = mapping_start + mapping.size;
918
919 // Repeatedly split overlapping guest memory regions until no overlaps remain.
920 while let Some((range_start, range_end)) = layout_set
921 .iter()
922 .find(|&&(range_start, range_end)| {
923 mapping_start < range_end && mapping_end > range_start
924 })
925 .cloned()
926 {
927 layout_set.remove(&(range_start, range_end));
928
929 if range_start < mapping_start {
930 layout_set.insert((range_start, mapping_start));
931 }
932 if range_end > mapping_end {
933 layout_set.insert((mapping_end, range_end));
934 }
935 }
936 }
937
938 // Build the final guest memory layout from the modified layout_set.
939 layout_set
940 .iter()
941 .map(|(start, end)| (GuestAddress(*start), end - start))
942 .collect()
943}
944
Dmitry Torokhovf75699f2021-12-03 11:19:13 -0800945pub fn run_config(cfg: Config) -> Result<ExitState> {
Zach Reiznerdc748482021-04-14 13:59:30 -0700946 let components = setup_vm_components(&cfg)?;
947
948 let guest_mem_layout =
Daniel Verkamp6b298582021-08-16 15:37:11 -0700949 Arch::guest_memory_layout(&components).context("failed to create guest memory layout")?;
Daniel Verkamp5586ff52022-02-24 16:34:55 -0800950
951 let guest_mem_layout =
952 punch_holes_in_guest_mem_layout_for_mappings(guest_mem_layout, &cfg.file_backed_mappings);
953
Daniel Verkamp6b298582021-08-16 15:37:11 -0700954 let guest_mem = GuestMemory::new(&guest_mem_layout).context("failed to create guest memory")?;
Zach Reiznerdc748482021-04-14 13:59:30 -0700955 let mut mem_policy = MemoryPolicy::empty();
956 if components.hugepages {
957 mem_policy |= MemoryPolicy::USE_HUGEPAGES;
958 }
Quentin Perret26203802021-12-02 09:48:43 +0000959 guest_mem.set_memory_policy(mem_policy);
Daniel Verkamp6b298582021-08-16 15:37:11 -0700960 let kvm = Kvm::new_with_path(&cfg.kvm_device_path).context("failed to create kvm")?;
Andrew Walbran00f1c9f2021-12-10 17:13:08 +0000961 let vm = KvmVm::new(&kvm, guest_mem, components.protected_vm).context("failed to create vm")?;
Junichi Uekawab3a094e2022-03-29 15:41:47 +0900962
963 if !cfg.userspace_msr.is_empty() {
964 vm.enable_userspace_msr()
965 .context("failed to enable userspace MSR handling, do you have kernel 5.10 or later")?;
966 }
967
Andrew Walbrane79aba12022-01-27 14:12:35 +0000968 // Check that the VM was actually created in protected mode as expected.
969 if cfg.protected_vm != ProtectionType::Unprotected && !vm.check_capability(VmCap::Protected) {
970 bail!("Failed to create protected VM");
971 }
Daniel Verkamp6b298582021-08-16 15:37:11 -0700972 let vm_clone = vm.try_clone().context("failed to clone vm")?;
Zach Reiznerdc748482021-04-14 13:59:30 -0700973
974 enum KvmIrqChip {
975 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
976 Split(KvmSplitIrqChip),
977 Kernel(KvmKernelIrqChip),
978 }
979
980 impl KvmIrqChip {
981 fn as_mut(&mut self) -> &mut dyn IrqChipArch {
982 match self {
983 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
984 KvmIrqChip::Split(i) => i,
985 KvmIrqChip::Kernel(i) => i,
986 }
987 }
988 }
989
990 let ioapic_host_tube;
991 let mut irq_chip = if cfg.split_irqchip {
992 #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
993 unimplemented!("KVM split irqchip mode only supported on x86 processors");
994 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
995 {
Daniel Verkamp6b298582021-08-16 15:37:11 -0700996 let (host_tube, ioapic_device_tube) = Tube::pair().context("failed to create tube")?;
Zach Reiznerdc748482021-04-14 13:59:30 -0700997 ioapic_host_tube = Some(host_tube);
998 KvmIrqChip::Split(
999 KvmSplitIrqChip::new(
1000 vm_clone,
1001 components.vcpu_count,
1002 ioapic_device_tube,
1003 Some(120),
1004 )
Daniel Verkamp6b298582021-08-16 15:37:11 -07001005 .context("failed to create IRQ chip")?,
Zach Reiznerdc748482021-04-14 13:59:30 -07001006 )
1007 }
1008 } else {
1009 ioapic_host_tube = None;
1010 KvmIrqChip::Kernel(
Daniel Verkamp6b298582021-08-16 15:37:11 -07001011 KvmKernelIrqChip::new(vm_clone, components.vcpu_count)
1012 .context("failed to create IRQ chip")?,
Zach Reiznerdc748482021-04-14 13:59:30 -07001013 )
1014 };
1015
1016 run_vm::<KvmVcpu, KvmVm>(cfg, components, vm, irq_chip.as_mut(), ioapic_host_tube)
1017}
1018
1019fn run_vm<Vcpu, V>(
Zach Reiznera90649a2021-03-31 12:56:08 -07001020 cfg: Config,
1021 #[allow(unused_mut)] mut components: VmComponents,
Zach Reiznerdc748482021-04-14 13:59:30 -07001022 mut vm: V,
1023 irq_chip: &mut dyn IrqChipArch,
1024 ioapic_host_tube: Option<Tube>,
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08001025) -> Result<ExitState>
Zach Reiznera90649a2021-03-31 12:56:08 -07001026where
1027 Vcpu: VcpuArch + 'static,
1028 V: VmArch + 'static,
Zach Reiznera90649a2021-03-31 12:56:08 -07001029{
Alexandre Courbot6a8f6562022-03-24 14:43:48 +09001030 if cfg.jail_config.is_some() {
Zach Reiznera90649a2021-03-31 12:56:08 -07001031 // Printing something to the syslog before entering minijail so that libc's syslogger has a
1032 // chance to open files necessary for its operation, like `/etc/localtime`. After jailing,
1033 // access to those files will not be possible.
1034 info!("crosvm entering multiprocess mode");
1035 }
1036
Daniel Verkampf1439d42021-05-21 13:55:10 -07001037 #[cfg(feature = "usb")]
Zach Reiznera90649a2021-03-31 12:56:08 -07001038 let (usb_control_tube, usb_provider) =
Daniel Verkamp6b298582021-08-16 15:37:11 -07001039 HostBackendDeviceProvider::new().context("failed to create usb provider")?;
Daniel Verkampf1439d42021-05-21 13:55:10 -07001040
Zach Reiznera90649a2021-03-31 12:56:08 -07001041 // Masking signals is inherently dangerous, since this can persist across clones/execs. Do this
1042 // before any jailed devices have been spawned, so that we can catch any of them that fail very
1043 // quickly.
Daniel Verkamp6b298582021-08-16 15:37:11 -07001044 let sigchld_fd = SignalFd::new(libc::SIGCHLD).context("failed to create signalfd")?;
Dylan Reid059a1882018-07-23 17:58:09 -07001045
Zach Reiznera60744b2019-02-13 17:33:32 -08001046 let control_server_socket = match &cfg.socket_path {
1047 Some(path) => Some(UnlinkUnixSeqpacketListener(
Daniel Verkamp6b298582021-08-16 15:37:11 -07001048 UnixSeqpacketListener::bind(path).context("failed to create control server")?,
Zach Reiznera60744b2019-02-13 17:33:32 -08001049 )),
1050 None => None,
Dylan Reid059a1882018-07-23 17:58:09 -07001051 };
Zach Reiznera60744b2019-02-13 17:33:32 -08001052
Zach Reiznera90649a2021-03-31 12:56:08 -07001053 let mut control_tubes = Vec::new();
1054
1055 #[cfg(all(target_arch = "x86_64", feature = "gdb"))]
1056 if let Some(port) = cfg.gdb {
1057 // GDB needs a control socket to interrupt vcpus.
Daniel Verkamp6b298582021-08-16 15:37:11 -07001058 let (gdb_host_tube, gdb_control_tube) = Tube::pair().context("failed to create tube")?;
Zach Reiznera90649a2021-03-31 12:56:08 -07001059 control_tubes.push(TaggedControlTube::Vm(gdb_host_tube));
1060 components.gdb = Some((port, gdb_control_tube));
1061 }
1062
Chirantan Ekbote2ee9dcd2021-05-26 18:21:44 +09001063 for wl_cfg in &cfg.vhost_user_wl {
1064 let wayland_host_tube = UnixSeqpacket::connect(&wl_cfg.vm_tube)
1065 .map(Tube::new)
Daniel Verkamp6b298582021-08-16 15:37:11 -07001066 .context("failed to connect to wayland tube")?;
Chirantan Ekbote2ee9dcd2021-05-26 18:21:44 +09001067 control_tubes.push(TaggedControlTube::VmMemory(wayland_host_tube));
1068 }
1069
Chirantan Ekbote44292f52021-06-25 18:31:41 +09001070 let mut vhost_user_gpu_tubes = Vec::with_capacity(cfg.vhost_user_gpu.len());
1071 for _ in 0..cfg.vhost_user_gpu.len() {
Alexandre Courbote55b7912022-03-04 16:54:38 +09001072 let (host_control_tube, device_control_tube) =
1073 Tube::pair().context("failed to create tube")?;
1074 let (host_gpu_tube, device_gpu_tube) = Tube::pair().context("failed to create tube")?;
1075 vhost_user_gpu_tubes.push((host_gpu_tube, device_gpu_tube, device_control_tube));
1076 control_tubes.push(TaggedControlTube::VmMemory(host_control_tube));
Chirantan Ekbote44292f52021-06-25 18:31:41 +09001077 }
1078
Daniel Verkamp6b298582021-08-16 15:37:11 -07001079 let (wayland_host_tube, wayland_device_tube) = Tube::pair().context("failed to create tube")?;
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001080 control_tubes.push(TaggedControlTube::VmMemory(wayland_host_tube));
Andrew Walbran3cd93602022-01-25 13:59:23 +00001081
1082 let (balloon_host_tube, balloon_device_tube) = if cfg.balloon {
David Stevens8be9ef02022-01-13 22:50:24 +09001083 if let Some(ref path) = cfg.balloon_control {
1084 (
1085 None,
1086 Some(Tube::new(
1087 UnixSeqpacket::connect(path).context("failed to create balloon control")?,
1088 )),
1089 )
1090 } else {
1091 // Balloon gets a special socket so balloon requests can be forwarded
1092 // from the main process.
1093 let (host, device) = Tube::pair().context("failed to create tube")?;
1094 // Set recv timeout to avoid deadlock on sending BalloonControlCommand
1095 // before the guest is ready.
1096 host.set_recv_timeout(Some(Duration::from_millis(100)))
1097 .context("failed to set timeout")?;
1098 (Some(host), Some(device))
1099 }
Andrew Walbran3cd93602022-01-25 13:59:23 +00001100 } else {
1101 (None, None)
1102 };
Dylan Reid059a1882018-07-23 17:58:09 -07001103
Daniel Verkamp92f73d72018-12-04 13:17:46 -08001104 // Create one control socket per disk.
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001105 let mut disk_device_tubes = Vec::new();
1106 let mut disk_host_tubes = Vec::new();
Daniel Verkamp92f73d72018-12-04 13:17:46 -08001107 let disk_count = cfg.disks.len();
1108 for _ in 0..disk_count {
Daniel Verkamp6b298582021-08-16 15:37:11 -07001109 let (disk_host_tub, disk_device_tube) = Tube::pair().context("failed to create tube")?;
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001110 disk_host_tubes.push(disk_host_tub);
1111 disk_device_tubes.push(disk_device_tube);
Daniel Verkamp92f73d72018-12-04 13:17:46 -08001112 }
1113
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001114 let mut pmem_device_tubes = Vec::new();
Daniel Verkampe1980a92020-02-07 11:00:55 -08001115 let pmem_count = cfg.pmem_devices.len();
1116 for _ in 0..pmem_count {
Daniel Verkamp6b298582021-08-16 15:37:11 -07001117 let (pmem_host_tube, pmem_device_tube) = Tube::pair().context("failed to create tube")?;
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001118 pmem_device_tubes.push(pmem_device_tube);
1119 control_tubes.push(TaggedControlTube::VmMsync(pmem_host_tube));
Daniel Verkampe1980a92020-02-07 11:00:55 -08001120 }
1121
Daniel Verkamp6b298582021-08-16 15:37:11 -07001122 let (gpu_host_tube, gpu_device_tube) = Tube::pair().context("failed to create tube")?;
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001123 control_tubes.push(TaggedControlTube::VmMemory(gpu_host_tube));
Gurchetan Singh96beafc2019-05-15 09:46:52 -07001124
Zach Reiznerdc748482021-04-14 13:59:30 -07001125 if let Some(ioapic_host_tube) = ioapic_host_tube {
1126 control_tubes.push(TaggedControlTube::VmIrq(ioapic_host_tube));
1127 }
Zhuocheng Dingf2e90bf2019-12-02 15:50:20 +08001128
Chuanxiao Dongbbb32af2020-04-27 16:37:10 +08001129 let battery = if cfg.battery_type.is_some() {
Daniel Verkampcfe49462021-08-19 17:11:05 -07001130 #[cfg_attr(not(feature = "power-monitor-powerd"), allow(clippy::manual_map))]
Alexandre Courbot6a8f6562022-03-24 14:43:48 +09001131 let jail = match simple_jail(&cfg.jail_config, "battery")? {
Daniel Verkampcfe49462021-08-19 17:11:05 -07001132 #[cfg_attr(not(feature = "power-monitor-powerd"), allow(unused_mut))]
Alex Lauf408c732020-11-10 18:24:04 +09001133 Some(mut jail) => {
1134 // Setup a bind mount to the system D-Bus socket if the powerd monitor is used.
1135 #[cfg(feature = "power-monitor-powerd")]
1136 {
Fergus Dall51200512021-08-19 12:54:26 +10001137 add_current_user_to_jail(&mut jail)?;
Alex Lauf408c732020-11-10 18:24:04 +09001138
1139 // Create a tmpfs in the device's root directory so that we can bind mount files.
1140 jail.mount_with_data(
1141 Path::new("none"),
1142 Path::new("/"),
1143 "tmpfs",
1144 (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as usize,
1145 "size=67108864",
1146 )?;
1147
1148 let system_bus_socket_path = Path::new("/run/dbus/system_bus_socket");
1149 jail.mount_bind(system_bus_socket_path, system_bus_socket_path, true)?;
1150 }
1151 Some(jail)
1152 }
1153 None => None,
1154 };
1155 (&cfg.battery_type, jail)
Chuanxiao Dongbbb32af2020-04-27 16:37:10 +08001156 } else {
1157 (&cfg.battery_type, None)
1158 };
1159
Lingfeng Yangd6ac1ab2020-01-31 13:55:35 -08001160 let map_request: Arc<Mutex<Option<ExternalMapping>>> = Arc::new(Mutex::new(None));
1161
Keiichi Watanabeeefe7fb2020-11-17 17:58:35 +09001162 let fs_count = cfg
1163 .shared_dirs
1164 .iter()
1165 .filter(|sd| sd.kind == SharedDirKind::FS)
1166 .count();
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001167 let mut fs_device_tubes = Vec::with_capacity(fs_count);
Keiichi Watanabeeefe7fb2020-11-17 17:58:35 +09001168 for _ in 0..fs_count {
Daniel Verkamp6b298582021-08-16 15:37:11 -07001169 let (fs_host_tube, fs_device_tube) = Tube::pair().context("failed to create tube")?;
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001170 control_tubes.push(TaggedControlTube::Fs(fs_host_tube));
1171 fs_device_tubes.push(fs_device_tube);
Keiichi Watanabeeefe7fb2020-11-17 17:58:35 +09001172 }
1173
Abhishek Bhardwaj90fd1642021-11-24 18:26:37 -08001174 let mut vvu_proxy_device_tubes = Vec::new();
1175 for _ in 0..cfg.vvu_proxy.len() {
1176 let (vvu_proxy_host_tube, vvu_proxy_device_tube) =
1177 Tube::pair().context("failed to create VVU proxy tube")?;
1178 control_tubes.push(TaggedControlTube::VmMemory(vvu_proxy_host_tube));
1179 vvu_proxy_device_tubes.push(vvu_proxy_device_tube);
1180 }
1181
Daniel Verkamp6b298582021-08-16 15:37:11 -07001182 let exit_evt = Event::new().context("failed to create event")?;
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08001183 let reset_evt = Event::new().context("failed to create event")?;
Andrew Walbran1a19c672022-01-24 17:24:10 +00001184 let crash_evt = Event::new().context("failed to create event")?;
Vineeth Pillai9a3d2dc2022-02-18 14:10:16 +00001185 let (panic_rdtube, panic_wrtube) = Tube::pair().context("failed to create tube")?;
Ryo Hashimoto8f9dc1d2021-08-18 19:07:29 +09001186
David Stevense4db4172022-03-10 13:26:04 +09001187 let pstore_size = components.pstore.as_ref().map(|pstore| pstore.size as u64);
David Stevensdbd24182022-03-10 10:53:56 +09001188 let mut sys_allocator = SystemAllocator::new(
1189 Arch::get_system_allocator_config(&vm),
1190 pstore_size,
1191 &cfg.mmio_address_ranges,
1192 )
1193 .context("failed to create system allocator")?;
David Stevense4db4172022-03-10 13:26:04 +09001194
Ryo Hashimoto8f9dc1d2021-08-18 19:07:29 +09001195 let ramoops_region = match &components.pstore {
1196 Some(pstore) => Some(
David Stevense4db4172022-03-10 13:26:04 +09001197 arch::pstore::create_memory_region(
1198 &mut vm,
1199 sys_allocator.reserved_region().unwrap(),
1200 pstore,
1201 )
1202 .context("failed to allocate pstore region")?,
Ryo Hashimoto8f9dc1d2021-08-18 19:07:29 +09001203 ),
1204 None => None,
1205 };
1206
Mattias Nisslerbbd91d02021-12-07 08:57:45 +00001207 create_file_backed_mappings(&cfg, &mut vm, &mut sys_allocator)?;
1208
Dmitry Torokhov9cbe5432022-01-25 19:17:07 -08001209 #[cfg(feature = "gpu")]
1210 // Hold on to the render server jail so it keeps running until we exit run_vm()
Dmitry Torokhove464a7a2022-01-26 13:29:36 -08001211 let (_render_server_jail, render_server_fd) =
1212 if let Some(parameters) = &cfg.gpu_render_server_parameters {
1213 let (jail, fd) = start_gpu_render_server(&cfg, parameters)?;
1214 (Some(ScopedMinijail(jail)), Some(fd))
1215 } else {
1216 (None, None)
1217 };
Dmitry Torokhov9cbe5432022-01-25 19:17:07 -08001218
David Stevens06d157a2022-01-13 23:44:48 +09001219 let init_balloon_size = components
1220 .memory_size
1221 .checked_sub(cfg.init_memory.map_or(components.memory_size, |m| {
1222 m.checked_mul(1024 * 1024).unwrap_or(u64::MAX)
1223 }))
1224 .context("failed to calculate init balloon size")?;
1225
Tomasz Nowicki64f43552022-02-22 14:14:45 +00001226 #[cfg(feature = "direct")]
1227 let mut irqs = Vec::new();
1228
1229 #[cfg(feature = "direct")]
1230 for irq in &cfg.direct_level_irq {
1231 if !sys_allocator.reserve_irq(*irq) {
1232 warn!("irq {} already reserved.", irq);
1233 }
Dmitry Torokhov7b7a2062022-03-19 23:01:33 -07001234 let irq_evt = devices::IrqLevelEvent::new().context("failed to create event")?;
Dmitry Torokhovf021a622022-03-21 11:00:29 -07001235 irq_chip.register_level_irq_event(*irq, &irq_evt).unwrap();
Dmitry Torokhov7b7a2062022-03-19 23:01:33 -07001236 let direct_irq = devices::DirectIrq::new_level(&irq_evt)
Tomasz Nowicki64f43552022-02-22 14:14:45 +00001237 .context("failed to enable interrupt forwarding")?;
1238 direct_irq
1239 .irq_enable(*irq)
1240 .context("failed to enable interrupt forwarding")?;
Dmytro Maluka0ac97972022-04-05 15:25:46 +00001241
1242 if cfg.direct_wake_irq.contains(&irq) {
1243 direct_irq
1244 .irq_wake_enable(*irq)
1245 .context("failed to enable interrupt wake")?;
1246 }
1247
Tomasz Nowicki64f43552022-02-22 14:14:45 +00001248 irqs.push(direct_irq);
1249 }
1250
1251 #[cfg(feature = "direct")]
1252 for irq in &cfg.direct_edge_irq {
1253 if !sys_allocator.reserve_irq(*irq) {
1254 warn!("irq {} already reserved.", irq);
1255 }
Dmitry Torokhov7b7a2062022-03-19 23:01:33 -07001256 let irq_evt = devices::IrqEdgeEvent::new().context("failed to create event")?;
Dmitry Torokhovf021a622022-03-21 11:00:29 -07001257 irq_chip.register_edge_irq_event(*irq, &irq_evt).unwrap();
Dmitry Torokhov7b7a2062022-03-19 23:01:33 -07001258 let direct_irq = devices::DirectIrq::new_edge(&irq_evt)
Tomasz Nowicki64f43552022-02-22 14:14:45 +00001259 .context("failed to enable interrupt forwarding")?;
1260 direct_irq
1261 .irq_enable(*irq)
1262 .context("failed to enable interrupt forwarding")?;
Dmytro Maluka0ac97972022-04-05 15:25:46 +00001263
1264 if cfg.direct_wake_irq.contains(&irq) {
1265 direct_irq
1266 .irq_wake_enable(*irq)
1267 .context("failed to enable interrupt wake")?;
1268 }
1269
Tomasz Nowicki64f43552022-02-22 14:14:45 +00001270 irqs.push(direct_irq);
1271 }
1272
Haiwei Li09b7b8e2022-02-18 18:16:05 +08001273 let mut iommu_attached_endpoints: BTreeMap<u32, Arc<Mutex<Box<dyn MemoryMapperTrait>>>> =
1274 BTreeMap::new();
Tomasz Nowickiab86d522021-09-22 05:50:46 +00001275 let mut devices = create_devices(
Zach Reiznerdc748482021-04-14 13:59:30 -07001276 &cfg,
1277 &mut vm,
1278 &mut sys_allocator,
1279 &exit_evt,
Vineeth Pillai9a3d2dc2022-02-18 14:10:16 +00001280 panic_wrtube,
Haiwei Li09b7b8e2022-02-18 18:16:05 +08001281 &mut iommu_attached_endpoints,
Zach Reiznerdc748482021-04-14 13:59:30 -07001282 &mut control_tubes,
1283 wayland_device_tube,
1284 gpu_device_tube,
Chirantan Ekbote44292f52021-06-25 18:31:41 +09001285 vhost_user_gpu_tubes,
Zach Reiznerdc748482021-04-14 13:59:30 -07001286 balloon_device_tube,
David Stevens06d157a2022-01-13 23:44:48 +09001287 init_balloon_size,
Zach Reiznerdc748482021-04-14 13:59:30 -07001288 &mut disk_device_tubes,
1289 &mut pmem_device_tubes,
1290 &mut fs_device_tubes,
Daniel Verkampf1439d42021-05-21 13:55:10 -07001291 #[cfg(feature = "usb")]
Zach Reiznerdc748482021-04-14 13:59:30 -07001292 usb_provider,
1293 Arc::clone(&map_request),
Dmitry Torokhov9cbe5432022-01-25 19:17:07 -08001294 #[cfg(feature = "gpu")]
1295 render_server_fd,
Abhishek Bhardwaj90fd1642021-11-24 18:26:37 -08001296 &mut vvu_proxy_device_tubes,
Zach Reiznerdc748482021-04-14 13:59:30 -07001297 )?;
1298
Haiwei Li09b7b8e2022-02-18 18:16:05 +08001299 let mut hp_endpoints_ranges: Vec<RangeInclusive<u32>> = Vec::new();
Anton Romanov33334412022-03-22 17:48:18 +00001300 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
Xiong Zhangf7874712021-12-24 10:53:59 +08001301 let mut hotplug_buses: Vec<Arc<Mutex<dyn HotPlugBus>>> = Vec::new();
Xiong Zhang1b6e0112022-03-15 11:34:16 +08001302 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1303 let mut gpe_notify_devs: Vec<(u32, Arc<Mutex<dyn GpeNotify>>)> = Vec::new();
Xiong Zhangf7874712021-12-24 10:53:59 +08001304 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1305 {
1306 #[cfg(feature = "direct")]
1307 let rp_host = cfg.pcie_rp.clone();
1308 #[cfg(not(feature = "direct"))]
Xiong Zhang626f0142022-03-12 16:05:17 +08001309 let rp_host: Vec<HostPcieRootPortParameters> = Vec::new();
Xiong Zhangf7874712021-12-24 10:53:59 +08001310
1311 // Create Pcie Root Port
1312 create_pcie_root_port(
1313 rp_host,
1314 &mut sys_allocator,
1315 &mut control_tubes,
1316 &mut devices,
1317 &mut hotplug_buses,
Haiwei Li09b7b8e2022-02-18 18:16:05 +08001318 &mut hp_endpoints_ranges,
Xiong Zhang1b6e0112022-03-15 11:34:16 +08001319 &mut gpe_notify_devs,
Xiong Zhangf7874712021-12-24 10:53:59 +08001320 )?;
1321 }
1322
Haiwei Li09b7b8e2022-02-18 18:16:05 +08001323 let (translate_response_senders, request_rx) = setup_virtio_access_platform(
1324 &mut sys_allocator,
1325 &mut iommu_attached_endpoints,
1326 &mut devices,
1327 )?;
1328
Haiwei Li87bc2fc2022-02-18 14:37:40 +08001329 let iommu_host_tube = if !iommu_attached_endpoints.is_empty() || cfg.virtio_iommu {
Haiwei Lie2dffbf2022-02-18 14:30:56 +08001330 let (iommu_host_tube, iommu_device_tube) = Tube::pair().context("failed to create tube")?;
Haiwei Li09b7b8e2022-02-18 18:16:05 +08001331 let iommu_dev = create_iommu_device(
1332 &cfg,
1333 (1u64 << vm.get_guest_phys_addr_bits()) - 1,
1334 iommu_attached_endpoints,
1335 hp_endpoints_ranges,
1336 translate_response_senders,
1337 request_rx,
1338 iommu_device_tube,
1339 )?;
1340
1341 let (msi_host_tube, msi_device_tube) = Tube::pair().context("failed to create tube")?;
1342 control_tubes.push(TaggedControlTube::VmIrq(msi_host_tube));
1343 let mut dev = VirtioPciDevice::new(vm.get_memory().clone(), iommu_dev.dev, msi_device_tube)
1344 .context("failed to create virtio pci dev")?;
1345 // early reservation for viommu.
1346 dev.allocate_address(&mut sys_allocator)
1347 .context("failed to allocate resources early for virtio pci dev")?;
1348 let dev = Box::new(dev);
1349 devices.push((dev, iommu_dev.jail));
Haiwei Lie2dffbf2022-02-18 14:30:56 +08001350 Some(iommu_host_tube)
1351 } else {
1352 None
1353 };
Haiwei Li09b7b8e2022-02-18 18:16:05 +08001354
Peter Fangc2bba082021-04-19 18:40:24 -07001355 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
Tomasz Nowickiab86d522021-09-22 05:50:46 +00001356 for device in devices
1357 .iter_mut()
1358 .filter_map(|(dev, _)| dev.as_pci_device_mut())
1359 {
Peter Fangc2bba082021-04-19 18:40:24 -07001360 let sdts = device
1361 .generate_acpi(components.acpi_sdts)
1362 .or_else(|| {
1363 error!("ACPI table generation error");
1364 None
1365 })
Daniel Verkamp6b298582021-08-16 15:37:11 -07001366 .ok_or_else(|| anyhow!("failed to generate ACPI table"))?;
Peter Fangc2bba082021-04-19 18:40:24 -07001367 components.acpi_sdts = sdts;
1368 }
1369
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +08001370 // KVM_CREATE_VCPU uses apic id for x86 and uses cpu id for others.
1371 let mut kvm_vcpu_ids = Vec::new();
1372
Kuo-Hsin Yang6139da62021-04-14 16:55:24 +08001373 #[cfg_attr(not(feature = "direct"), allow(unused_mut))]
Zach Reiznerdc748482021-04-14 13:59:30 -07001374 let mut linux = Arch::build_vm::<V, Vcpu>(
Trent Begin17ccaad2019-04-17 13:51:25 -06001375 components,
Zach Reiznerdc748482021-04-14 13:59:30 -07001376 &exit_evt,
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08001377 &reset_evt,
Zach Reiznerdc748482021-04-14 13:59:30 -07001378 &mut sys_allocator,
Trent Begin17ccaad2019-04-17 13:51:25 -06001379 &cfg.serial_parameters,
Alexandre Courbot6a8f6562022-03-24 14:43:48 +09001380 simple_jail(&cfg.jail_config, "serial")?,
Chuanxiao Dongbbb32af2020-04-27 16:37:10 +08001381 battery,
Zach Reiznera90649a2021-03-31 12:56:08 -07001382 vm,
Ryo Hashimoto8f9dc1d2021-08-18 19:07:29 +09001383 ramoops_region,
Tomasz Nowickiab86d522021-09-22 05:50:46 +00001384 devices,
Zach Reiznerdc748482021-04-14 13:59:30 -07001385 irq_chip,
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +08001386 &mut kvm_vcpu_ids,
Trent Begin17ccaad2019-04-17 13:51:25 -06001387 )
Daniel Verkamp6b298582021-08-16 15:37:11 -07001388 .context("the architecture failed to build the vm")?;
Lepton Wu60893882018-11-21 11:06:18 -08001389
Daniel Verkamp1286b482021-11-30 15:14:16 -08001390 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1391 {
Xiong Zhangf7874712021-12-24 10:53:59 +08001392 for hotplug_bus in hotplug_buses.iter() {
1393 linux.hotplug_bus.push(hotplug_bus.clone());
1394 }
Xiong Zhang1b6e0112022-03-15 11:34:16 +08001395
1396 if let Some(pm) = &linux.pm {
1397 while let Some((gpe, notify_dev)) = gpe_notify_devs.pop() {
1398 pm.lock().register_gpe_notify_dev(gpe, notify_dev);
1399 }
1400 }
Daniel Verkamp1286b482021-11-30 15:14:16 -08001401 }
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08001402
Tomasz Jeznach3ce74762021-02-26 01:01:53 -08001403 #[cfg(feature = "direct")]
1404 if let Some(pmio) = &cfg.direct_pmio {
Daniel Verkamp6b298582021-08-16 15:37:11 -07001405 let direct_io = Arc::new(
1406 devices::DirectIo::new(&pmio.path, false).context("failed to open direct io device")?,
1407 );
Tomasz Jeznach3ce74762021-02-26 01:01:53 -08001408 for range in pmio.ranges.iter() {
1409 linux
1410 .io_bus
Junichi Uekawab180f9c2021-12-07 09:21:36 +09001411 .insert_sync(direct_io.clone(), range.base, range.len)
Tomasz Jeznach3ce74762021-02-26 01:01:53 -08001412 .unwrap();
1413 }
1414 };
1415
Tomasz Jeznach7271f752021-03-04 01:44:06 -08001416 #[cfg(feature = "direct")]
Tomasz Jeznach9e6c6332021-05-27 21:49:14 -07001417 if let Some(mmio) = &cfg.direct_mmio {
Xiong Zhang46471a02021-11-12 00:34:42 +08001418 let direct_mmio = Arc::new(
Junichi Uekawab180f9c2021-12-07 09:21:36 +09001419 devices::DirectMmio::new(&mmio.path, false, &mmio.ranges)
Xiong Zhang46471a02021-11-12 00:34:42 +08001420 .context("failed to open direct mmio device")?,
Daniel Verkamp6b298582021-08-16 15:37:11 -07001421 );
Xiong Zhang46471a02021-11-12 00:34:42 +08001422
Tomasz Jeznach9e6c6332021-05-27 21:49:14 -07001423 for range in mmio.ranges.iter() {
1424 linux
1425 .mmio_bus
Junichi Uekawab180f9c2021-12-07 09:21:36 +09001426 .insert_sync(direct_mmio.clone(), range.base, range.len)
Tomasz Jeznach9e6c6332021-05-27 21:49:14 -07001427 .unwrap();
1428 }
1429 };
1430
Daniel Verkamp6b298582021-08-16 15:37:11 -07001431 let gralloc = RutabagaGralloc::new().context("failed to create gralloc")?;
Daniel Verkamp92f73d72018-12-04 13:17:46 -08001432 run_control(
1433 linux,
Zach Reiznerdc748482021-04-14 13:59:30 -07001434 sys_allocator,
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001435 cfg,
Zach Reiznera60744b2019-02-13 17:33:32 -08001436 control_server_socket,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001437 control_tubes,
1438 balloon_host_tube,
1439 &disk_host_tubes,
Daniel Verkampf1439d42021-05-21 13:55:10 -07001440 #[cfg(feature = "usb")]
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001441 usb_control_tube,
Zach Reiznerdc748482021-04-14 13:59:30 -07001442 exit_evt,
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08001443 reset_evt,
Andrew Walbran1a19c672022-01-24 17:24:10 +00001444 crash_evt,
Vineeth Pillai9a3d2dc2022-02-18 14:10:16 +00001445 panic_rdtube,
Daniel Verkamp92f73d72018-12-04 13:17:46 -08001446 sigchld_fd,
Lingfeng Yangd6ac1ab2020-01-31 13:55:35 -08001447 Arc::clone(&map_request),
Gurchetan Singh293913c2020-12-09 10:44:13 -08001448 gralloc,
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +08001449 kvm_vcpu_ids,
Haiwei Lie2dffbf2022-02-18 14:30:56 +08001450 iommu_host_tube,
Daniel Verkamp92f73d72018-12-04 13:17:46 -08001451 )
Dylan Reid0ed91ab2018-05-31 15:42:18 -07001452}
1453
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08001454fn get_hp_bus<V: VmArch, Vcpu: VcpuArch>(
1455 linux: &RunnableLinuxVm<V, Vcpu>,
1456 host_addr: PciAddress,
1457) -> Result<(Arc<Mutex<dyn HotPlugBus>>, u8)> {
1458 for hp_bus in linux.hotplug_bus.iter() {
1459 if let Some(number) = hp_bus.lock().is_match(host_addr) {
1460 return Ok((hp_bus.clone(), number));
1461 }
1462 }
1463 Err(anyhow!("Failed to find a suitable hotplug bus"))
1464}
1465
Xiong Zhang8c9fe3e2021-04-12 15:07:17 +08001466fn add_vfio_device<V: VmArch, Vcpu: VcpuArch>(
1467 linux: &mut RunnableLinuxVm<V, Vcpu>,
1468 sys_allocator: &mut SystemAllocator,
1469 cfg: &Config,
1470 control_tubes: &mut Vec<TaggedControlTube>,
Haiwei Lie2dffbf2022-02-18 14:30:56 +08001471 iommu_host_tube: &Option<Tube>,
Xiong Zhang8c9fe3e2021-04-12 15:07:17 +08001472 vfio_path: &Path,
1473) -> Result<()> {
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08001474 let host_os_str = vfio_path
1475 .file_name()
1476 .ok_or_else(|| anyhow!("failed to parse or find vfio path"))?;
1477 let host_str = host_os_str
1478 .to_str()
1479 .ok_or_else(|| anyhow!("failed to parse or find vfio path"))?;
Daniel Verkamp906a38f2022-02-22 13:58:53 -08001480 let host_addr =
1481 PciAddress::from_string(host_str).context("failed to parse vfio pci address")?;
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08001482
1483 let (hp_bus, bus_num) = get_hp_bus(linux, host_addr)?;
1484
Woody Chow055b81b2022-01-25 18:34:29 +09001485 let mut endpoints: BTreeMap<u32, Arc<Mutex<Box<dyn MemoryMapperTrait>>>> = BTreeMap::new();
Xiong Zhang8c9fe3e2021-04-12 15:07:17 +08001486 let (vfio_pci_device, jail) = create_vfio_device(
1487 cfg,
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08001488 &linux.vm,
Xiong Zhang8c9fe3e2021-04-12 15:07:17 +08001489 sys_allocator,
1490 control_tubes,
1491 vfio_path,
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08001492 Some(bus_num),
Victor Ding3f749592022-03-18 05:44:20 +00001493 None,
Xiong Zhang8c9fe3e2021-04-12 15:07:17 +08001494 &mut endpoints,
Chuanxiao Donga8d427b2022-01-07 10:26:24 +08001495 None,
Haiwei Lie2dffbf2022-02-18 14:30:56 +08001496 if iommu_host_tube.is_some() {
1497 IommuDevType::VirtioIommu
1498 } else {
1499 IommuDevType::NoIommu
1500 },
Xiong Zhang8c9fe3e2021-04-12 15:07:17 +08001501 )?;
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08001502
1503 let pci_address = Arch::register_pci_device(linux, vfio_pci_device, jail, sys_allocator)
Daniel Verkamp6b298582021-08-16 15:37:11 -07001504 .context("Failed to configure pci hotplug device")?;
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08001505
Haiwei Lie2dffbf2022-02-18 14:30:56 +08001506 if let Some(iommu_host_tube) = iommu_host_tube {
1507 let &endpoint_addr = endpoints.iter().next().unwrap().0;
1508 let mapper = endpoints.remove(&endpoint_addr).unwrap();
1509 if let Some(vfio_wrapper) = mapper.lock().as_vfio_wrapper() {
1510 let vfio_container = vfio_wrapper.as_vfio_container();
1511 let descriptor = vfio_container.lock().into_raw_descriptor()?;
1512 let request = VirtioIOMMURequest::VfioCommand(VirtioIOMMUVfioCommand::VfioDeviceAdd {
1513 endpoint_addr,
1514 container: {
1515 // Safe because the descriptor is uniquely owned by `descriptor`.
1516 unsafe { File::from_raw_descriptor(descriptor) }
1517 },
1518 });
1519
1520 match virtio_iommu_request(iommu_host_tube, &request)
1521 .map_err(|_| VirtioIOMMUVfioError::SocketFailed)?
1522 {
1523 VirtioIOMMUResponse::VfioResponse(VirtioIOMMUVfioResult::Ok) => (),
1524 resp => bail!("Unexpected message response: {:?}", resp),
1525 }
1526 };
1527 }
1528
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08001529 let host_key = HostHotPlugKey::Vfio { host_addr };
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08001530 let mut hp_bus = hp_bus.lock();
1531 hp_bus.add_hotplug_device(host_key, pci_address);
1532 hp_bus.hot_plug(pci_address);
1533 Ok(())
Xiong Zhang8c9fe3e2021-04-12 15:07:17 +08001534}
1535
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08001536fn remove_vfio_device<V: VmArch, Vcpu: VcpuArch>(
1537 linux: &RunnableLinuxVm<V, Vcpu>,
Xiong Zhang2d45b912021-05-13 16:22:25 +08001538 sys_allocator: &mut SystemAllocator,
Haiwei Lie2dffbf2022-02-18 14:30:56 +08001539 iommu_host_tube: &Option<Tube>,
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08001540 vfio_path: &Path,
1541) -> Result<()> {
Daniel Verkamp6b298582021-08-16 15:37:11 -07001542 let host_os_str = vfio_path
1543 .file_name()
1544 .ok_or_else(|| anyhow!("failed to parse or find vfio path"))?;
1545 let host_str = host_os_str
1546 .to_str()
1547 .ok_or_else(|| anyhow!("failed to parse or find vfio path"))?;
Daniel Verkamp906a38f2022-02-22 13:58:53 -08001548 let host_addr =
1549 PciAddress::from_string(host_str).context("failed to parse vfio pci address")?;
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08001550 let host_key = HostHotPlugKey::Vfio { host_addr };
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08001551 for hp_bus in linux.hotplug_bus.iter() {
1552 let mut hp_bus_lock = hp_bus.lock();
1553 if let Some(pci_addr) = hp_bus_lock.get_hotplug_device(host_key) {
Haiwei Lie2dffbf2022-02-18 14:30:56 +08001554 if let Some(iommu_host_tube) = iommu_host_tube {
1555 let request =
1556 VirtioIOMMURequest::VfioCommand(VirtioIOMMUVfioCommand::VfioDeviceDel {
1557 endpoint_addr: pci_addr.to_u32(),
1558 });
1559 match virtio_iommu_request(iommu_host_tube, &request)
1560 .map_err(|_| VirtioIOMMUVfioError::SocketFailed)?
1561 {
1562 VirtioIOMMUResponse::VfioResponse(VirtioIOMMUVfioResult::Ok) => (),
1563 resp => bail!("Unexpected message response: {:?}", resp),
1564 }
1565 }
1566
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08001567 hp_bus_lock.hot_unplug(pci_addr);
Xiong Zhang2d45b912021-05-13 16:22:25 +08001568 sys_allocator.release_pci(pci_addr.bus, pci_addr.dev, pci_addr.func);
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08001569 return Ok(());
1570 }
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08001571 }
1572
Daniel Verkamp6b298582021-08-16 15:37:11 -07001573 Err(anyhow!("HotPlugBus hasn't been implemented"))
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08001574}
Xiong Zhang8c9fe3e2021-04-12 15:07:17 +08001575
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001576fn handle_vfio_command<V: VmArch, Vcpu: VcpuArch>(
1577 linux: &mut RunnableLinuxVm<V, Vcpu>,
1578 sys_allocator: &mut SystemAllocator,
1579 cfg: &Config,
1580 add_tubes: &mut Vec<TaggedControlTube>,
Haiwei Lie2dffbf2022-02-18 14:30:56 +08001581 iommu_host_tube: &Option<Tube>,
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001582 vfio_path: &Path,
1583 add: bool,
1584) -> VmResponse {
1585 let ret = if add {
Haiwei Lie2dffbf2022-02-18 14:30:56 +08001586 add_vfio_device(
1587 linux,
1588 sys_allocator,
1589 cfg,
1590 add_tubes,
1591 iommu_host_tube,
1592 vfio_path,
1593 )
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001594 } else {
Haiwei Lie2dffbf2022-02-18 14:30:56 +08001595 remove_vfio_device(linux, sys_allocator, iommu_host_tube, vfio_path)
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001596 };
1597
1598 match ret {
1599 Ok(()) => VmResponse::Ok,
1600 Err(e) => {
1601 error!("hanlde_vfio_command failure: {}", e);
1602 add_tubes.clear();
1603 VmResponse::Err(base::Error::new(libc::EINVAL))
1604 }
1605 }
1606}
1607
Zach Reiznerdc748482021-04-14 13:59:30 -07001608fn run_control<V: VmArch + 'static, Vcpu: VcpuArch + 'static>(
1609 mut linux: RunnableLinuxVm<V, Vcpu>,
1610 mut sys_allocator: SystemAllocator,
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001611 cfg: Config,
Zach Reiznera60744b2019-02-13 17:33:32 -08001612 control_server_socket: Option<UnlinkUnixSeqpacketListener>,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001613 mut control_tubes: Vec<TaggedControlTube>,
Andrew Walbran3cd93602022-01-25 13:59:23 +00001614 balloon_host_tube: Option<Tube>,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001615 disk_host_tubes: &[Tube],
Daniel Verkampf1439d42021-05-21 13:55:10 -07001616 #[cfg(feature = "usb")] usb_control_tube: Tube,
Zach Reiznerdc748482021-04-14 13:59:30 -07001617 exit_evt: Event,
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08001618 reset_evt: Event,
Andrew Walbran1a19c672022-01-24 17:24:10 +00001619 crash_evt: Event,
Vineeth Pillai9a3d2dc2022-02-18 14:10:16 +00001620 panic_rdtube: Tube,
Zach Reizner55a9e502018-10-03 10:22:32 -07001621 sigchld_fd: SignalFd,
Lingfeng Yangd6ac1ab2020-01-31 13:55:35 -08001622 map_request: Arc<Mutex<Option<ExternalMapping>>>,
Gurchetan Singh293913c2020-12-09 10:44:13 -08001623 mut gralloc: RutabagaGralloc,
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +08001624 kvm_vcpu_ids: Vec<usize>,
Haiwei Lie2dffbf2022-02-18 14:30:56 +08001625 iommu_host_tube: Option<Tube>,
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08001626) -> Result<ExitState> {
Zach Reizner5bed0d22018-03-28 02:31:11 -07001627 #[derive(PollToken)]
1628 enum Token {
1629 Exit,
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08001630 Reset,
Andrew Walbran1a19c672022-01-24 17:24:10 +00001631 Crash,
Vineeth Pillai9a3d2dc2022-02-18 14:10:16 +00001632 Panic,
Chuanxiao Dong546f01c2020-02-12 21:58:47 +08001633 Suspend,
Zach Reizner5bed0d22018-03-28 02:31:11 -07001634 ChildSignal,
Colin Downs-Razoukbd532762020-09-08 15:49:35 -07001635 IrqFd { index: IrqEventIndex },
Zach Reiznera60744b2019-02-13 17:33:32 -08001636 VmControlServer,
Zach Reizner5bed0d22018-03-28 02:31:11 -07001637 VmControl { index: usize },
Tomasz Nowicki98801002022-02-23 21:00:00 +00001638 DelayedIrqFd,
Zach Reizner5bed0d22018-03-28 02:31:11 -07001639 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08001640
Zach Reizner19ad1f32019-12-12 18:58:50 -08001641 stdin()
Zach Reizner39aa26b2017-12-12 18:03:23 -08001642 .set_raw_mode()
1643 .expect("failed to set terminal raw mode");
1644
Michael Hoylee392c462020-10-07 03:29:24 -07001645 let wait_ctx = WaitContext::build_with(&[
Zach Reiznerdc748482021-04-14 13:59:30 -07001646 (&exit_evt, Token::Exit),
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08001647 (&reset_evt, Token::Reset),
Andrew Walbran1a19c672022-01-24 17:24:10 +00001648 (&crash_evt, Token::Crash),
Vineeth Pillai9a3d2dc2022-02-18 14:10:16 +00001649 (&panic_rdtube, Token::Panic),
Chuanxiao Dong546f01c2020-02-12 21:58:47 +08001650 (&linux.suspend_evt, Token::Suspend),
Zach Reiznerb2110be2019-07-23 15:55:03 -07001651 (&sigchld_fd, Token::ChildSignal),
1652 ])
Daniel Verkamp6b298582021-08-16 15:37:11 -07001653 .context("failed to add descriptor to wait context")?;
Zach Reiznerb2110be2019-07-23 15:55:03 -07001654
Zach Reiznera60744b2019-02-13 17:33:32 -08001655 if let Some(socket_server) = &control_server_socket {
Michael Hoylee392c462020-10-07 03:29:24 -07001656 wait_ctx
Zach Reiznera60744b2019-02-13 17:33:32 -08001657 .add(socket_server, Token::VmControlServer)
Daniel Verkamp6b298582021-08-16 15:37:11 -07001658 .context("failed to add descriptor to wait context")?;
Zach Reiznera60744b2019-02-13 17:33:32 -08001659 }
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001660 for (index, socket) in control_tubes.iter().enumerate() {
Michael Hoylee392c462020-10-07 03:29:24 -07001661 wait_ctx
Zach Reizner55a9e502018-10-03 10:22:32 -07001662 .add(socket.as_ref(), Token::VmControl { index })
Daniel Verkamp6b298582021-08-16 15:37:11 -07001663 .context("failed to add descriptor to wait context")?;
Zach Reizner39aa26b2017-12-12 18:03:23 -08001664 }
1665
Steven Richmanf32d0b42020-06-20 21:45:32 -07001666 let events = linux
1667 .irq_chip
1668 .irq_event_tokens()
Daniel Verkamp6b298582021-08-16 15:37:11 -07001669 .context("failed to add descriptor to wait context")?;
Steven Richmanf32d0b42020-06-20 21:45:32 -07001670
Colin Downs-Razoukbd532762020-09-08 15:49:35 -07001671 for (index, _gsi, evt) in events {
Michael Hoylee392c462020-10-07 03:29:24 -07001672 wait_ctx
Colin Downs-Razoukbd532762020-09-08 15:49:35 -07001673 .add(&evt, Token::IrqFd { index })
Daniel Verkamp6b298582021-08-16 15:37:11 -07001674 .context("failed to add descriptor to wait context")?;
Zhuocheng Dingb9f4c9b2019-12-02 15:50:28 +08001675 }
1676
Tomasz Nowicki98801002022-02-23 21:00:00 +00001677 if let Some(delayed_ioapic_irq_trigger) = linux.irq_chip.irq_delayed_event_token()? {
1678 wait_ctx
1679 .add(&delayed_ioapic_irq_trigger, Token::DelayedIrqFd)
1680 .context("failed to add descriptor to wait context")?;
1681 }
1682
Alexandre Courbot6a8f6562022-03-24 14:43:48 +09001683 if cfg.jail_config.is_some() {
Lepton Wu20333e42019-03-14 10:48:03 -07001684 // Before starting VCPUs, in case we started with some capabilities, drop them all.
Daniel Verkamp6b298582021-08-16 15:37:11 -07001685 drop_capabilities().context("failed to drop process capabilities")?;
Lepton Wu20333e42019-03-14 10:48:03 -07001686 }
Dmitry Torokhov71006072019-03-06 10:56:51 -08001687
Keiichi Watanabec5262e92020-10-21 15:57:33 +09001688 #[cfg(all(target_arch = "x86_64", feature = "gdb"))]
1689 // Create a channel for GDB thread.
1690 let (to_gdb_channel, from_vcpu_channel) = if linux.gdb.is_some() {
1691 let (s, r) = mpsc::channel();
1692 (Some(s), Some(r))
1693 } else {
1694 (None, None)
1695 };
1696
Steven Richmanf32d0b42020-06-20 21:45:32 -07001697 let mut vcpu_handles = Vec::with_capacity(linux.vcpu_count);
1698 let vcpu_thread_barrier = Arc::new(Barrier::new(linux.vcpu_count + 1));
Steven Richmanf32d0b42020-06-20 21:45:32 -07001699 let use_hypervisor_signals = !linux
1700 .vm
1701 .get_hypervisor()
Andrew Walbran985491a2022-01-27 13:47:40 +00001702 .check_capability(HypervisorCap::ImmediateExit);
Anton Romanov5acc0f52022-01-28 00:18:11 +00001703 vcpu::setup_vcpu_signal_handler::<Vcpu>(use_hypervisor_signals)?;
Steven Richmanf32d0b42020-06-20 21:45:32 -07001704
Zach Reizner304e7312020-09-29 16:00:24 -07001705 let vcpus: Vec<Option<_>> = match linux.vcpus.take() {
Andrew Walbran9cfdbd92021-01-11 17:40:34 +00001706 Some(vec) => vec.into_iter().map(Some).collect(),
Steven Richmanf32d0b42020-06-20 21:45:32 -07001707 None => iter::repeat_with(|| None).take(linux.vcpu_count).collect(),
1708 };
Yusuke Sato31e136a2021-08-18 11:51:38 -07001709 // Enable core scheduling before creating vCPUs so that the cookie will be
1710 // shared by all vCPU threads.
1711 // TODO(b/199312402): Avoid enabling core scheduling for the crosvm process
1712 // itself for even better performance. Only vCPUs need the feature.
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001713 if cfg.per_vm_core_scheduling {
Yusuke Sato31e136a2021-08-18 11:51:38 -07001714 if let Err(e) = enable_core_scheduling() {
1715 error!("Failed to enable core scheduling: {}", e);
1716 }
1717 }
Vineeth Pillai2b6855e2022-01-12 16:57:22 +00001718 let vcpu_cgroup_tasks_file = match &cfg.vcpu_cgroup_path {
1719 None => None,
1720 Some(cgroup_path) => {
1721 // Move main process to cgroup_path
1722 let mut f = File::create(&cgroup_path.join("tasks"))?;
1723 f.write_all(process::id().to_string().as_bytes())?;
1724 Some(f)
1725 }
1726 };
Daniel Verkamp94c35272019-09-12 13:31:30 -07001727 for (cpu_id, vcpu) in vcpus.into_iter().enumerate() {
Dylan Reidb0492662019-05-17 14:50:13 -07001728 let (to_vcpu_channel, from_main_channel) = mpsc::channel();
Daniel Verkampc677fb42020-09-08 13:47:49 -07001729 let vcpu_affinity = match linux.vcpu_affinity.clone() {
1730 Some(VcpuAffinity::Global(v)) => v,
1731 Some(VcpuAffinity::PerVcpu(mut m)) => m.remove(&cpu_id).unwrap_or_default(),
1732 None => Default::default(),
1733 };
Anton Romanov5acc0f52022-01-28 00:18:11 +00001734 let handle = vcpu::run_vcpu(
Steven Richmanf32d0b42020-06-20 21:45:32 -07001735 cpu_id,
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +08001736 kvm_vcpu_ids[cpu_id],
Zach Reizner55a9e502018-10-03 10:22:32 -07001737 vcpu,
Daniel Verkamp6b298582021-08-16 15:37:11 -07001738 linux.vm.try_clone().context("failed to clone vm")?,
1739 linux
1740 .irq_chip
1741 .try_box_clone()
1742 .context("failed to clone irqchip")?,
Steven Richmanf32d0b42020-06-20 21:45:32 -07001743 linux.vcpu_count,
Kansho Nishidaab205af2020-08-13 18:17:50 +09001744 linux.rt_cpus.contains(&cpu_id),
Daniel Verkampc677fb42020-09-08 13:47:49 -07001745 vcpu_affinity,
Suleiman Souhlal63630e82021-02-18 11:53:11 +09001746 linux.delay_rt,
Suleiman Souhlal015c3c12020-10-07 14:15:41 +09001747 linux.no_smt,
Zach Reizner55a9e502018-10-03 10:22:32 -07001748 vcpu_thread_barrier.clone(),
Steven Richmanf32d0b42020-06-20 21:45:32 -07001749 linux.has_bios,
Colin Downs-Razouk11bed5e2021-11-02 09:33:14 -07001750 (*linux.io_bus).clone(),
1751 (*linux.mmio_bus).clone(),
Daniel Verkamp6b298582021-08-16 15:37:11 -07001752 exit_evt.try_clone().context("failed to clone event")?,
Andrew Walbranb28ae8e2022-01-17 14:33:10 +00001753 reset_evt.try_clone().context("failed to clone event")?,
Andrew Walbran1a19c672022-01-24 17:24:10 +00001754 crash_evt.try_clone().context("failed to clone event")?,
Steven Richmanf32d0b42020-06-20 21:45:32 -07001755 linux.vm.check_capability(VmCap::PvClockSuspend),
Dylan Reidb0492662019-05-17 14:50:13 -07001756 from_main_channel,
Steven Richmanf32d0b42020-06-20 21:45:32 -07001757 use_hypervisor_signals,
Keiichi Watanabec5262e92020-10-21 15:57:33 +09001758 #[cfg(all(target_arch = "x86_64", feature = "gdb"))]
1759 to_gdb_channel.clone(),
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001760 cfg.per_vm_core_scheduling,
1761 cfg.host_cpu_topology,
Zide Chen344e2432022-01-28 14:58:53 -08001762 cfg.privileged_vm,
Vineeth Pillai2b6855e2022-01-12 16:57:22 +00001763 match vcpu_cgroup_tasks_file {
1764 None => None,
1765 Some(ref f) => Some(
1766 f.try_clone()
1767 .context("failed to clone vcpu cgroup tasks file")?,
1768 ),
1769 },
Junichi Uekawab3a094e2022-03-29 15:41:47 +09001770 cfg.userspace_msr.clone(),
Zach Reizner55a9e502018-10-03 10:22:32 -07001771 )?;
Dylan Reidb0492662019-05-17 14:50:13 -07001772 vcpu_handles.push((handle, to_vcpu_channel));
Dylan Reid059a1882018-07-23 17:58:09 -07001773 }
Steven Richmanf32d0b42020-06-20 21:45:32 -07001774
Keiichi Watanabec5262e92020-10-21 15:57:33 +09001775 #[cfg(all(target_arch = "x86_64", feature = "gdb"))]
1776 // Spawn GDB thread.
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001777 if let Some((gdb_port_num, gdb_control_tube)) = linux.gdb.take() {
Keiichi Watanabec5262e92020-10-21 15:57:33 +09001778 let to_vcpu_channels = vcpu_handles
1779 .iter()
1780 .map(|(_handle, channel)| channel.clone())
1781 .collect();
1782 let target = GdbStub::new(
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001783 gdb_control_tube,
Keiichi Watanabec5262e92020-10-21 15:57:33 +09001784 to_vcpu_channels,
1785 from_vcpu_channel.unwrap(), // Must succeed to unwrap()
1786 );
1787 thread::Builder::new()
1788 .name("gdb".to_owned())
1789 .spawn(move || gdb_thread(target, gdb_port_num))
Daniel Verkamp6b298582021-08-16 15:37:11 -07001790 .context("failed to spawn GDB thread")?;
Keiichi Watanabec5262e92020-10-21 15:57:33 +09001791 };
1792
Dylan Reid059a1882018-07-23 17:58:09 -07001793 vcpu_thread_barrier.wait();
1794
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08001795 let mut exit_state = ExitState::Stop;
Charles William Dick54045012021-07-27 19:11:53 +09001796 let mut balloon_stats_id: u64 = 0;
1797
Michael Hoylee392c462020-10-07 03:29:24 -07001798 'wait: loop {
Zach Reizner5bed0d22018-03-28 02:31:11 -07001799 let events = {
Michael Hoylee392c462020-10-07 03:29:24 -07001800 match wait_ctx.wait() {
Zach Reizner39aa26b2017-12-12 18:03:23 -08001801 Ok(v) => v,
1802 Err(e) => {
David Tolnayb4bd00f2019-02-12 17:51:26 -08001803 error!("failed to poll: {}", e);
Zach Reizner39aa26b2017-12-12 18:03:23 -08001804 break;
1805 }
1806 }
1807 };
Zach Reiznera60744b2019-02-13 17:33:32 -08001808
1809 let mut vm_control_indices_to_remove = Vec::new();
Michael Hoylee392c462020-10-07 03:29:24 -07001810 for event in events.iter().filter(|e| e.is_readable) {
1811 match event.token {
Zach Reizner5bed0d22018-03-28 02:31:11 -07001812 Token::Exit => {
Zach Reizner39aa26b2017-12-12 18:03:23 -08001813 info!("vcpu requested shutdown");
Michael Hoylee392c462020-10-07 03:29:24 -07001814 break 'wait;
Zach Reizner39aa26b2017-12-12 18:03:23 -08001815 }
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08001816 Token::Reset => {
1817 info!("vcpu requested reset");
1818 exit_state = ExitState::Reset;
1819 break 'wait;
1820 }
Andrew Walbran1a19c672022-01-24 17:24:10 +00001821 Token::Crash => {
1822 info!("vcpu crashed");
1823 exit_state = ExitState::Crash;
1824 break 'wait;
1825 }
Vineeth Pillai9a3d2dc2022-02-18 14:10:16 +00001826 Token::Panic => {
1827 let mut break_to_wait: bool = true;
1828 match panic_rdtube.recv::<u8>() {
1829 Ok(panic_code) => {
1830 let panic_code = PvPanicCode::from_u8(panic_code);
1831 info!("Guest reported panic [Code: {}]", panic_code);
1832 if panic_code == PvPanicCode::CrashLoaded {
1833 // VM is booting to crash kernel.
1834 break_to_wait = false;
1835 }
1836 }
1837 Err(e) => {
1838 warn!("failed to recv panic event: {} ", e);
1839 }
1840 }
1841 if break_to_wait {
1842 exit_state = ExitState::GuestPanic;
1843 break 'wait;
1844 }
1845 }
Chuanxiao Dong546f01c2020-02-12 21:58:47 +08001846 Token::Suspend => {
1847 info!("VM requested suspend");
1848 linux.suspend_evt.read().unwrap();
Anton Romanov5acc0f52022-01-28 00:18:11 +00001849 vcpu::kick_all_vcpus(
Zach Reiznerdc748482021-04-14 13:59:30 -07001850 &vcpu_handles,
1851 linux.irq_chip.as_irq_chip(),
Daniel Verkamp29409802021-02-24 14:46:19 -08001852 VcpuControl::RunState(VmRunMode::Suspending),
Zach Reiznerdc748482021-04-14 13:59:30 -07001853 );
Chuanxiao Dong546f01c2020-02-12 21:58:47 +08001854 }
Zach Reizner5bed0d22018-03-28 02:31:11 -07001855 Token::ChildSignal => {
Zach Reizner39aa26b2017-12-12 18:03:23 -08001856 // Print all available siginfo structs, then exit the loop.
Daniel Verkamp6b298582021-08-16 15:37:11 -07001857 while let Some(siginfo) =
1858 sigchld_fd.read().context("failed to create signalfd")?
1859 {
Zach Reizner3ba00982019-01-23 19:04:43 -08001860 let pid = siginfo.ssi_pid;
1861 let pid_label = match linux.pid_debug_label_map.get(&pid) {
1862 Some(label) => format!("{} (pid {})", label, pid),
1863 None => format!("pid {}", pid),
1864 };
David Tolnayf5032762018-12-03 10:46:45 -08001865 error!(
1866 "child {} died: signo {}, status {}, code {}",
Zach Reizner3ba00982019-01-23 19:04:43 -08001867 pid_label, siginfo.ssi_signo, siginfo.ssi_status, siginfo.ssi_code
David Tolnayf5032762018-12-03 10:46:45 -08001868 );
Zach Reizner39aa26b2017-12-12 18:03:23 -08001869 }
Michael Hoylee392c462020-10-07 03:29:24 -07001870 break 'wait;
Zach Reizner39aa26b2017-12-12 18:03:23 -08001871 }
Colin Downs-Razoukbd532762020-09-08 15:49:35 -07001872 Token::IrqFd { index } => {
1873 if let Err(e) = linux.irq_chip.service_irq_event(index) {
1874 error!("failed to signal irq {}: {}", index, e);
Zhuocheng Dingb9f4c9b2019-12-02 15:50:28 +08001875 }
1876 }
Tomasz Nowicki98801002022-02-23 21:00:00 +00001877 Token::DelayedIrqFd => {
1878 if let Err(e) = linux.irq_chip.process_delayed_irq_events() {
1879 warn!("can't deliver delayed irqs: {}", e);
1880 }
1881 }
Zach Reiznera60744b2019-02-13 17:33:32 -08001882 Token::VmControlServer => {
1883 if let Some(socket_server) = &control_server_socket {
1884 match socket_server.accept() {
1885 Ok(socket) => {
Michael Hoylee392c462020-10-07 03:29:24 -07001886 wait_ctx
Zach Reiznera60744b2019-02-13 17:33:32 -08001887 .add(
1888 &socket,
1889 Token::VmControl {
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001890 index: control_tubes.len(),
Zach Reiznera60744b2019-02-13 17:33:32 -08001891 },
1892 )
Daniel Verkamp6b298582021-08-16 15:37:11 -07001893 .context("failed to add descriptor to wait context")?;
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001894 control_tubes.push(TaggedControlTube::Vm(Tube::new(socket)));
Zach Reiznera60744b2019-02-13 17:33:32 -08001895 }
1896 Err(e) => error!("failed to accept socket: {}", e),
1897 }
1898 }
1899 }
Zach Reizner5bed0d22018-03-28 02:31:11 -07001900 Token::VmControl { index } => {
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001901 let mut add_tubes = Vec::new();
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001902 if let Some(socket) = control_tubes.get(index) {
Jakub Starond99cd0a2019-04-11 14:09:39 -07001903 match socket {
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001904 TaggedControlTube::Vm(tube) => match tube.recv::<VmRequest>() {
Jakub Starond99cd0a2019-04-11 14:09:39 -07001905 Ok(request) => {
1906 let mut run_mode_opt = None;
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001907 let response = match request {
1908 VmRequest::VfioCommand { vfio_path, add } => {
1909 handle_vfio_command(
1910 &mut linux,
1911 &mut sys_allocator,
1912 &cfg,
1913 &mut add_tubes,
Haiwei Lie2dffbf2022-02-18 14:30:56 +08001914 &iommu_host_tube,
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001915 &vfio_path,
1916 add,
1917 )
1918 }
1919 _ => request.execute(
1920 &mut run_mode_opt,
Andrew Walbran3cd93602022-01-25 13:59:23 +00001921 balloon_host_tube.as_ref(),
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001922 &mut balloon_stats_id,
1923 disk_host_tubes,
Peter Fang6ca03232021-12-20 02:17:21 -08001924 &mut linux.pm,
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001925 #[cfg(feature = "usb")]
1926 Some(&usb_control_tube),
1927 #[cfg(not(feature = "usb"))]
1928 None,
1929 &mut linux.bat_control,
1930 &vcpu_handles,
1931 ),
1932 };
1933
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001934 if let Err(e) = tube.send(&response) {
Jakub Starond99cd0a2019-04-11 14:09:39 -07001935 error!("failed to send VmResponse: {}", e);
1936 }
1937 if let Some(run_mode) = run_mode_opt {
1938 info!("control socket changed run mode to {}", run_mode);
1939 match run_mode {
1940 VmRunMode::Exiting => {
Michael Hoylee392c462020-10-07 03:29:24 -07001941 break 'wait;
Jakub Starond99cd0a2019-04-11 14:09:39 -07001942 }
Keiichi Watanabec5262e92020-10-21 15:57:33 +09001943 other => {
Chuanxiao Dong2bbe85c2020-11-12 17:18:07 +08001944 if other == VmRunMode::Running {
Daniel Verkampda4e8a92021-07-21 13:49:02 -07001945 for dev in &linux.resume_notify_devices {
1946 dev.lock().resume_imminent();
1947 }
Chuanxiao Dong546f01c2020-02-12 21:58:47 +08001948 }
Anton Romanov5acc0f52022-01-28 00:18:11 +00001949 vcpu::kick_all_vcpus(
Steven Richman11dc6712020-09-02 15:39:14 -07001950 &vcpu_handles,
Zach Reiznerdc748482021-04-14 13:59:30 -07001951 linux.irq_chip.as_irq_chip(),
Daniel Verkamp29409802021-02-24 14:46:19 -08001952 VcpuControl::RunState(other),
Steven Richman11dc6712020-09-02 15:39:14 -07001953 );
Zach Reizner6a8fdd92019-01-16 14:38:41 -08001954 }
1955 }
1956 }
Zach Reizner5bed0d22018-03-28 02:31:11 -07001957 }
Jakub Starond99cd0a2019-04-11 14:09:39 -07001958 Err(e) => {
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001959 if let TubeError::Disconnected = e {
Jakub Starond99cd0a2019-04-11 14:09:39 -07001960 vm_control_indices_to_remove.push(index);
1961 } else {
1962 error!("failed to recv VmRequest: {}", e);
1963 }
Zach Reiznera60744b2019-02-13 17:33:32 -08001964 }
Jakub Starond99cd0a2019-04-11 14:09:39 -07001965 },
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001966 TaggedControlTube::VmMemory(tube) => {
1967 match tube.recv::<VmMemoryRequest>() {
1968 Ok(request) => {
1969 let response = request.execute(
1970 &mut linux.vm,
Zach Reiznerdc748482021-04-14 13:59:30 -07001971 &mut sys_allocator,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001972 Arc::clone(&map_request),
1973 &mut gralloc,
1974 );
1975 if let Err(e) = tube.send(&response) {
1976 error!("failed to send VmMemoryControlResponse: {}", e);
1977 }
1978 }
1979 Err(e) => {
1980 if let TubeError::Disconnected = e {
1981 vm_control_indices_to_remove.push(index);
1982 } else {
1983 error!("failed to recv VmMemoryControlRequest: {}", e);
1984 }
Jakub Starond99cd0a2019-04-11 14:09:39 -07001985 }
1986 }
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001987 }
1988 TaggedControlTube::VmIrq(tube) => match tube.recv::<VmIrqRequest>() {
Xiong Zhang2515b752019-09-19 10:29:02 +08001989 Ok(request) => {
Steven Richmanf32d0b42020-06-20 21:45:32 -07001990 let response = {
1991 let irq_chip = &mut linux.irq_chip;
1992 request.execute(
1993 |setup| match setup {
Vikram Auradkar0953c582022-03-21 17:33:54 -07001994 IrqSetup::Event(irq, ev, _, _, _) => {
Dmitry Torokhovf021a622022-03-21 11:00:29 -07001995 let irq_evt = devices::IrqEdgeEvent::from_event(ev.try_clone()?);
Colin Downs-Razoukbd532762020-09-08 15:49:35 -07001996 if let Some(event_index) = irq_chip
Dmitry Torokhovf021a622022-03-21 11:00:29 -07001997 .register_edge_irq_event(irq, &irq_evt)?
Colin Downs-Razoukbd532762020-09-08 15:49:35 -07001998 {
1999 match wait_ctx.add(
2000 ev,
2001 Token::IrqFd {
2002 index: event_index
2003 },
2004 ) {
2005 Err(e) => {
2006 warn!("failed to add IrqFd to poll context: {}", e);
2007 Err(e)
2008 },
2009 Ok(_) => {
2010 Ok(())
2011 }
2012 }
2013 } else {
2014 Ok(())
2015 }
Steven Richmanf32d0b42020-06-20 21:45:32 -07002016 }
2017 IrqSetup::Route(route) => irq_chip.route_irq(route),
Dmitry Torokhovf021a622022-03-21 11:00:29 -07002018 IrqSetup::UnRegister(irq, ev) => {
2019 let irq_evt = devices::IrqEdgeEvent::from_event(ev.try_clone()?);
2020 irq_chip.unregister_edge_irq_event(irq, &irq_evt)
2021 }
Steven Richmanf32d0b42020-06-20 21:45:32 -07002022 },
Zach Reiznerdc748482021-04-14 13:59:30 -07002023 &mut sys_allocator,
Steven Richmanf32d0b42020-06-20 21:45:32 -07002024 )
2025 };
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002026 if let Err(e) = tube.send(&response) {
Xiong Zhang2515b752019-09-19 10:29:02 +08002027 error!("failed to send VmIrqResponse: {}", e);
2028 }
2029 }
2030 Err(e) => {
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002031 if let TubeError::Disconnected = e {
Xiong Zhang2515b752019-09-19 10:29:02 +08002032 vm_control_indices_to_remove.push(index);
2033 } else {
2034 error!("failed to recv VmIrqRequest: {}", e);
2035 }
2036 }
2037 },
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002038 TaggedControlTube::VmMsync(tube) => {
2039 match tube.recv::<VmMsyncRequest>() {
2040 Ok(request) => {
2041 let response = request.execute(&mut linux.vm);
2042 if let Err(e) = tube.send(&response) {
2043 error!("failed to send VmMsyncResponse: {}", e);
2044 }
2045 }
2046 Err(e) => {
2047 if let TubeError::Disconnected = e {
2048 vm_control_indices_to_remove.push(index);
2049 } else {
2050 error!("failed to recv VmMsyncRequest: {}", e);
2051 }
Daniel Verkampe1980a92020-02-07 11:00:55 -08002052 }
2053 }
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002054 }
2055 TaggedControlTube::Fs(tube) => match tube.recv::<FsMappingRequest>() {
Keiichi Watanabeeefe7fb2020-11-17 17:58:35 +09002056 Ok(request) => {
2057 let response =
Zach Reiznerdc748482021-04-14 13:59:30 -07002058 request.execute(&mut linux.vm, &mut sys_allocator);
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002059 if let Err(e) = tube.send(&response) {
Keiichi Watanabeeefe7fb2020-11-17 17:58:35 +09002060 error!("failed to send VmResponse: {}", e);
2061 }
2062 }
2063 Err(e) => {
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002064 if let TubeError::Disconnected = e {
Keiichi Watanabeeefe7fb2020-11-17 17:58:35 +09002065 vm_control_indices_to_remove.push(index);
2066 } else {
2067 error!("failed to recv VmResponse: {}", e);
2068 }
2069 }
2070 },
Zach Reizner39aa26b2017-12-12 18:03:23 -08002071 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08002072 }
Xiong Zhangc78e72b2021-04-08 11:31:41 +08002073 if !add_tubes.is_empty() {
2074 for (idx, socket) in add_tubes.iter().enumerate() {
2075 wait_ctx
2076 .add(
2077 socket.as_ref(),
2078 Token::VmControl {
2079 index: idx + control_tubes.len(),
2080 },
2081 )
2082 .context(
2083 "failed to add hotplug vfio-pci descriptor ot wait context",
2084 )?;
2085 }
2086 control_tubes.append(&mut add_tubes);
2087 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08002088 }
Zach Reizner5bed0d22018-03-28 02:31:11 -07002089 }
2090 }
Zach Reiznera60744b2019-02-13 17:33:32 -08002091
Vikram Auradkarede68c72021-07-01 14:33:54 -07002092 // It's possible more data is readable and buffered while the socket is hungup,
2093 // so don't delete the tube from the poll context until we're sure all the
2094 // data is read.
2095 // Below case covers a condition where we have received a hungup event and the tube is not
2096 // readable.
2097 // In case of readable tube, once all data is read, any attempt to read more data on hungup
2098 // tube should fail. On such failure, we get Disconnected error and index gets added to
2099 // vm_control_indices_to_remove by the time we reach here.
2100 for event in events.iter().filter(|e| e.is_hungup && !e.is_readable) {
2101 if let Token::VmControl { index } = event.token {
2102 vm_control_indices_to_remove.push(index);
Zach Reizner39aa26b2017-12-12 18:03:23 -08002103 }
2104 }
Zach Reiznera60744b2019-02-13 17:33:32 -08002105
2106 // Sort in reverse so the highest indexes are removed first. This removal algorithm
Zide Chen89584072019-11-14 10:33:51 -08002107 // preserves correct indexes as each element is removed.
Daniel Verkamp8c2f0002020-08-31 15:13:35 -07002108 vm_control_indices_to_remove.sort_unstable_by_key(|&k| Reverse(k));
Zach Reiznera60744b2019-02-13 17:33:32 -08002109 vm_control_indices_to_remove.dedup();
2110 for index in vm_control_indices_to_remove {
Michael Hoylee392c462020-10-07 03:29:24 -07002111 // Delete the socket from the `wait_ctx` synchronously. Otherwise, the kernel will do
2112 // this automatically when the FD inserted into the `wait_ctx` is closed after this
Zide Chen89584072019-11-14 10:33:51 -08002113 // if-block, but this removal can be deferred unpredictably. In some instances where the
Michael Hoylee392c462020-10-07 03:29:24 -07002114 // system is under heavy load, we can even get events returned by `wait_ctx` for an FD
Zide Chen89584072019-11-14 10:33:51 -08002115 // that has already been closed. Because the token associated with that spurious event
2116 // now belongs to a different socket, the control loop will start to interact with
2117 // sockets that might not be ready to use. This can cause incorrect hangup detection or
2118 // blocking on a socket that will never be ready. See also: crbug.com/1019986
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002119 if let Some(socket) = control_tubes.get(index) {
Daniel Verkamp6b298582021-08-16 15:37:11 -07002120 wait_ctx
2121 .delete(socket)
2122 .context("failed to remove descriptor from wait context")?;
Zide Chen89584072019-11-14 10:33:51 -08002123 }
2124
2125 // This line implicitly drops the socket at `index` when it gets returned by
2126 // `swap_remove`. After this line, the socket at `index` is not the one from
2127 // `vm_control_indices_to_remove`. Because of this socket's change in index, we need to
Michael Hoylee392c462020-10-07 03:29:24 -07002128 // use `wait_ctx.modify` to change the associated index in its `Token::VmControl`.
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002129 control_tubes.swap_remove(index);
2130 if let Some(tube) = control_tubes.get(index) {
Michael Hoylee392c462020-10-07 03:29:24 -07002131 wait_ctx
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002132 .modify(tube, EventType::Read, Token::VmControl { index })
Daniel Verkamp6b298582021-08-16 15:37:11 -07002133 .context("failed to add descriptor to wait context")?;
Zach Reiznera60744b2019-02-13 17:33:32 -08002134 }
2135 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08002136 }
2137
Anton Romanov5acc0f52022-01-28 00:18:11 +00002138 vcpu::kick_all_vcpus(
Zach Reiznerdc748482021-04-14 13:59:30 -07002139 &vcpu_handles,
2140 linux.irq_chip.as_irq_chip(),
Daniel Verkamp29409802021-02-24 14:46:19 -08002141 VcpuControl::RunState(VmRunMode::Exiting),
Zach Reiznerdc748482021-04-14 13:59:30 -07002142 );
Steven Richman11dc6712020-09-02 15:39:14 -07002143 for (handle, _) in vcpu_handles {
2144 if let Err(e) = handle.join() {
2145 error!("failed to join vcpu thread: {:?}", e);
Zach Reizner39aa26b2017-12-12 18:03:23 -08002146 }
2147 }
2148
Daniel Verkamp94c35272019-09-12 13:31:30 -07002149 // Explicitly drop the VM structure here to allow the devices to clean up before the
2150 // control sockets are closed when this function exits.
2151 mem::drop(linux);
2152
Zach Reizner19ad1f32019-12-12 18:58:50 -08002153 stdin()
Zach Reizner39aa26b2017-12-12 18:03:23 -08002154 .set_canon_mode()
2155 .expect("failed to restore canonical mode for terminal");
2156
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08002157 Ok(exit_state)
Zach Reizner39aa26b2017-12-12 18:03:23 -08002158}
Daniel Verkamp5586ff52022-02-24 16:34:55 -08002159
2160#[cfg(test)]
2161mod tests {
2162 use super::*;
Xiong Zhang626f0142022-03-12 16:05:17 +08002163 use std::path::PathBuf;
Daniel Verkamp5586ff52022-02-24 16:34:55 -08002164
2165 // Create a file-backed mapping parameters struct with the given `address` and `size` and other
2166 // parameters set to default values.
2167 fn test_file_backed_mapping(address: u64, size: u64) -> FileBackedMappingParameters {
2168 FileBackedMappingParameters {
2169 address,
2170 size,
2171 path: PathBuf::new(),
2172 offset: 0,
2173 writable: false,
2174 sync: false,
2175 }
2176 }
2177
2178 #[test]
2179 fn guest_mem_file_backed_mappings_overlap() {
2180 // Base case: no file mappings; output layout should be identical.
2181 assert_eq!(
2182 punch_holes_in_guest_mem_layout_for_mappings(
2183 vec![
2184 (GuestAddress(0), 0xD000_0000),
2185 (GuestAddress(0x1_0000_0000), 0x8_0000),
2186 ],
2187 &[]
2188 ),
2189 vec![
2190 (GuestAddress(0), 0xD000_0000),
2191 (GuestAddress(0x1_0000_0000), 0x8_0000),
2192 ]
2193 );
2194
2195 // File mapping that does not overlap guest memory.
2196 assert_eq!(
2197 punch_holes_in_guest_mem_layout_for_mappings(
2198 vec![
2199 (GuestAddress(0), 0xD000_0000),
2200 (GuestAddress(0x1_0000_0000), 0x8_0000),
2201 ],
2202 &[test_file_backed_mapping(0xD000_0000, 0x1000)]
2203 ),
2204 vec![
2205 (GuestAddress(0), 0xD000_0000),
2206 (GuestAddress(0x1_0000_0000), 0x8_0000),
2207 ]
2208 );
2209
2210 // File mapping at the start of the low address space region.
2211 assert_eq!(
2212 punch_holes_in_guest_mem_layout_for_mappings(
2213 vec![
2214 (GuestAddress(0), 0xD000_0000),
2215 (GuestAddress(0x1_0000_0000), 0x8_0000),
2216 ],
2217 &[test_file_backed_mapping(0, 0x2000)]
2218 ),
2219 vec![
2220 (GuestAddress(0x2000), 0xD000_0000 - 0x2000),
2221 (GuestAddress(0x1_0000_0000), 0x8_0000),
2222 ]
2223 );
2224
2225 // File mapping at the end of the low address space region.
2226 assert_eq!(
2227 punch_holes_in_guest_mem_layout_for_mappings(
2228 vec![
2229 (GuestAddress(0), 0xD000_0000),
2230 (GuestAddress(0x1_0000_0000), 0x8_0000),
2231 ],
2232 &[test_file_backed_mapping(0xD000_0000 - 0x2000, 0x2000)]
2233 ),
2234 vec![
2235 (GuestAddress(0), 0xD000_0000 - 0x2000),
2236 (GuestAddress(0x1_0000_0000), 0x8_0000),
2237 ]
2238 );
2239
2240 // File mapping fully contained within the middle of the low address space region.
2241 assert_eq!(
2242 punch_holes_in_guest_mem_layout_for_mappings(
2243 vec![
2244 (GuestAddress(0), 0xD000_0000),
2245 (GuestAddress(0x1_0000_0000), 0x8_0000),
2246 ],
2247 &[test_file_backed_mapping(0x1000, 0x2000)]
2248 ),
2249 vec![
2250 (GuestAddress(0), 0x1000),
2251 (GuestAddress(0x3000), 0xD000_0000 - 0x3000),
2252 (GuestAddress(0x1_0000_0000), 0x8_0000),
2253 ]
2254 );
2255
2256 // File mapping at the start of the high address space region.
2257 assert_eq!(
2258 punch_holes_in_guest_mem_layout_for_mappings(
2259 vec![
2260 (GuestAddress(0), 0xD000_0000),
2261 (GuestAddress(0x1_0000_0000), 0x8_0000),
2262 ],
2263 &[test_file_backed_mapping(0x1_0000_0000, 0x2000)]
2264 ),
2265 vec![
2266 (GuestAddress(0), 0xD000_0000),
2267 (GuestAddress(0x1_0000_2000), 0x8_0000 - 0x2000),
2268 ]
2269 );
2270
2271 // File mapping at the end of the high address space region.
2272 assert_eq!(
2273 punch_holes_in_guest_mem_layout_for_mappings(
2274 vec![
2275 (GuestAddress(0), 0xD000_0000),
2276 (GuestAddress(0x1_0000_0000), 0x8_0000),
2277 ],
2278 &[test_file_backed_mapping(0x1_0008_0000 - 0x2000, 0x2000)]
2279 ),
2280 vec![
2281 (GuestAddress(0), 0xD000_0000),
2282 (GuestAddress(0x1_0000_0000), 0x8_0000 - 0x2000),
2283 ]
2284 );
2285
2286 // File mapping fully contained within the middle of the high address space region.
2287 assert_eq!(
2288 punch_holes_in_guest_mem_layout_for_mappings(
2289 vec![
2290 (GuestAddress(0), 0xD000_0000),
2291 (GuestAddress(0x1_0000_0000), 0x8_0000),
2292 ],
2293 &[test_file_backed_mapping(0x1_0000_1000, 0x2000)]
2294 ),
2295 vec![
2296 (GuestAddress(0), 0xD000_0000),
2297 (GuestAddress(0x1_0000_0000), 0x1000),
2298 (GuestAddress(0x1_0000_3000), 0x8_0000 - 0x3000),
2299 ]
2300 );
2301
2302 // File mapping overlapping two guest memory regions.
2303 assert_eq!(
2304 punch_holes_in_guest_mem_layout_for_mappings(
2305 vec![
2306 (GuestAddress(0), 0xD000_0000),
2307 (GuestAddress(0x1_0000_0000), 0x8_0000),
2308 ],
2309 &[test_file_backed_mapping(0xA000_0000, 0x60002000)]
2310 ),
2311 vec![
2312 (GuestAddress(0), 0xA000_0000),
2313 (GuestAddress(0x1_0000_2000), 0x8_0000 - 0x2000),
2314 ]
2315 );
2316 }
2317}