blob: cc5bc0cf7ea5d5c753ac87872727ba7212f803bd [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 Zhangf7874712021-12-24 10:53:59 +080017use std::path::{Path, PathBuf};
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
Anton Romanov5acc0f52022-01-28 00:18:11 +000025use libc;
Zach Reizner39aa26b2017-12-12 18:03:23 -080026
Tomasz Jeznach42644642020-05-20 23:27:59 -070027use acpi_tables::sdt::SDT;
28
Daniel Verkamp6b298582021-08-16 15:37:11 -070029use anyhow::{anyhow, bail, Context, Result};
Zach Reiznerd49bcdb2021-01-07 08:30:28 -080030use base::*;
Daniel Verkamp578e7cc2022-03-01 22:34:52 -080031use base::{UnixSeqpacket, UnixSeqpacketListener, UnlinkUnixSeqpacketListener};
Anton Romanov5acc0f52022-01-28 00:18:11 +000032use devices::serial_device::SerialHardware;
Zide Chenafdb9382021-06-17 12:04:43 -070033use devices::vfio::{VfioCommonSetup, VfioCommonTrait};
Woody Chow055b81b2022-01-25 18:34:29 +090034use devices::virtio::memory_mapper::MemoryMapperTrait;
Anton Romanovd43ae3c2022-01-31 17:32:54 +000035#[cfg(feature = "gpu")]
Anton Romanov5acc0f52022-01-28 00:18:11 +000036use devices::virtio::{self, EventDevice};
paulhsiace17e6e2020-08-28 18:37:45 +080037#[cfg(feature = "audio")]
38use devices::Ac97Dev;
Xiong Zhang17b0daf2019-04-23 17:14:50 +080039use devices::{
Anton Romanov5acc0f52022-01-28 00:18:11 +000040 self, BusDeviceObj, HostHotPlugKey, HotPlugBus, IrqEventIndex, KvmKernelIrqChip, PciAddress,
Vineeth Pillai9a3d2dc2022-02-18 14:10:16 +000041 PciBridge, PciDevice, PcieHostRootPort, PcieRootPort, PvPanicCode, PvPanicPciDevice,
Woody Chow055b81b2022-01-25 18:34:29 +090042 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
Sonny Rao2ffa0cb2018-02-26 17:27:40 -080063#[cfg(any(target_arch = "arm", target_arch = "aarch64"))]
Steven Richmanf32d0b42020-06-20 21:45:32 -070064use {
65 aarch64::AArch64 as Arch,
Steven Richman11dc6712020-09-02 15:39:14 -070066 devices::IrqChipAArch64 as IrqChipArch,
Steven Richmanf32d0b42020-06-20 21:45:32 -070067 hypervisor::{VcpuAArch64 as VcpuArch, VmAArch64 as VmArch},
68};
Zach Reizner55a9e502018-10-03 10:22:32 -070069#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
Steven Richmanf32d0b42020-06-20 21:45:32 -070070use {
Steven Richman11dc6712020-09-02 15:39:14 -070071 devices::{IrqChipX86_64 as IrqChipArch, KvmSplitIrqChip},
72 hypervisor::{VcpuX86_64 as VcpuArch, VmX86_64 as VmArch},
Steven Richmanf32d0b42020-06-20 21:45:32 -070073 x86_64::X8664arch as Arch,
74};
Zach Reizner39aa26b2017-12-12 18:03:23 -080075
Anton Romanov5acc0f52022-01-28 00:18:11 +000076mod device_helpers;
77use device_helpers::*;
78mod jail_helpers;
79use jail_helpers::*;
80mod vcpu;
Chirantan Ekbote2ee9dcd2021-05-26 18:21:44 +090081
David Tolnay2b089fc2019-03-04 15:33:22 -080082#[cfg(feature = "gpu")]
Anton Romanov5acc0f52022-01-28 00:18:11 +000083mod gpu;
Chirantan Ekbote44292f52021-06-25 18:31:41 +090084#[cfg(feature = "gpu")]
Dmitry Torokhove464a7a2022-01-26 13:29:36 -080085pub use gpu::GpuRenderServerParameters;
86#[cfg(feature = "gpu")]
Anton Romanov5acc0f52022-01-28 00:18:11 +000087use gpu::*;
Jorge E. Moreirad4562d02021-06-28 16:21:12 -070088
Zach Reiznerd49bcdb2021-01-07 08:30:28 -080089// gpu_device_tube is not used when GPU support is disabled.
Dmitry Torokhovee42b8c2019-05-27 11:14:20 -070090#[cfg_attr(not(feature = "gpu"), allow(unused_variables))]
David Tolnay2b089fc2019-03-04 15:33:22 -080091fn create_virtio_devices(
92 cfg: &Config,
Steven Richmanf32d0b42020-06-20 21:45:32 -070093 vm: &mut impl Vm,
Jakub Starona3411ea2019-04-24 10:55:25 -070094 resources: &mut SystemAllocator,
Michael Hoyle685316f2020-09-16 15:29:20 -070095 _exit_evt: &Event,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -080096 wayland_device_tube: Tube,
97 gpu_device_tube: Tube,
Alexandre Courbote55b7912022-03-04 16:54:38 +090098 vhost_user_gpu_tubes: Vec<(Tube, Tube, Tube)>,
Andrew Walbran3cd93602022-01-25 13:59:23 +000099 balloon_device_tube: Option<Tube>,
Chuanxiao Dong146a13b2021-12-09 12:59:54 +0800100 balloon_inflate_tube: Option<Tube>,
David Stevens06d157a2022-01-13 23:44:48 +0900101 init_balloon_size: u64,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800102 disk_device_tubes: &mut Vec<Tube>,
103 pmem_device_tubes: &mut Vec<Tube>,
Lingfeng Yangd6ac1ab2020-01-31 13:55:35 -0800104 map_request: Arc<Mutex<Option<ExternalMapping>>>,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800105 fs_device_tubes: &mut Vec<Tube>,
Dmitry Torokhov9cbe5432022-01-25 19:17:07 -0800106 #[cfg(feature = "gpu")] render_server_fd: Option<SafeDescriptor>,
Abhishek Bhardwaj90fd1642021-11-24 18:26:37 -0800107 vvu_proxy_device_tubes: &mut Vec<Tube>,
David Tolnay2b089fc2019-03-04 15:33:22 -0800108) -> DeviceResult<Vec<VirtioDeviceStub>> {
Dylan Reid059a1882018-07-23 17:58:09 -0700109 let mut devs = Vec::new();
Zach Reizner39aa26b2017-12-12 18:03:23 -0800110
Chirantan Ekbote44292f52021-06-25 18:31:41 +0900111 #[cfg(feature = "gpu")]
Alexandre Courbote55b7912022-03-04 16:54:38 +0900112 for (opt, (host_gpu_tube, device_gpu_tube, device_control_tube)) in
113 cfg.vhost_user_gpu.iter().zip(vhost_user_gpu_tubes)
114 {
Chirantan Ekbote44292f52021-06-25 18:31:41 +0900115 devs.push(create_vhost_user_gpu_device(
116 cfg,
117 opt,
Alexandre Courbote55b7912022-03-04 16:54:38 +0900118 (host_gpu_tube, device_gpu_tube),
119 device_control_tube,
Chirantan Ekbote44292f52021-06-25 18:31:41 +0900120 )?);
121 }
122
Abhishek Bhardwaj103c1b72021-11-01 15:52:23 -0700123 for opt in &cfg.vvu_proxy {
Abhishek Bhardwaj90fd1642021-11-24 18:26:37 -0800124 devs.push(create_vvu_proxy_device(
125 cfg,
126 opt,
127 vvu_proxy_device_tubes.remove(0),
128 )?);
Abhishek Bhardwaj103c1b72021-11-01 15:52:23 -0700129 }
130
David Tolnayfa701712019-02-13 16:42:54 -0800131 #[cfg_attr(not(feature = "gpu"), allow(unused_mut))]
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800132 let mut resource_bridges = Vec::<Tube>::new();
Chirantan Ekbotedd11d432019-06-11 21:50:46 +0900133
Ryo Hashimoto0b788de2019-12-10 17:14:13 +0900134 if !cfg.wayland_socket_paths.is_empty() {
Chirantan Ekbotedd11d432019-06-11 21:50:46 +0900135 #[cfg_attr(not(feature = "gpu"), allow(unused_mut))]
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800136 let mut wl_resource_bridge = None::<Tube>;
Chirantan Ekbotedd11d432019-06-11 21:50:46 +0900137
138 #[cfg(feature = "gpu")]
139 {
Jason Macnakcc7070b2019-11-06 14:48:12 -0800140 if cfg.gpu_parameters.is_some() {
Daniel Verkamp6b298582021-08-16 15:37:11 -0700141 let (wl_socket, gpu_socket) = Tube::pair().context("failed to create tube")?;
Chirantan Ekbotedd11d432019-06-11 21:50:46 +0900142 resource_bridges.push(gpu_socket);
143 wl_resource_bridge = Some(wl_socket);
144 }
145 }
146
147 devs.push(create_wayland_device(
148 cfg,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800149 wayland_device_tube,
Chirantan Ekbotedd11d432019-06-11 21:50:46 +0900150 wl_resource_bridge,
151 )?);
152 }
David Tolnayfa701712019-02-13 16:42:54 -0800153
Keiichi Watanabe57df6a02019-12-06 22:24:40 +0900154 #[cfg(feature = "video-decoder")]
Alexandre Courbotb42b3e52021-07-09 23:38:57 +0900155 let video_dec_cfg = if let Some(backend) = cfg.video_dec {
Daniel Verkamp6b298582021-08-16 15:37:11 -0700156 let (video_tube, gpu_tube) = Tube::pair().context("failed to create tube")?;
Daniel Verkampffb59122021-03-18 14:06:15 -0700157 resource_bridges.push(gpu_tube);
Alexandre Courbotb42b3e52021-07-09 23:38:57 +0900158 Some((video_tube, backend))
Daniel Verkampffb59122021-03-18 14:06:15 -0700159 } else {
160 None
161 };
Keiichi Watanabe57df6a02019-12-06 22:24:40 +0900162
163 #[cfg(feature = "video-encoder")]
Alexandre Courbotb42b3e52021-07-09 23:38:57 +0900164 let video_enc_cfg = if let Some(backend) = cfg.video_enc {
Daniel Verkamp6b298582021-08-16 15:37:11 -0700165 let (video_tube, gpu_tube) = Tube::pair().context("failed to create tube")?;
Daniel Verkampffb59122021-03-18 14:06:15 -0700166 resource_bridges.push(gpu_tube);
Alexandre Courbotb42b3e52021-07-09 23:38:57 +0900167 Some((video_tube, backend))
Daniel Verkampffb59122021-03-18 14:06:15 -0700168 } else {
169 None
170 };
Keiichi Watanabe57df6a02019-12-06 22:24:40 +0900171
Zach Reizner3a8100a2017-09-13 19:15:43 -0700172 #[cfg(feature = "gpu")]
173 {
Noah Golddc7f52b2020-02-01 13:01:58 -0800174 if let Some(gpu_parameters) = &cfg.gpu_parameters {
Anton Romanov5acc0f52022-01-28 00:18:11 +0000175 let mut gpu_display_w = virtio::DEFAULT_DISPLAY_WIDTH;
176 let mut gpu_display_h = virtio::DEFAULT_DISPLAY_HEIGHT;
Jason Macnakd659a0d2021-03-15 15:33:01 -0700177 if !gpu_parameters.displays.is_empty() {
178 gpu_display_w = gpu_parameters.displays[0].width;
179 gpu_display_h = gpu_parameters.displays[0].height;
180 }
181
Zach Reizner65b98f12019-11-22 17:34:58 -0800182 let mut event_devices = Vec::new();
183 if cfg.display_window_mouse {
184 let (event_device_socket, virtio_dev_socket) =
Daniel Verkamp6b298582021-08-16 15:37:11 -0700185 UnixStream::pair().context("failed to create socket")?;
Tristan Muntsinger486cffc2020-09-29 22:05:41 +0000186 let (multi_touch_width, multi_touch_height) = cfg
187 .virtio_multi_touch
Jorge E. Moreira6635ca42021-04-28 13:11:41 -0700188 .first()
Kaiyi Libccb4eb2020-02-06 17:53:11 -0800189 .as_ref()
Tristan Muntsinger486cffc2020-09-29 22:05:41 +0000190 .map(|multi_touch_spec| multi_touch_spec.get_size())
Jason Macnakd659a0d2021-03-15 15:33:01 -0700191 .unwrap_or((gpu_display_w, gpu_display_h));
Tristan Muntsinger486cffc2020-09-29 22:05:41 +0000192 let dev = virtio::new_multi_touch(
Jorge E. Moreira6635ca42021-04-28 13:11:41 -0700193 // u32::MAX is the least likely to collide with the indices generated above for
194 // the multi_touch options, which begin at 0.
195 u32::MAX,
Kaiyi Libccb4eb2020-02-06 17:53:11 -0800196 virtio_dev_socket,
Tristan Muntsinger486cffc2020-09-29 22:05:41 +0000197 multi_touch_width,
198 multi_touch_height,
Noah Goldd4ca29b2020-10-27 12:21:52 -0700199 virtio::base_features(cfg.protected_vm),
Kaiyi Libccb4eb2020-02-06 17:53:11 -0800200 )
Daniel Verkamp6b298582021-08-16 15:37:11 -0700201 .context("failed to set up mouse device")?;
Zach Reizner65b98f12019-11-22 17:34:58 -0800202 devs.push(VirtioDeviceStub {
203 dev: Box::new(dev),
Daniel Verkamp166d1dd2021-08-19 17:05:29 -0700204 jail: simple_jail(cfg, "input_device")?,
Zach Reizner65b98f12019-11-22 17:34:58 -0800205 });
206 event_devices.push(EventDevice::touchscreen(event_device_socket));
207 }
208 if cfg.display_window_keyboard {
209 let (event_device_socket, virtio_dev_socket) =
Daniel Verkamp6b298582021-08-16 15:37:11 -0700210 UnixStream::pair().context("failed to create socket")?;
Noah Goldd4ca29b2020-10-27 12:21:52 -0700211 let dev = virtio::new_keyboard(
Jorge E. Moreira6635ca42021-04-28 13:11:41 -0700212 // u32::MAX is the least likely to collide with the indices generated above for
213 // the multi_touch options, which begin at 0.
214 u32::MAX,
Noah Goldd4ca29b2020-10-27 12:21:52 -0700215 virtio_dev_socket,
216 virtio::base_features(cfg.protected_vm),
217 )
Daniel Verkamp6b298582021-08-16 15:37:11 -0700218 .context("failed to set up keyboard device")?;
Zach Reizner65b98f12019-11-22 17:34:58 -0800219 devs.push(VirtioDeviceStub {
220 dev: Box::new(dev),
Daniel Verkamp166d1dd2021-08-19 17:05:29 -0700221 jail: simple_jail(cfg, "input_device")?,
Zach Reizner65b98f12019-11-22 17:34:58 -0800222 });
223 event_devices.push(EventDevice::keyboard(event_device_socket));
224 }
Chia-I Wu16fb6592021-11-10 11:45:32 -0800225
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700226 devs.push(create_gpu_device(
227 cfg,
228 _exit_evt,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800229 gpu_device_tube,
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700230 resource_bridges,
Ryo Hashimoto0b788de2019-12-10 17:14:13 +0900231 // Use the unnamed socket for GPU display screens.
232 cfg.wayland_socket_paths.get(""),
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700233 cfg.x_display.clone(),
Chia-I Wu16fb6592021-11-10 11:45:32 -0800234 render_server_fd,
Zach Reizner65b98f12019-11-22 17:34:58 -0800235 event_devices,
Lingfeng Yangd6ac1ab2020-01-31 13:55:35 -0800236 map_request,
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700237 )?);
Zach Reizner3a8100a2017-09-13 19:15:43 -0700238 }
239 }
240
Richard Fung08289b12022-02-02 20:46:19 +0000241 for (_, param) in cfg
242 .serial_parameters
243 .iter()
244 .filter(|(_k, v)| v.hardware == SerialHardware::VirtioConsole)
245 {
246 let dev = create_console_device(cfg, param)?;
247 devs.push(dev);
248 }
249
250 for disk in &cfg.disks {
251 let disk_device_tube = disk_device_tubes.remove(0);
252 devs.push(create_block_device(cfg, disk, disk_device_tube)?);
253 }
254
255 for blk in &cfg.vhost_user_blk {
256 devs.push(create_vhost_user_block_device(cfg, blk)?);
257 }
258
259 for console in &cfg.vhost_user_console {
260 devs.push(create_vhost_user_console_device(cfg, console)?);
261 }
262
263 for (index, pmem_disk) in cfg.pmem_devices.iter().enumerate() {
264 let pmem_device_tube = pmem_device_tubes.remove(0);
265 devs.push(create_pmem_device(
266 cfg,
267 vm,
268 resources,
269 pmem_disk,
270 index,
271 pmem_device_tube,
272 )?);
273 }
274
Andrew Walbrana24a7522022-02-09 18:23:00 +0000275 if cfg.rng {
276 devs.push(create_rng_device(cfg)?);
277 }
Richard Fung08289b12022-02-02 20:46:19 +0000278
279 #[cfg(feature = "tpm")]
280 {
281 if cfg.software_tpm {
282 devs.push(create_tpm_device(cfg)?);
283 }
284 }
285
286 for (idx, single_touch_spec) in cfg.virtio_single_touch.iter().enumerate() {
287 devs.push(create_single_touch_device(
288 cfg,
289 single_touch_spec,
290 idx as u32,
291 )?);
292 }
293
294 for (idx, multi_touch_spec) in cfg.virtio_multi_touch.iter().enumerate() {
295 devs.push(create_multi_touch_device(
296 cfg,
297 multi_touch_spec,
298 idx as u32,
299 )?);
300 }
301
302 for (idx, trackpad_spec) in cfg.virtio_trackpad.iter().enumerate() {
303 devs.push(create_trackpad_device(cfg, trackpad_spec, idx as u32)?);
304 }
305
306 for (idx, mouse_socket) in cfg.virtio_mice.iter().enumerate() {
307 devs.push(create_mouse_device(cfg, mouse_socket, idx as u32)?);
308 }
309
310 for (idx, keyboard_socket) in cfg.virtio_keyboard.iter().enumerate() {
311 devs.push(create_keyboard_device(cfg, keyboard_socket, idx as u32)?);
312 }
313
314 for (idx, switches_socket) in cfg.virtio_switches.iter().enumerate() {
315 devs.push(create_switches_device(cfg, switches_socket, idx as u32)?);
316 }
317
318 for dev_path in &cfg.virtio_input_evdevs {
319 devs.push(create_vinput_device(cfg, dev_path)?);
320 }
321
322 if let Some(balloon_device_tube) = balloon_device_tube {
323 devs.push(create_balloon_device(
324 cfg,
325 balloon_device_tube,
326 balloon_inflate_tube,
327 init_balloon_size,
328 )?);
329 }
330
331 // We checked above that if the IP is defined, then the netmask is, too.
332 for tap_fd in &cfg.tap_fd {
333 devs.push(create_tap_net_device_from_fd(cfg, *tap_fd)?);
334 }
335
336 if let (Some(host_ip), Some(netmask), Some(mac_address)) =
337 (cfg.host_ip, cfg.netmask, cfg.mac_address)
338 {
339 if !cfg.vhost_user_net.is_empty() {
340 bail!("vhost-user-net cannot be used with any of --host_ip, --netmask or --mac");
341 }
342 devs.push(create_net_device_from_config(
343 cfg,
344 host_ip,
345 netmask,
346 mac_address,
347 )?);
348 }
349
350 for tap_name in &cfg.tap_name {
351 devs.push(create_tap_net_device_from_name(cfg, tap_name.as_bytes())?);
352 }
353
354 for net in &cfg.vhost_user_net {
355 devs.push(create_vhost_user_net_device(cfg, net)?);
356 }
357
358 for vsock in &cfg.vhost_user_vsock {
359 devs.push(create_vhost_user_vsock_device(cfg, vsock)?);
360 }
361
362 for opt in &cfg.vhost_user_wl {
363 devs.push(create_vhost_user_wl_device(cfg, opt)?);
364 }
365
Chih-Yang Hsiae31731c2022-01-05 17:30:28 +0800366 #[cfg(feature = "audio_cras")]
367 {
368 for cras_snd in &cfg.cras_snds {
369 devs.push(create_cras_snd_device(cfg, cras_snd.clone())?);
370 }
371 }
372
Daniel Verkampffb59122021-03-18 14:06:15 -0700373 #[cfg(feature = "video-decoder")]
374 {
Alexandre Courbotb42b3e52021-07-09 23:38:57 +0900375 if let Some((video_dec_tube, video_dec_backend)) = video_dec_cfg {
Daniel Verkampffb59122021-03-18 14:06:15 -0700376 register_video_device(
Alexandre Courbotb42b3e52021-07-09 23:38:57 +0900377 video_dec_backend,
Daniel Verkampffb59122021-03-18 14:06:15 -0700378 &mut devs,
379 video_dec_tube,
380 cfg,
381 devices::virtio::VideoDeviceType::Decoder,
382 )?;
383 }
384 }
385
386 #[cfg(feature = "video-encoder")]
387 {
Alexandre Courbotb42b3e52021-07-09 23:38:57 +0900388 if let Some((video_enc_tube, video_enc_backend)) = video_enc_cfg {
Daniel Verkampffb59122021-03-18 14:06:15 -0700389 register_video_device(
Alexandre Courbotb42b3e52021-07-09 23:38:57 +0900390 video_enc_backend,
Daniel Verkampffb59122021-03-18 14:06:15 -0700391 &mut devs,
392 video_enc_tube,
393 cfg,
394 devices::virtio::VideoDeviceType::Encoder,
395 )?;
396 }
397 }
398
Zach Reizneraa575662018-08-15 10:46:32 -0700399 if let Some(cid) = cfg.cid {
Chirantan Ekbote3e8d52b2021-09-10 18:27:16 +0900400 devs.push(create_vhost_vsock_device(cfg, cid)?);
Zach Reizneraa575662018-08-15 10:46:32 -0700401 }
402
Woody Chow5890b702021-02-12 14:57:02 +0900403 for vhost_user_fs in &cfg.vhost_user_fs {
Daniel Verkamp166d1dd2021-08-19 17:05:29 -0700404 devs.push(create_vhost_user_fs_device(cfg, vhost_user_fs)?);
Woody Chow5890b702021-02-12 14:57:02 +0900405 }
406
Woody Chow1b16db12021-04-02 16:59:59 +0900407 #[cfg(feature = "audio")]
408 for vhost_user_snd in &cfg.vhost_user_snd {
409 devs.push(create_vhost_user_snd_device(cfg, vhost_user_snd)?);
410 }
411
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900412 for shared_dir in &cfg.shared_dirs {
413 let SharedDir {
414 src,
415 tag,
416 kind,
417 uid_map,
418 gid_map,
Chirantan Ekbote75ba8752020-10-27 18:33:02 +0900419 fs_cfg,
420 p9_cfg,
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900421 } = shared_dir;
David Tolnay2b089fc2019-03-04 15:33:22 -0800422
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900423 let dev = match kind {
Keiichi Watanabeeefe7fb2020-11-17 17:58:35 +0900424 SharedDirKind::FS => {
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800425 let device_tube = fs_device_tubes.remove(0);
426 create_fs_device(cfg, uid_map, gid_map, src, tag, fs_cfg.clone(), device_tube)?
Keiichi Watanabeeefe7fb2020-11-17 17:58:35 +0900427 }
Chirantan Ekbote75ba8752020-10-27 18:33:02 +0900428 SharedDirKind::P9 => create_9p_device(cfg, uid_map, gid_map, src, tag, p9_cfg.clone())?,
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900429 };
430 devs.push(dev);
David Tolnay2b089fc2019-03-04 15:33:22 -0800431 }
432
JaeMan Parkeb9cc532021-07-02 15:02:59 +0900433 if let Some(vhost_user_mac80211_hwsim) = &cfg.vhost_user_mac80211_hwsim {
434 devs.push(create_vhost_user_mac80211_hwsim_device(
435 cfg,
Daniel Verkamp166d1dd2021-08-19 17:05:29 -0700436 vhost_user_mac80211_hwsim,
JaeMan Parkeb9cc532021-07-02 15:02:59 +0900437 )?);
438 }
439
Jorge E. Moreirad4562d02021-06-28 16:21:12 -0700440 #[cfg(feature = "audio")]
441 if let Some(path) = &cfg.sound {
Daniel Verkamp166d1dd2021-08-19 17:05:29 -0700442 devs.push(create_sound_device(path, cfg)?);
Jorge E. Moreirad4562d02021-06-28 16:21:12 -0700443 }
444
David Tolnay2b089fc2019-03-04 15:33:22 -0800445 Ok(devs)
446}
447
448fn create_devices(
Trent Begin17ccaad2019-04-17 13:51:25 -0600449 cfg: &Config,
Steven Richmanf32d0b42020-06-20 21:45:32 -0700450 vm: &mut impl Vm,
Jakub Starona3411ea2019-04-24 10:55:25 -0700451 resources: &mut SystemAllocator,
Michael Hoyle685316f2020-09-16 15:29:20 -0700452 exit_evt: &Event,
Vineeth Pillai9a3d2dc2022-02-18 14:10:16 +0000453 panic_wrtube: Tube,
Haiwei Li09b7b8e2022-02-18 18:16:05 +0800454 iommu_attached_endpoints: &mut BTreeMap<u32, Arc<Mutex<Box<dyn MemoryMapperTrait>>>>,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800455 control_tubes: &mut Vec<TaggedControlTube>,
456 wayland_device_tube: Tube,
457 gpu_device_tube: Tube,
Alexandre Courbote55b7912022-03-04 16:54:38 +0900458 // Tuple content: (host-side GPU tube, device-side GPU tube, device-side control tube).
459 vhost_user_gpu_tubes: Vec<(Tube, Tube, Tube)>,
Andrew Walbran3cd93602022-01-25 13:59:23 +0000460 balloon_device_tube: Option<Tube>,
David Stevens06d157a2022-01-13 23:44:48 +0900461 init_balloon_size: u64,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800462 disk_device_tubes: &mut Vec<Tube>,
463 pmem_device_tubes: &mut Vec<Tube>,
464 fs_device_tubes: &mut Vec<Tube>,
Daniel Verkampf1439d42021-05-21 13:55:10 -0700465 #[cfg(feature = "usb")] usb_provider: HostBackendDeviceProvider,
Lingfeng Yangd6ac1ab2020-01-31 13:55:35 -0800466 map_request: Arc<Mutex<Option<ExternalMapping>>>,
Dmitry Torokhov9cbe5432022-01-25 19:17:07 -0800467 #[cfg(feature = "gpu")] render_server_fd: Option<SafeDescriptor>,
Abhishek Bhardwaj90fd1642021-11-24 18:26:37 -0800468 vvu_proxy_device_tubes: &mut Vec<Tube>,
Tomasz Nowickiab86d522021-09-22 05:50:46 +0000469) -> DeviceResult<Vec<(Box<dyn BusDeviceObj>, Option<Minijail>)>> {
Chuanxiao Dong146a13b2021-12-09 12:59:54 +0800470 let mut devices: Vec<(Box<dyn BusDeviceObj>, Option<Minijail>)> = Vec::new();
471 let mut balloon_inflate_tube: Option<Tube> = None;
Zide Chen5deee482021-04-19 11:06:01 -0700472 if !cfg.vfio.is_empty() {
Chuanxiao Donga8d427b2022-01-07 10:26:24 +0800473 let mut coiommu_attached_endpoints = Vec::new();
Zide Chendfc4b882021-03-10 16:35:37 -0800474
Tomasz Nowicki71aca792021-06-09 18:53:49 +0000475 for vfio_dev in cfg
476 .vfio
477 .iter()
478 .filter(|dev| dev.get_type() == VfioType::Pci)
479 {
480 let vfio_path = &vfio_dev.vfio_path;
Zide Chen5deee482021-04-19 11:06:01 -0700481 let (vfio_pci_device, jail) = create_vfio_device(
482 cfg,
483 vm,
484 resources,
485 control_tubes,
486 vfio_path.as_path(),
Xiong Zhangf82f2dc2021-05-21 16:54:12 +0800487 None,
Haiwei Li09b7b8e2022-02-18 18:16:05 +0800488 iommu_attached_endpoints,
Chuanxiao Donga8d427b2022-01-07 10:26:24 +0800489 Some(&mut coiommu_attached_endpoints),
490 vfio_dev.iommu_dev_type(),
Zide Chen5deee482021-04-19 11:06:01 -0700491 )?;
Zide Chendfc4b882021-03-10 16:35:37 -0800492
Tomasz Nowickiab86d522021-09-22 05:50:46 +0000493 devices.push((vfio_pci_device, jail));
Zide Chen5deee482021-04-19 11:06:01 -0700494 }
Zide Chendfc4b882021-03-10 16:35:37 -0800495
Tomasz Nowicki344eb142021-09-22 05:51:58 +0000496 for vfio_dev in cfg
497 .vfio
498 .iter()
499 .filter(|dev| dev.get_type() == VfioType::Platform)
500 {
501 let vfio_path = &vfio_dev.vfio_path;
502 let (vfio_plat_dev, jail) = create_vfio_platform_device(
503 cfg,
504 vm,
505 resources,
506 control_tubes,
507 vfio_path.as_path(),
Haiwei Li09b7b8e2022-02-18 18:16:05 +0800508 iommu_attached_endpoints,
Chuanxiao Donga8d427b2022-01-07 10:26:24 +0800509 IommuDevType::NoIommu, // Virtio IOMMU is not supported yet
Tomasz Nowicki344eb142021-09-22 05:51:58 +0000510 )?;
511
512 devices.push((Box::new(vfio_plat_dev), jail));
513 }
514
Chuanxiao Dongcb03ec62022-01-20 08:25:38 +0800515 if !coiommu_attached_endpoints.is_empty() || !iommu_attached_endpoints.is_empty() {
516 let mut buf = mem::MaybeUninit::<libc::rlimit>::zeroed();
517 let res = unsafe { libc::getrlimit(libc::RLIMIT_MEMLOCK, buf.as_mut_ptr()) };
518 if res == 0 {
519 let limit = unsafe { buf.assume_init() };
520 let rlim_new = limit
521 .rlim_cur
522 .saturating_add(vm.get_memory().memory_size() as libc::rlim_t);
523 let rlim_max = max(limit.rlim_max, rlim_new);
524 if limit.rlim_cur < rlim_new {
525 let limit_arg = libc::rlimit {
526 rlim_cur: rlim_new as libc::rlim_t,
527 rlim_max: rlim_max as libc::rlim_t,
528 };
529 let res = unsafe { libc::setrlimit(libc::RLIMIT_MEMLOCK, &limit_arg) };
530 if res != 0 {
531 bail!("Set rlimit failed");
532 }
533 }
534 } else {
535 bail!("Get rlimit failed");
536 }
537 }
538
Chuanxiao Donga8d427b2022-01-07 10:26:24 +0800539 if !coiommu_attached_endpoints.is_empty() {
540 let vfio_container =
541 VfioCommonSetup::vfio_get_container(IommuDevType::CoIommu, None as Option<&Path>)
542 .context("failed to get vfio container")?;
543 let (coiommu_host_tube, coiommu_device_tube) =
544 Tube::pair().context("failed to create coiommu tube")?;
545 control_tubes.push(TaggedControlTube::VmMemory(coiommu_host_tube));
546 let vcpu_count = cfg.vcpu_count.unwrap_or(1) as u64;
Chuanxiao Dong146a13b2021-12-09 12:59:54 +0800547 let (coiommu_tube, balloon_tube) =
548 Tube::pair().context("failed to create coiommu tube")?;
549 balloon_inflate_tube = Some(balloon_tube);
Chuanxiao Donga8d427b2022-01-07 10:26:24 +0800550 let dev = CoIommuDev::new(
551 vm.get_memory().clone(),
552 vfio_container,
553 coiommu_device_tube,
Chuanxiao Dong146a13b2021-12-09 12:59:54 +0800554 coiommu_tube,
Chuanxiao Donga8d427b2022-01-07 10:26:24 +0800555 coiommu_attached_endpoints,
556 vcpu_count,
Chuanxiao Dongd4468612022-01-14 14:21:17 +0800557 cfg.coiommu_param.unwrap_or_default(),
Chuanxiao Donga8d427b2022-01-07 10:26:24 +0800558 )
559 .context("failed to create coiommu device")?;
560
561 devices.push((Box::new(dev), simple_jail(cfg, "coiommu")?));
562 }
Xiong Zhang17b0daf2019-04-23 17:14:50 +0800563 }
564
Chuanxiao Dong146a13b2021-12-09 12:59:54 +0800565 let stubs = create_virtio_devices(
566 cfg,
567 vm,
568 resources,
569 exit_evt,
570 wayland_device_tube,
571 gpu_device_tube,
572 vhost_user_gpu_tubes,
573 balloon_device_tube,
574 balloon_inflate_tube,
David Stevens06d157a2022-01-13 23:44:48 +0900575 init_balloon_size,
Chuanxiao Dong146a13b2021-12-09 12:59:54 +0800576 disk_device_tubes,
577 pmem_device_tubes,
578 map_request,
579 fs_device_tubes,
Dmitry Torokhov9cbe5432022-01-25 19:17:07 -0800580 #[cfg(feature = "gpu")]
581 render_server_fd,
Abhishek Bhardwaj90fd1642021-11-24 18:26:37 -0800582 vvu_proxy_device_tubes,
Chuanxiao Dong146a13b2021-12-09 12:59:54 +0800583 )?;
584
585 for stub in stubs {
586 let (msi_host_tube, msi_device_tube) = Tube::pair().context("failed to create tube")?;
587 control_tubes.push(TaggedControlTube::VmIrq(msi_host_tube));
588 let dev = VirtioPciDevice::new(vm.get_memory().clone(), stub.dev, msi_device_tube)
589 .context("failed to create virtio pci dev")?;
590 let dev = Box::new(dev) as Box<dyn BusDeviceObj>;
591 devices.push((dev, stub.jail));
592 }
593
594 #[cfg(feature = "audio")]
595 for ac97_param in &cfg.ac97_parameters {
596 let dev = Ac97Dev::try_new(vm.get_memory().clone(), ac97_param.clone())
597 .context("failed to create ac97 device")?;
598 let jail = simple_jail(cfg, dev.minijail_policy())?;
599 devices.push((Box::new(dev), jail));
600 }
601
602 #[cfg(feature = "usb")]
Sebastian Ene0440d352022-02-04 12:23:56 +0000603 if cfg.usb {
Chuanxiao Dong146a13b2021-12-09 12:59:54 +0800604 // Create xhci controller.
605 let usb_controller = Box::new(XhciController::new(vm.get_memory().clone(), usb_provider));
606 devices.push((usb_controller, simple_jail(cfg, "xhci")?));
607 }
608
Mattias Nisslerde2c6402021-10-21 12:05:29 +0000609 for params in &cfg.stub_pci_devices {
610 // Stub devices don't need jailing since they don't do anything.
611 devices.push((Box::new(StubPciDevice::new(params)), None));
612 }
613
Vineeth Pillai9a3d2dc2022-02-18 14:10:16 +0000614 devices.push((Box::new(PvPanicPciDevice::new(panic_wrtube)), None));
Tomasz Nowickiab86d522021-09-22 05:50:46 +0000615 Ok(devices)
David Tolnay2b089fc2019-03-04 15:33:22 -0800616}
617
Mattias Nisslerbbd91d02021-12-07 08:57:45 +0000618fn create_file_backed_mappings(
619 cfg: &Config,
620 vm: &mut impl Vm,
621 resources: &mut SystemAllocator,
622) -> Result<()> {
623 for mapping in &cfg.file_backed_mappings {
624 let file = OpenOptions::new()
625 .read(true)
626 .write(mapping.writable)
627 .custom_flags(if mapping.sync { libc::O_SYNC } else { 0 })
628 .open(&mapping.path)
629 .context("failed to open file for file-backed mapping")?;
630 let prot = if mapping.writable {
631 Protection::read_write()
632 } else {
633 Protection::read()
634 };
635 let size = mapping
636 .size
637 .try_into()
638 .context("Invalid size for file-backed mapping")?;
639 let memory_mapping = MemoryMappingBuilder::new(size)
640 .from_file(&file)
641 .offset(mapping.offset)
642 .protection(prot)
643 .build()
644 .context("failed to map backing file for file-backed mapping")?;
645
Daniel Verkampde4d7292022-03-01 15:22:38 -0800646 match resources.mmio_allocator_any().allocate_at(
647 mapping.address,
648 mapping.size,
649 Alloc::FileBacked(mapping.address),
650 "file-backed mapping".to_owned(),
651 ) {
652 // OutOfSpace just means that this mapping is not in the MMIO regions at all, so don't
653 // consider it an error.
654 // TODO(b/222769529): Reserve this region in a global memory address space allocator once
655 // we have that so nothing else can accidentally overlap with it.
656 Ok(()) | Err(resources::Error::OutOfSpace) => {}
657 e => e.context("failed to allocate guest address for file-backed mapping")?,
658 }
Mattias Nisslerbbd91d02021-12-07 08:57:45 +0000659
660 vm.add_memory_region(
661 GuestAddress(mapping.address),
662 Box::new(memory_mapping),
663 !mapping.writable,
664 /* log_dirty_pages = */ false,
665 )
666 .context("failed to configure file-backed mapping")?;
667 }
668
669 Ok(())
670}
671
Xiong Zhangf7874712021-12-24 10:53:59 +0800672fn create_pcie_root_port(
673 host_pcie_rp: Vec<PathBuf>,
674 sys_allocator: &mut SystemAllocator,
675 control_tubes: &mut Vec<TaggedControlTube>,
676 devices: &mut Vec<(Box<dyn BusDeviceObj>, Option<Minijail>)>,
677 hp_vec: &mut Vec<Arc<Mutex<dyn HotPlugBus>>>,
Haiwei Li09b7b8e2022-02-18 18:16:05 +0800678 hp_endpoints_ranges: &mut Vec<RangeInclusive<u32>>,
Xiong Zhangf7874712021-12-24 10:53:59 +0800679) -> Result<()> {
680 if host_pcie_rp.is_empty() {
681 // user doesn't specify host pcie root port which link to this virtual pcie rp,
682 // find the empty bus and create a total virtual pcie rp
Haiwei Lie35d4652022-02-10 15:39:33 +0800683 let mut hp_sec_bus = 0u8;
684 // Create Pcie Root Port for non-root buses, each non-root bus device will be
685 // connected behind a virtual pcie root port.
686 for i in 1..255 {
687 if sys_allocator.pci_bus_empty(i) {
688 if hp_sec_bus == 0 {
689 hp_sec_bus = i;
690 }
691 continue;
692 }
693 let pcie_root_port = Arc::new(Mutex::new(PcieRootPort::new(i, false)));
694 let (msi_host_tube, msi_device_tube) = Tube::pair().context("failed to create tube")?;
695 control_tubes.push(TaggedControlTube::VmIrq(msi_host_tube));
696 let pci_bridge = Box::new(PciBridge::new(pcie_root_port.clone(), msi_device_tube));
697 // no ipc is used if the root port disables hotplug
698 devices.push((pci_bridge, None));
699 }
700
701 // Create Pcie Root Port for hot-plug
702 if hp_sec_bus == 0 {
703 return Err(anyhow!("no more addresses are available"));
704 }
705 let pcie_root_port = Arc::new(Mutex::new(PcieRootPort::new(hp_sec_bus, true)));
Xiong Zhangf7874712021-12-24 10:53:59 +0800706 let (msi_host_tube, msi_device_tube) = Tube::pair().context("failed to create tube")?;
707 control_tubes.push(TaggedControlTube::VmIrq(msi_host_tube));
708 let pci_bridge = Box::new(PciBridge::new(pcie_root_port.clone(), msi_device_tube));
709
Haiwei Li09b7b8e2022-02-18 18:16:05 +0800710 hp_endpoints_ranges.push(RangeInclusive::new(
711 PciAddress {
712 bus: pci_bridge.get_secondary_num(),
713 dev: 0,
714 func: 0,
715 }
716 .to_u32(),
717 PciAddress {
718 bus: pci_bridge.get_subordinate_num(),
719 dev: 32,
720 func: 8,
721 }
722 .to_u32(),
723 ));
724
Xiong Zhangf7874712021-12-24 10:53:59 +0800725 devices.push((pci_bridge, None));
726 hp_vec.push(pcie_root_port as Arc<Mutex<dyn HotPlugBus>>);
727 } else {
728 // user specify host pcie root port which link to this virtual pcie rp,
729 // reserve the host pci BDF and create a virtual pcie RP with some attrs same as host
730 for pcie_sysfs in host_pcie_rp.iter() {
Xiong Zhangd6de3192022-02-16 13:24:06 +0800731 let pcie_host = PcieHostRootPort::new(pcie_sysfs.as_path())?;
732 let bus_range = pcie_host.get_bus_range();
733 let mut slot_implemented = true;
734 for i in bus_range.secondary..=bus_range.subordinate {
735 // if this bus is occupied by one vfio-pci device, this vfio-pci device is
736 // connected to a pci bridge on host statically, then it should be connected
737 // to a virtual pci bridge in guest statically, this bridge won't have
738 // hotplug capability and won't use slot.
739 if !sys_allocator.pci_bus_empty(i) {
740 slot_implemented = false;
741 }
742 }
743 let pcie_root_port = Arc::new(Mutex::new(PcieRootPort::new_from_host(
744 pcie_host,
745 slot_implemented,
746 )?));
Xiong Zhangf7874712021-12-24 10:53:59 +0800747
748 let (msi_host_tube, msi_device_tube) = Tube::pair().context("failed to create tube")?;
749 control_tubes.push(TaggedControlTube::VmIrq(msi_host_tube));
750 let mut pci_bridge = Box::new(PciBridge::new(pcie_root_port.clone(), msi_device_tube));
751 // early reservation for host pcie root port devices.
752 let rootport_addr = pci_bridge.allocate_address(sys_allocator);
753 if rootport_addr.is_err() {
754 warn!(
755 "address reservation failed for hot pcie root port {}",
756 pci_bridge.debug_label()
757 );
758 }
759
Haiwei Li09b7b8e2022-02-18 18:16:05 +0800760 hp_endpoints_ranges.push(RangeInclusive::new(
761 PciAddress {
762 bus: pci_bridge.get_secondary_num(),
763 dev: 0,
764 func: 0,
765 }
766 .to_u32(),
767 PciAddress {
768 bus: pci_bridge.get_subordinate_num(),
769 dev: 32,
770 func: 8,
771 }
772 .to_u32(),
773 ));
774
Xiong Zhangf7874712021-12-24 10:53:59 +0800775 devices.push((pci_bridge, None));
776 hp_vec.push(pcie_root_port as Arc<Mutex<dyn HotPlugBus>>);
777 }
778 }
779
780 Ok(())
781}
782
Zach Reiznera90649a2021-03-31 12:56:08 -0700783fn setup_vm_components(cfg: &Config) -> Result<VmComponents> {
David Tolnay2b089fc2019-03-04 15:33:22 -0800784 let initrd_image = if let Some(initrd_path) = &cfg.initrd_path {
Andrew Walbranbc55e302021-07-13 17:35:10 +0100785 Some(
Junichi Uekawa7bea39f2021-07-16 14:05:06 +0900786 open_file(
787 initrd_path,
788 true, /*read_only*/
789 false, /*O_DIRECT*/
790 )
Daniel Verkamp6b298582021-08-16 15:37:11 -0700791 .with_context(|| format!("failed to open initrd {}", initrd_path.display()))?,
Andrew Walbranbc55e302021-07-13 17:35:10 +0100792 )
Daniel Verkampe403f5c2018-12-11 16:29:26 -0800793 } else {
794 None
795 };
796
Cody Schuffelen6d1ab502019-05-21 12:12:38 -0700797 let vm_image = match cfg.executable_path {
Andrew Walbranbc55e302021-07-13 17:35:10 +0100798 Some(Executable::Kernel(ref kernel_path)) => VmImage::Kernel(
Junichi Uekawa7bea39f2021-07-16 14:05:06 +0900799 open_file(
800 kernel_path,
801 true, /*read_only*/
802 false, /*O_DIRECT*/
803 )
Daniel Verkamp6b298582021-08-16 15:37:11 -0700804 .with_context(|| format!("failed to open kernel image {}", kernel_path.display()))?,
Andrew Walbranbc55e302021-07-13 17:35:10 +0100805 ),
806 Some(Executable::Bios(ref bios_path)) => VmImage::Bios(
Junichi Uekawa7bea39f2021-07-16 14:05:06 +0900807 open_file(bios_path, true /*read_only*/, false /*O_DIRECT*/)
Daniel Verkamp6b298582021-08-16 15:37:11 -0700808 .with_context(|| format!("failed to open bios {}", bios_path.display()))?,
Andrew Walbranbc55e302021-07-13 17:35:10 +0100809 ),
Cody Schuffelen6d1ab502019-05-21 12:12:38 -0700810 _ => panic!("Did not receive a bios or kernel, should be impossible."),
811 };
812
Will Deaconc48e7832021-07-30 19:03:06 +0100813 let swiotlb = if let Some(size) = cfg.swiotlb {
814 Some(
815 size.checked_mul(1024 * 1024)
Daniel Verkamp6b298582021-08-16 15:37:11 -0700816 .ok_or_else(|| anyhow!("requested swiotlb size too large"))?,
Will Deaconc48e7832021-07-30 19:03:06 +0100817 )
818 } else {
819 match cfg.protected_vm {
Andrew Walbran0bbbb682021-12-13 13:42:07 +0000820 ProtectionType::Protected | ProtectionType::ProtectedWithoutFirmware => {
821 Some(64 * 1024 * 1024)
822 }
Will Deaconc48e7832021-07-30 19:03:06 +0100823 ProtectionType::Unprotected => None,
824 }
825 };
826
Zach Reiznera90649a2021-03-31 12:56:08 -0700827 Ok(VmComponents {
Daniel Verkamp6a847062019-11-26 13:16:35 -0800828 memory_size: cfg
829 .memory
830 .unwrap_or(256)
831 .checked_mul(1024 * 1024)
Daniel Verkamp6b298582021-08-16 15:37:11 -0700832 .ok_or_else(|| anyhow!("requested memory size too large"))?,
Will Deaconc48e7832021-07-30 19:03:06 +0100833 swiotlb,
Dylan Reid059a1882018-07-23 17:58:09 -0700834 vcpu_count: cfg.vcpu_count.unwrap_or(1),
Daniel Verkamp107edb32019-04-05 09:58:48 -0700835 vcpu_affinity: cfg.vcpu_affinity.clone(),
Daniel Verkamp8a72afc2021-03-15 17:55:52 -0700836 cpu_clusters: cfg.cpu_clusters.clone(),
837 cpu_capacity: cfg.cpu_capacity.clone(),
Suleiman Souhlal015c3c12020-10-07 14:15:41 +0900838 no_smt: cfg.no_smt,
Sergey Senozhatsky1e369c52021-04-13 20:23:51 +0900839 hugepages: cfg.hugepages,
Cody Schuffelen6d1ab502019-05-21 12:12:38 -0700840 vm_image,
Tristan Muntsinger4133b012018-12-21 16:01:56 -0800841 android_fstab: cfg
842 .android_fstab
843 .as_ref()
Daniel Verkamp6b298582021-08-16 15:37:11 -0700844 .map(|x| {
845 File::open(x)
846 .with_context(|| format!("failed to open android fstab file {}", x.display()))
847 })
Tristan Muntsinger4133b012018-12-21 16:01:56 -0800848 .map_or(Ok(None), |v| v.map(Some))?,
Kansho Nishida282115b2019-12-18 13:13:14 +0900849 pstore: cfg.pstore.clone(),
Daniel Verkampe403f5c2018-12-11 16:29:26 -0800850 initrd_image,
Daniel Verkampaac28132018-10-15 14:58:48 -0700851 extra_kernel_params: cfg.params.clone(),
Tomasz Jeznach42644642020-05-20 23:27:59 -0700852 acpi_sdts: cfg
853 .acpi_tables
854 .iter()
Daniel Verkamp6b298582021-08-16 15:37:11 -0700855 .map(|path| {
856 SDT::from_file(path)
857 .with_context(|| format!("failed to open ACPI file {}", path.display()))
858 })
Tomasz Jeznach42644642020-05-20 23:27:59 -0700859 .collect::<Result<Vec<SDT>>>()?,
Kansho Nishidaab205af2020-08-13 18:17:50 +0900860 rt_cpus: cfg.rt_cpus.clone(),
Suleiman Souhlal63630e82021-02-18 11:53:11 +0900861 delay_rt: cfg.delay_rt,
Will Deacon7d2b8ac2020-10-06 18:51:12 +0100862 protected_vm: cfg.protected_vm,
Keiichi Watanabec5262e92020-10-21 15:57:33 +0900863 #[cfg(all(target_arch = "x86_64", feature = "gdb"))]
Zach Reiznera90649a2021-03-31 12:56:08 -0700864 gdb: None,
Tomasz Jeznachccb26942021-03-30 22:44:11 -0700865 dmi_path: cfg.dmi_path.clone(),
Tomasz Jeznachd93c29f2021-04-12 11:00:24 -0700866 no_legacy: cfg.no_legacy,
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +0800867 host_cpu_topology: cfg.host_cpu_topology,
Grzegorz Jaszczykd33874e2022-02-11 18:27:29 +0000868 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
869 force_s2idle: cfg.force_s2idle,
Zach Reiznera90649a2021-03-31 12:56:08 -0700870 })
871}
872
Andrew Walbranb28ae8e2022-01-17 14:33:10 +0000873#[derive(Copy, Clone, Debug, Eq, PartialEq)]
Dmitry Torokhovf75699f2021-12-03 11:19:13 -0800874pub enum ExitState {
875 Reset,
876 Stop,
Andrew Walbran1a19c672022-01-24 17:24:10 +0000877 Crash,
Vineeth Pillai9a3d2dc2022-02-18 14:10:16 +0000878 GuestPanic,
Dmitry Torokhovf75699f2021-12-03 11:19:13 -0800879}
880
Daniel Verkamp5586ff52022-02-24 16:34:55 -0800881// Remove ranges in `guest_mem_layout` that overlap with ranges in `file_backed_mappings`.
882// Returns the updated guest memory layout.
883fn punch_holes_in_guest_mem_layout_for_mappings(
884 guest_mem_layout: Vec<(GuestAddress, u64)>,
885 file_backed_mappings: &[FileBackedMappingParameters],
886) -> Vec<(GuestAddress, u64)> {
887 // Create a set containing (start, end) pairs with exclusive end (end = start + size; the byte
888 // at end is not included in the range).
889 let mut layout_set = BTreeSet::new();
890 for (addr, size) in &guest_mem_layout {
891 layout_set.insert((addr.offset(), addr.offset() + size));
892 }
893
894 for mapping in file_backed_mappings {
895 let mapping_start = mapping.address;
896 let mapping_end = mapping_start + mapping.size;
897
898 // Repeatedly split overlapping guest memory regions until no overlaps remain.
899 while let Some((range_start, range_end)) = layout_set
900 .iter()
901 .find(|&&(range_start, range_end)| {
902 mapping_start < range_end && mapping_end > range_start
903 })
904 .cloned()
905 {
906 layout_set.remove(&(range_start, range_end));
907
908 if range_start < mapping_start {
909 layout_set.insert((range_start, mapping_start));
910 }
911 if range_end > mapping_end {
912 layout_set.insert((mapping_end, range_end));
913 }
914 }
915 }
916
917 // Build the final guest memory layout from the modified layout_set.
918 layout_set
919 .iter()
920 .map(|(start, end)| (GuestAddress(*start), end - start))
921 .collect()
922}
923
Dmitry Torokhovf75699f2021-12-03 11:19:13 -0800924pub fn run_config(cfg: Config) -> Result<ExitState> {
Zach Reiznerdc748482021-04-14 13:59:30 -0700925 let components = setup_vm_components(&cfg)?;
926
927 let guest_mem_layout =
Daniel Verkamp6b298582021-08-16 15:37:11 -0700928 Arch::guest_memory_layout(&components).context("failed to create guest memory layout")?;
Daniel Verkamp5586ff52022-02-24 16:34:55 -0800929
930 let guest_mem_layout =
931 punch_holes_in_guest_mem_layout_for_mappings(guest_mem_layout, &cfg.file_backed_mappings);
932
Daniel Verkamp6b298582021-08-16 15:37:11 -0700933 let guest_mem = GuestMemory::new(&guest_mem_layout).context("failed to create guest memory")?;
Zach Reiznerdc748482021-04-14 13:59:30 -0700934 let mut mem_policy = MemoryPolicy::empty();
935 if components.hugepages {
936 mem_policy |= MemoryPolicy::USE_HUGEPAGES;
937 }
Quentin Perret26203802021-12-02 09:48:43 +0000938 guest_mem.set_memory_policy(mem_policy);
Daniel Verkamp6b298582021-08-16 15:37:11 -0700939 let kvm = Kvm::new_with_path(&cfg.kvm_device_path).context("failed to create kvm")?;
Andrew Walbran00f1c9f2021-12-10 17:13:08 +0000940 let vm = KvmVm::new(&kvm, guest_mem, components.protected_vm).context("failed to create vm")?;
Andrew Walbrane79aba12022-01-27 14:12:35 +0000941 // Check that the VM was actually created in protected mode as expected.
942 if cfg.protected_vm != ProtectionType::Unprotected && !vm.check_capability(VmCap::Protected) {
943 bail!("Failed to create protected VM");
944 }
Daniel Verkamp6b298582021-08-16 15:37:11 -0700945 let vm_clone = vm.try_clone().context("failed to clone vm")?;
Zach Reiznerdc748482021-04-14 13:59:30 -0700946
947 enum KvmIrqChip {
948 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
949 Split(KvmSplitIrqChip),
950 Kernel(KvmKernelIrqChip),
951 }
952
953 impl KvmIrqChip {
954 fn as_mut(&mut self) -> &mut dyn IrqChipArch {
955 match self {
956 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
957 KvmIrqChip::Split(i) => i,
958 KvmIrqChip::Kernel(i) => i,
959 }
960 }
961 }
962
963 let ioapic_host_tube;
964 let mut irq_chip = if cfg.split_irqchip {
965 #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
966 unimplemented!("KVM split irqchip mode only supported on x86 processors");
967 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
968 {
Daniel Verkamp6b298582021-08-16 15:37:11 -0700969 let (host_tube, ioapic_device_tube) = Tube::pair().context("failed to create tube")?;
Zach Reiznerdc748482021-04-14 13:59:30 -0700970 ioapic_host_tube = Some(host_tube);
971 KvmIrqChip::Split(
972 KvmSplitIrqChip::new(
973 vm_clone,
974 components.vcpu_count,
975 ioapic_device_tube,
976 Some(120),
977 )
Daniel Verkamp6b298582021-08-16 15:37:11 -0700978 .context("failed to create IRQ chip")?,
Zach Reiznerdc748482021-04-14 13:59:30 -0700979 )
980 }
981 } else {
982 ioapic_host_tube = None;
983 KvmIrqChip::Kernel(
Daniel Verkamp6b298582021-08-16 15:37:11 -0700984 KvmKernelIrqChip::new(vm_clone, components.vcpu_count)
985 .context("failed to create IRQ chip")?,
Zach Reiznerdc748482021-04-14 13:59:30 -0700986 )
987 };
988
989 run_vm::<KvmVcpu, KvmVm>(cfg, components, vm, irq_chip.as_mut(), ioapic_host_tube)
990}
991
992fn run_vm<Vcpu, V>(
Zach Reiznera90649a2021-03-31 12:56:08 -0700993 cfg: Config,
994 #[allow(unused_mut)] mut components: VmComponents,
Zach Reiznerdc748482021-04-14 13:59:30 -0700995 mut vm: V,
996 irq_chip: &mut dyn IrqChipArch,
997 ioapic_host_tube: Option<Tube>,
Dmitry Torokhovf75699f2021-12-03 11:19:13 -0800998) -> Result<ExitState>
Zach Reiznera90649a2021-03-31 12:56:08 -0700999where
1000 Vcpu: VcpuArch + 'static,
1001 V: VmArch + 'static,
Zach Reiznera90649a2021-03-31 12:56:08 -07001002{
1003 if cfg.sandbox {
1004 // Printing something to the syslog before entering minijail so that libc's syslogger has a
1005 // chance to open files necessary for its operation, like `/etc/localtime`. After jailing,
1006 // access to those files will not be possible.
1007 info!("crosvm entering multiprocess mode");
1008 }
1009
Daniel Verkampf1439d42021-05-21 13:55:10 -07001010 #[cfg(feature = "usb")]
Zach Reiznera90649a2021-03-31 12:56:08 -07001011 let (usb_control_tube, usb_provider) =
Daniel Verkamp6b298582021-08-16 15:37:11 -07001012 HostBackendDeviceProvider::new().context("failed to create usb provider")?;
Daniel Verkampf1439d42021-05-21 13:55:10 -07001013
Zach Reiznera90649a2021-03-31 12:56:08 -07001014 // Masking signals is inherently dangerous, since this can persist across clones/execs. Do this
1015 // before any jailed devices have been spawned, so that we can catch any of them that fail very
1016 // quickly.
Daniel Verkamp6b298582021-08-16 15:37:11 -07001017 let sigchld_fd = SignalFd::new(libc::SIGCHLD).context("failed to create signalfd")?;
Dylan Reid059a1882018-07-23 17:58:09 -07001018
Zach Reiznera60744b2019-02-13 17:33:32 -08001019 let control_server_socket = match &cfg.socket_path {
1020 Some(path) => Some(UnlinkUnixSeqpacketListener(
Daniel Verkamp6b298582021-08-16 15:37:11 -07001021 UnixSeqpacketListener::bind(path).context("failed to create control server")?,
Zach Reiznera60744b2019-02-13 17:33:32 -08001022 )),
1023 None => None,
Dylan Reid059a1882018-07-23 17:58:09 -07001024 };
Zach Reiznera60744b2019-02-13 17:33:32 -08001025
Zach Reiznera90649a2021-03-31 12:56:08 -07001026 let mut control_tubes = Vec::new();
1027
1028 #[cfg(all(target_arch = "x86_64", feature = "gdb"))]
1029 if let Some(port) = cfg.gdb {
1030 // GDB needs a control socket to interrupt vcpus.
Daniel Verkamp6b298582021-08-16 15:37:11 -07001031 let (gdb_host_tube, gdb_control_tube) = Tube::pair().context("failed to create tube")?;
Zach Reiznera90649a2021-03-31 12:56:08 -07001032 control_tubes.push(TaggedControlTube::Vm(gdb_host_tube));
1033 components.gdb = Some((port, gdb_control_tube));
1034 }
1035
Chirantan Ekbote2ee9dcd2021-05-26 18:21:44 +09001036 for wl_cfg in &cfg.vhost_user_wl {
1037 let wayland_host_tube = UnixSeqpacket::connect(&wl_cfg.vm_tube)
1038 .map(Tube::new)
Daniel Verkamp6b298582021-08-16 15:37:11 -07001039 .context("failed to connect to wayland tube")?;
Chirantan Ekbote2ee9dcd2021-05-26 18:21:44 +09001040 control_tubes.push(TaggedControlTube::VmMemory(wayland_host_tube));
1041 }
1042
Chirantan Ekbote44292f52021-06-25 18:31:41 +09001043 let mut vhost_user_gpu_tubes = Vec::with_capacity(cfg.vhost_user_gpu.len());
1044 for _ in 0..cfg.vhost_user_gpu.len() {
Alexandre Courbote55b7912022-03-04 16:54:38 +09001045 let (host_control_tube, device_control_tube) =
1046 Tube::pair().context("failed to create tube")?;
1047 let (host_gpu_tube, device_gpu_tube) = Tube::pair().context("failed to create tube")?;
1048 vhost_user_gpu_tubes.push((host_gpu_tube, device_gpu_tube, device_control_tube));
1049 control_tubes.push(TaggedControlTube::VmMemory(host_control_tube));
Chirantan Ekbote44292f52021-06-25 18:31:41 +09001050 }
1051
Daniel Verkamp6b298582021-08-16 15:37:11 -07001052 let (wayland_host_tube, wayland_device_tube) = Tube::pair().context("failed to create tube")?;
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001053 control_tubes.push(TaggedControlTube::VmMemory(wayland_host_tube));
Andrew Walbran3cd93602022-01-25 13:59:23 +00001054
1055 let (balloon_host_tube, balloon_device_tube) = if cfg.balloon {
David Stevens8be9ef02022-01-13 22:50:24 +09001056 if let Some(ref path) = cfg.balloon_control {
1057 (
1058 None,
1059 Some(Tube::new(
1060 UnixSeqpacket::connect(path).context("failed to create balloon control")?,
1061 )),
1062 )
1063 } else {
1064 // Balloon gets a special socket so balloon requests can be forwarded
1065 // from the main process.
1066 let (host, device) = Tube::pair().context("failed to create tube")?;
1067 // Set recv timeout to avoid deadlock on sending BalloonControlCommand
1068 // before the guest is ready.
1069 host.set_recv_timeout(Some(Duration::from_millis(100)))
1070 .context("failed to set timeout")?;
1071 (Some(host), Some(device))
1072 }
Andrew Walbran3cd93602022-01-25 13:59:23 +00001073 } else {
1074 (None, None)
1075 };
Dylan Reid059a1882018-07-23 17:58:09 -07001076
Daniel Verkamp92f73d72018-12-04 13:17:46 -08001077 // Create one control socket per disk.
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001078 let mut disk_device_tubes = Vec::new();
1079 let mut disk_host_tubes = Vec::new();
Daniel Verkamp92f73d72018-12-04 13:17:46 -08001080 let disk_count = cfg.disks.len();
1081 for _ in 0..disk_count {
Daniel Verkamp6b298582021-08-16 15:37:11 -07001082 let (disk_host_tub, disk_device_tube) = Tube::pair().context("failed to create tube")?;
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001083 disk_host_tubes.push(disk_host_tub);
1084 disk_device_tubes.push(disk_device_tube);
Daniel Verkamp92f73d72018-12-04 13:17:46 -08001085 }
1086
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001087 let mut pmem_device_tubes = Vec::new();
Daniel Verkampe1980a92020-02-07 11:00:55 -08001088 let pmem_count = cfg.pmem_devices.len();
1089 for _ in 0..pmem_count {
Daniel Verkamp6b298582021-08-16 15:37:11 -07001090 let (pmem_host_tube, pmem_device_tube) = Tube::pair().context("failed to create tube")?;
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001091 pmem_device_tubes.push(pmem_device_tube);
1092 control_tubes.push(TaggedControlTube::VmMsync(pmem_host_tube));
Daniel Verkampe1980a92020-02-07 11:00:55 -08001093 }
1094
Daniel Verkamp6b298582021-08-16 15:37:11 -07001095 let (gpu_host_tube, gpu_device_tube) = Tube::pair().context("failed to create tube")?;
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001096 control_tubes.push(TaggedControlTube::VmMemory(gpu_host_tube));
Gurchetan Singh96beafc2019-05-15 09:46:52 -07001097
Zach Reiznerdc748482021-04-14 13:59:30 -07001098 if let Some(ioapic_host_tube) = ioapic_host_tube {
1099 control_tubes.push(TaggedControlTube::VmIrq(ioapic_host_tube));
1100 }
Zhuocheng Dingf2e90bf2019-12-02 15:50:20 +08001101
Chuanxiao Dongbbb32af2020-04-27 16:37:10 +08001102 let battery = if cfg.battery_type.is_some() {
Daniel Verkampcfe49462021-08-19 17:11:05 -07001103 #[cfg_attr(not(feature = "power-monitor-powerd"), allow(clippy::manual_map))]
Alex Lauf408c732020-11-10 18:24:04 +09001104 let jail = match simple_jail(&cfg, "battery")? {
Daniel Verkampcfe49462021-08-19 17:11:05 -07001105 #[cfg_attr(not(feature = "power-monitor-powerd"), allow(unused_mut))]
Alex Lauf408c732020-11-10 18:24:04 +09001106 Some(mut jail) => {
1107 // Setup a bind mount to the system D-Bus socket if the powerd monitor is used.
1108 #[cfg(feature = "power-monitor-powerd")]
1109 {
Fergus Dall51200512021-08-19 12:54:26 +10001110 add_current_user_to_jail(&mut jail)?;
Alex Lauf408c732020-11-10 18:24:04 +09001111
1112 // Create a tmpfs in the device's root directory so that we can bind mount files.
1113 jail.mount_with_data(
1114 Path::new("none"),
1115 Path::new("/"),
1116 "tmpfs",
1117 (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as usize,
1118 "size=67108864",
1119 )?;
1120
1121 let system_bus_socket_path = Path::new("/run/dbus/system_bus_socket");
1122 jail.mount_bind(system_bus_socket_path, system_bus_socket_path, true)?;
1123 }
1124 Some(jail)
1125 }
1126 None => None,
1127 };
1128 (&cfg.battery_type, jail)
Chuanxiao Dongbbb32af2020-04-27 16:37:10 +08001129 } else {
1130 (&cfg.battery_type, None)
1131 };
1132
Lingfeng Yangd6ac1ab2020-01-31 13:55:35 -08001133 let map_request: Arc<Mutex<Option<ExternalMapping>>> = Arc::new(Mutex::new(None));
1134
Keiichi Watanabeeefe7fb2020-11-17 17:58:35 +09001135 let fs_count = cfg
1136 .shared_dirs
1137 .iter()
1138 .filter(|sd| sd.kind == SharedDirKind::FS)
1139 .count();
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001140 let mut fs_device_tubes = Vec::with_capacity(fs_count);
Keiichi Watanabeeefe7fb2020-11-17 17:58:35 +09001141 for _ in 0..fs_count {
Daniel Verkamp6b298582021-08-16 15:37:11 -07001142 let (fs_host_tube, fs_device_tube) = Tube::pair().context("failed to create tube")?;
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001143 control_tubes.push(TaggedControlTube::Fs(fs_host_tube));
1144 fs_device_tubes.push(fs_device_tube);
Keiichi Watanabeeefe7fb2020-11-17 17:58:35 +09001145 }
1146
Abhishek Bhardwaj90fd1642021-11-24 18:26:37 -08001147 let mut vvu_proxy_device_tubes = Vec::new();
1148 for _ in 0..cfg.vvu_proxy.len() {
1149 let (vvu_proxy_host_tube, vvu_proxy_device_tube) =
1150 Tube::pair().context("failed to create VVU proxy tube")?;
1151 control_tubes.push(TaggedControlTube::VmMemory(vvu_proxy_host_tube));
1152 vvu_proxy_device_tubes.push(vvu_proxy_device_tube);
1153 }
1154
Daniel Verkamp6b298582021-08-16 15:37:11 -07001155 let exit_evt = Event::new().context("failed to create event")?;
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08001156 let reset_evt = Event::new().context("failed to create event")?;
Andrew Walbran1a19c672022-01-24 17:24:10 +00001157 let crash_evt = Event::new().context("failed to create event")?;
Vineeth Pillai9a3d2dc2022-02-18 14:10:16 +00001158 let (panic_rdtube, panic_wrtube) = Tube::pair().context("failed to create tube")?;
Ryo Hashimoto8f9dc1d2021-08-18 19:07:29 +09001159
David Stevense4db4172022-03-10 13:26:04 +09001160 let pstore_size = components.pstore.as_ref().map(|pstore| pstore.size as u64);
David Stevensdbd24182022-03-10 10:53:56 +09001161 let mut sys_allocator = SystemAllocator::new(
1162 Arch::get_system_allocator_config(&vm),
1163 pstore_size,
1164 &cfg.mmio_address_ranges,
1165 )
1166 .context("failed to create system allocator")?;
David Stevense4db4172022-03-10 13:26:04 +09001167
Ryo Hashimoto8f9dc1d2021-08-18 19:07:29 +09001168 let ramoops_region = match &components.pstore {
1169 Some(pstore) => Some(
David Stevense4db4172022-03-10 13:26:04 +09001170 arch::pstore::create_memory_region(
1171 &mut vm,
1172 sys_allocator.reserved_region().unwrap(),
1173 pstore,
1174 )
1175 .context("failed to allocate pstore region")?,
Ryo Hashimoto8f9dc1d2021-08-18 19:07:29 +09001176 ),
1177 None => None,
1178 };
1179
Mattias Nisslerbbd91d02021-12-07 08:57:45 +00001180 create_file_backed_mappings(&cfg, &mut vm, &mut sys_allocator)?;
1181
Dmitry Torokhov9cbe5432022-01-25 19:17:07 -08001182 #[cfg(feature = "gpu")]
1183 // Hold on to the render server jail so it keeps running until we exit run_vm()
Dmitry Torokhove464a7a2022-01-26 13:29:36 -08001184 let (_render_server_jail, render_server_fd) =
1185 if let Some(parameters) = &cfg.gpu_render_server_parameters {
1186 let (jail, fd) = start_gpu_render_server(&cfg, parameters)?;
1187 (Some(ScopedMinijail(jail)), Some(fd))
1188 } else {
1189 (None, None)
1190 };
Dmitry Torokhov9cbe5432022-01-25 19:17:07 -08001191
David Stevens06d157a2022-01-13 23:44:48 +09001192 let init_balloon_size = components
1193 .memory_size
1194 .checked_sub(cfg.init_memory.map_or(components.memory_size, |m| {
1195 m.checked_mul(1024 * 1024).unwrap_or(u64::MAX)
1196 }))
1197 .context("failed to calculate init balloon size")?;
1198
Tomasz Nowicki64f43552022-02-22 14:14:45 +00001199 #[cfg(feature = "direct")]
1200 let mut irqs = Vec::new();
1201
1202 #[cfg(feature = "direct")]
1203 for irq in &cfg.direct_level_irq {
1204 if !sys_allocator.reserve_irq(*irq) {
1205 warn!("irq {} already reserved.", irq);
1206 }
1207 let trigger = Event::new().context("failed to create event")?;
1208 let resample = Event::new().context("failed to create event")?;
1209 irq_chip
1210 .register_irq_event(*irq, &trigger, Some(&resample))
1211 .unwrap();
1212 let direct_irq = devices::DirectIrq::new(trigger, Some(resample))
1213 .context("failed to enable interrupt forwarding")?;
1214 direct_irq
1215 .irq_enable(*irq)
1216 .context("failed to enable interrupt forwarding")?;
1217 irqs.push(direct_irq);
1218 }
1219
1220 #[cfg(feature = "direct")]
1221 for irq in &cfg.direct_edge_irq {
1222 if !sys_allocator.reserve_irq(*irq) {
1223 warn!("irq {} already reserved.", irq);
1224 }
1225 let trigger = Event::new().context("failed to create event")?;
1226 irq_chip.register_irq_event(*irq, &trigger, None).unwrap();
1227 let direct_irq = devices::DirectIrq::new(trigger, None)
1228 .context("failed to enable interrupt forwarding")?;
1229 direct_irq
1230 .irq_enable(*irq)
1231 .context("failed to enable interrupt forwarding")?;
1232 irqs.push(direct_irq);
1233 }
1234
Haiwei Li09b7b8e2022-02-18 18:16:05 +08001235 let mut iommu_attached_endpoints: BTreeMap<u32, Arc<Mutex<Box<dyn MemoryMapperTrait>>>> =
1236 BTreeMap::new();
Tomasz Nowickiab86d522021-09-22 05:50:46 +00001237 let mut devices = create_devices(
Zach Reiznerdc748482021-04-14 13:59:30 -07001238 &cfg,
1239 &mut vm,
1240 &mut sys_allocator,
1241 &exit_evt,
Vineeth Pillai9a3d2dc2022-02-18 14:10:16 +00001242 panic_wrtube,
Haiwei Li09b7b8e2022-02-18 18:16:05 +08001243 &mut iommu_attached_endpoints,
Zach Reiznerdc748482021-04-14 13:59:30 -07001244 &mut control_tubes,
1245 wayland_device_tube,
1246 gpu_device_tube,
Chirantan Ekbote44292f52021-06-25 18:31:41 +09001247 vhost_user_gpu_tubes,
Zach Reiznerdc748482021-04-14 13:59:30 -07001248 balloon_device_tube,
David Stevens06d157a2022-01-13 23:44:48 +09001249 init_balloon_size,
Zach Reiznerdc748482021-04-14 13:59:30 -07001250 &mut disk_device_tubes,
1251 &mut pmem_device_tubes,
1252 &mut fs_device_tubes,
Daniel Verkampf1439d42021-05-21 13:55:10 -07001253 #[cfg(feature = "usb")]
Zach Reiznerdc748482021-04-14 13:59:30 -07001254 usb_provider,
1255 Arc::clone(&map_request),
Dmitry Torokhov9cbe5432022-01-25 19:17:07 -08001256 #[cfg(feature = "gpu")]
1257 render_server_fd,
Abhishek Bhardwaj90fd1642021-11-24 18:26:37 -08001258 &mut vvu_proxy_device_tubes,
Zach Reiznerdc748482021-04-14 13:59:30 -07001259 )?;
1260
Haiwei Li09b7b8e2022-02-18 18:16:05 +08001261 let mut hp_endpoints_ranges: Vec<RangeInclusive<u32>> = Vec::new();
1262
Xiong Zhangf7874712021-12-24 10:53:59 +08001263 let mut hotplug_buses: Vec<Arc<Mutex<dyn HotPlugBus>>> = Vec::new();
1264 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1265 {
1266 #[cfg(feature = "direct")]
1267 let rp_host = cfg.pcie_rp.clone();
1268 #[cfg(not(feature = "direct"))]
1269 let rp_host: Vec<PathBuf> = Vec::new();
1270
1271 // Create Pcie Root Port
1272 create_pcie_root_port(
1273 rp_host,
1274 &mut sys_allocator,
1275 &mut control_tubes,
1276 &mut devices,
1277 &mut hotplug_buses,
Haiwei Li09b7b8e2022-02-18 18:16:05 +08001278 &mut hp_endpoints_ranges,
Xiong Zhangf7874712021-12-24 10:53:59 +08001279 )?;
1280 }
1281
Haiwei Li09b7b8e2022-02-18 18:16:05 +08001282 let (translate_response_senders, request_rx) = setup_virtio_access_platform(
1283 &mut sys_allocator,
1284 &mut iommu_attached_endpoints,
1285 &mut devices,
1286 )?;
1287
Haiwei Li87bc2fc2022-02-18 14:37:40 +08001288 let iommu_host_tube = if !iommu_attached_endpoints.is_empty() || cfg.virtio_iommu {
Haiwei Lie2dffbf2022-02-18 14:30:56 +08001289 let (iommu_host_tube, iommu_device_tube) = Tube::pair().context("failed to create tube")?;
Haiwei Li09b7b8e2022-02-18 18:16:05 +08001290 let iommu_dev = create_iommu_device(
1291 &cfg,
1292 (1u64 << vm.get_guest_phys_addr_bits()) - 1,
1293 iommu_attached_endpoints,
1294 hp_endpoints_ranges,
1295 translate_response_senders,
1296 request_rx,
1297 iommu_device_tube,
1298 )?;
1299
1300 let (msi_host_tube, msi_device_tube) = Tube::pair().context("failed to create tube")?;
1301 control_tubes.push(TaggedControlTube::VmIrq(msi_host_tube));
1302 let mut dev = VirtioPciDevice::new(vm.get_memory().clone(), iommu_dev.dev, msi_device_tube)
1303 .context("failed to create virtio pci dev")?;
1304 // early reservation for viommu.
1305 dev.allocate_address(&mut sys_allocator)
1306 .context("failed to allocate resources early for virtio pci dev")?;
1307 let dev = Box::new(dev);
1308 devices.push((dev, iommu_dev.jail));
Haiwei Lie2dffbf2022-02-18 14:30:56 +08001309 Some(iommu_host_tube)
1310 } else {
1311 None
1312 };
Haiwei Li09b7b8e2022-02-18 18:16:05 +08001313
Peter Fangc2bba082021-04-19 18:40:24 -07001314 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
Tomasz Nowickiab86d522021-09-22 05:50:46 +00001315 for device in devices
1316 .iter_mut()
1317 .filter_map(|(dev, _)| dev.as_pci_device_mut())
1318 {
Peter Fangc2bba082021-04-19 18:40:24 -07001319 let sdts = device
1320 .generate_acpi(components.acpi_sdts)
1321 .or_else(|| {
1322 error!("ACPI table generation error");
1323 None
1324 })
Daniel Verkamp6b298582021-08-16 15:37:11 -07001325 .ok_or_else(|| anyhow!("failed to generate ACPI table"))?;
Peter Fangc2bba082021-04-19 18:40:24 -07001326 components.acpi_sdts = sdts;
1327 }
1328
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +08001329 // KVM_CREATE_VCPU uses apic id for x86 and uses cpu id for others.
1330 let mut kvm_vcpu_ids = Vec::new();
1331
Kuo-Hsin Yang6139da62021-04-14 16:55:24 +08001332 #[cfg_attr(not(feature = "direct"), allow(unused_mut))]
Zach Reiznerdc748482021-04-14 13:59:30 -07001333 let mut linux = Arch::build_vm::<V, Vcpu>(
Trent Begin17ccaad2019-04-17 13:51:25 -06001334 components,
Zach Reiznerdc748482021-04-14 13:59:30 -07001335 &exit_evt,
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08001336 &reset_evt,
Zach Reiznerdc748482021-04-14 13:59:30 -07001337 &mut sys_allocator,
Trent Begin17ccaad2019-04-17 13:51:25 -06001338 &cfg.serial_parameters,
Matt Delco45caf912019-11-13 08:11:09 -08001339 simple_jail(&cfg, "serial")?,
Chuanxiao Dongbbb32af2020-04-27 16:37:10 +08001340 battery,
Zach Reiznera90649a2021-03-31 12:56:08 -07001341 vm,
Ryo Hashimoto8f9dc1d2021-08-18 19:07:29 +09001342 ramoops_region,
Tomasz Nowickiab86d522021-09-22 05:50:46 +00001343 devices,
Zach Reiznerdc748482021-04-14 13:59:30 -07001344 irq_chip,
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +08001345 &mut kvm_vcpu_ids,
Trent Begin17ccaad2019-04-17 13:51:25 -06001346 )
Daniel Verkamp6b298582021-08-16 15:37:11 -07001347 .context("the architecture failed to build the vm")?;
Lepton Wu60893882018-11-21 11:06:18 -08001348
Daniel Verkamp1286b482021-11-30 15:14:16 -08001349 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1350 {
Xiong Zhangf7874712021-12-24 10:53:59 +08001351 for hotplug_bus in hotplug_buses.iter() {
1352 linux.hotplug_bus.push(hotplug_bus.clone());
1353 }
Daniel Verkamp1286b482021-11-30 15:14:16 -08001354 }
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08001355
Tomasz Jeznach3ce74762021-02-26 01:01:53 -08001356 #[cfg(feature = "direct")]
1357 if let Some(pmio) = &cfg.direct_pmio {
Daniel Verkamp6b298582021-08-16 15:37:11 -07001358 let direct_io = Arc::new(
1359 devices::DirectIo::new(&pmio.path, false).context("failed to open direct io device")?,
1360 );
Tomasz Jeznach3ce74762021-02-26 01:01:53 -08001361 for range in pmio.ranges.iter() {
1362 linux
1363 .io_bus
Junichi Uekawab180f9c2021-12-07 09:21:36 +09001364 .insert_sync(direct_io.clone(), range.base, range.len)
Tomasz Jeznach3ce74762021-02-26 01:01:53 -08001365 .unwrap();
1366 }
1367 };
1368
Tomasz Jeznach7271f752021-03-04 01:44:06 -08001369 #[cfg(feature = "direct")]
Tomasz Jeznach9e6c6332021-05-27 21:49:14 -07001370 if let Some(mmio) = &cfg.direct_mmio {
Xiong Zhang46471a02021-11-12 00:34:42 +08001371 let direct_mmio = Arc::new(
Junichi Uekawab180f9c2021-12-07 09:21:36 +09001372 devices::DirectMmio::new(&mmio.path, false, &mmio.ranges)
Xiong Zhang46471a02021-11-12 00:34:42 +08001373 .context("failed to open direct mmio device")?,
Daniel Verkamp6b298582021-08-16 15:37:11 -07001374 );
Xiong Zhang46471a02021-11-12 00:34:42 +08001375
Tomasz Jeznach9e6c6332021-05-27 21:49:14 -07001376 for range in mmio.ranges.iter() {
1377 linux
1378 .mmio_bus
Junichi Uekawab180f9c2021-12-07 09:21:36 +09001379 .insert_sync(direct_mmio.clone(), range.base, range.len)
Tomasz Jeznach9e6c6332021-05-27 21:49:14 -07001380 .unwrap();
1381 }
1382 };
1383
Daniel Verkamp6b298582021-08-16 15:37:11 -07001384 let gralloc = RutabagaGralloc::new().context("failed to create gralloc")?;
Daniel Verkamp92f73d72018-12-04 13:17:46 -08001385 run_control(
1386 linux,
Zach Reiznerdc748482021-04-14 13:59:30 -07001387 sys_allocator,
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001388 cfg,
Zach Reiznera60744b2019-02-13 17:33:32 -08001389 control_server_socket,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001390 control_tubes,
1391 balloon_host_tube,
1392 &disk_host_tubes,
Daniel Verkampf1439d42021-05-21 13:55:10 -07001393 #[cfg(feature = "usb")]
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001394 usb_control_tube,
Zach Reiznerdc748482021-04-14 13:59:30 -07001395 exit_evt,
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08001396 reset_evt,
Andrew Walbran1a19c672022-01-24 17:24:10 +00001397 crash_evt,
Vineeth Pillai9a3d2dc2022-02-18 14:10:16 +00001398 panic_rdtube,
Daniel Verkamp92f73d72018-12-04 13:17:46 -08001399 sigchld_fd,
Lingfeng Yangd6ac1ab2020-01-31 13:55:35 -08001400 Arc::clone(&map_request),
Gurchetan Singh293913c2020-12-09 10:44:13 -08001401 gralloc,
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +08001402 kvm_vcpu_ids,
Haiwei Lie2dffbf2022-02-18 14:30:56 +08001403 iommu_host_tube,
Daniel Verkamp92f73d72018-12-04 13:17:46 -08001404 )
Dylan Reid0ed91ab2018-05-31 15:42:18 -07001405}
1406
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08001407fn get_hp_bus<V: VmArch, Vcpu: VcpuArch>(
1408 linux: &RunnableLinuxVm<V, Vcpu>,
1409 host_addr: PciAddress,
1410) -> Result<(Arc<Mutex<dyn HotPlugBus>>, u8)> {
1411 for hp_bus in linux.hotplug_bus.iter() {
1412 if let Some(number) = hp_bus.lock().is_match(host_addr) {
1413 return Ok((hp_bus.clone(), number));
1414 }
1415 }
1416 Err(anyhow!("Failed to find a suitable hotplug bus"))
1417}
1418
Xiong Zhang8c9fe3e2021-04-12 15:07:17 +08001419fn add_vfio_device<V: VmArch, Vcpu: VcpuArch>(
1420 linux: &mut RunnableLinuxVm<V, Vcpu>,
1421 sys_allocator: &mut SystemAllocator,
1422 cfg: &Config,
1423 control_tubes: &mut Vec<TaggedControlTube>,
Haiwei Lie2dffbf2022-02-18 14:30:56 +08001424 iommu_host_tube: &Option<Tube>,
Xiong Zhang8c9fe3e2021-04-12 15:07:17 +08001425 vfio_path: &Path,
1426) -> Result<()> {
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08001427 let host_os_str = vfio_path
1428 .file_name()
1429 .ok_or_else(|| anyhow!("failed to parse or find vfio path"))?;
1430 let host_str = host_os_str
1431 .to_str()
1432 .ok_or_else(|| anyhow!("failed to parse or find vfio path"))?;
Daniel Verkamp906a38f2022-02-22 13:58:53 -08001433 let host_addr =
1434 PciAddress::from_string(host_str).context("failed to parse vfio pci address")?;
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08001435
1436 let (hp_bus, bus_num) = get_hp_bus(linux, host_addr)?;
1437
Woody Chow055b81b2022-01-25 18:34:29 +09001438 let mut endpoints: BTreeMap<u32, Arc<Mutex<Box<dyn MemoryMapperTrait>>>> = BTreeMap::new();
Xiong Zhang8c9fe3e2021-04-12 15:07:17 +08001439 let (vfio_pci_device, jail) = create_vfio_device(
1440 cfg,
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08001441 &linux.vm,
Xiong Zhang8c9fe3e2021-04-12 15:07:17 +08001442 sys_allocator,
1443 control_tubes,
1444 vfio_path,
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08001445 Some(bus_num),
Xiong Zhang8c9fe3e2021-04-12 15:07:17 +08001446 &mut endpoints,
Chuanxiao Donga8d427b2022-01-07 10:26:24 +08001447 None,
Haiwei Lie2dffbf2022-02-18 14:30:56 +08001448 if iommu_host_tube.is_some() {
1449 IommuDevType::VirtioIommu
1450 } else {
1451 IommuDevType::NoIommu
1452 },
Xiong Zhang8c9fe3e2021-04-12 15:07:17 +08001453 )?;
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08001454
1455 let pci_address = Arch::register_pci_device(linux, vfio_pci_device, jail, sys_allocator)
Daniel Verkamp6b298582021-08-16 15:37:11 -07001456 .context("Failed to configure pci hotplug device")?;
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08001457
Haiwei Lie2dffbf2022-02-18 14:30:56 +08001458 if let Some(iommu_host_tube) = iommu_host_tube {
1459 let &endpoint_addr = endpoints.iter().next().unwrap().0;
1460 let mapper = endpoints.remove(&endpoint_addr).unwrap();
1461 if let Some(vfio_wrapper) = mapper.lock().as_vfio_wrapper() {
1462 let vfio_container = vfio_wrapper.as_vfio_container();
1463 let descriptor = vfio_container.lock().into_raw_descriptor()?;
1464 let request = VirtioIOMMURequest::VfioCommand(VirtioIOMMUVfioCommand::VfioDeviceAdd {
1465 endpoint_addr,
1466 container: {
1467 // Safe because the descriptor is uniquely owned by `descriptor`.
1468 unsafe { File::from_raw_descriptor(descriptor) }
1469 },
1470 });
1471
1472 match virtio_iommu_request(iommu_host_tube, &request)
1473 .map_err(|_| VirtioIOMMUVfioError::SocketFailed)?
1474 {
1475 VirtioIOMMUResponse::VfioResponse(VirtioIOMMUVfioResult::Ok) => (),
1476 resp => bail!("Unexpected message response: {:?}", resp),
1477 }
1478 };
1479 }
1480
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08001481 let host_key = HostHotPlugKey::Vfio { host_addr };
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08001482 let mut hp_bus = hp_bus.lock();
1483 hp_bus.add_hotplug_device(host_key, pci_address);
1484 hp_bus.hot_plug(pci_address);
1485 Ok(())
Xiong Zhang8c9fe3e2021-04-12 15:07:17 +08001486}
1487
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08001488fn remove_vfio_device<V: VmArch, Vcpu: VcpuArch>(
1489 linux: &RunnableLinuxVm<V, Vcpu>,
Xiong Zhang2d45b912021-05-13 16:22:25 +08001490 sys_allocator: &mut SystemAllocator,
Haiwei Lie2dffbf2022-02-18 14:30:56 +08001491 iommu_host_tube: &Option<Tube>,
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08001492 vfio_path: &Path,
1493) -> Result<()> {
Daniel Verkamp6b298582021-08-16 15:37:11 -07001494 let host_os_str = vfio_path
1495 .file_name()
1496 .ok_or_else(|| anyhow!("failed to parse or find vfio path"))?;
1497 let host_str = host_os_str
1498 .to_str()
1499 .ok_or_else(|| anyhow!("failed to parse or find vfio path"))?;
Daniel Verkamp906a38f2022-02-22 13:58:53 -08001500 let host_addr =
1501 PciAddress::from_string(host_str).context("failed to parse vfio pci address")?;
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08001502 let host_key = HostHotPlugKey::Vfio { host_addr };
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08001503 for hp_bus in linux.hotplug_bus.iter() {
1504 let mut hp_bus_lock = hp_bus.lock();
1505 if let Some(pci_addr) = hp_bus_lock.get_hotplug_device(host_key) {
Haiwei Lie2dffbf2022-02-18 14:30:56 +08001506 if let Some(iommu_host_tube) = iommu_host_tube {
1507 let request =
1508 VirtioIOMMURequest::VfioCommand(VirtioIOMMUVfioCommand::VfioDeviceDel {
1509 endpoint_addr: pci_addr.to_u32(),
1510 });
1511 match virtio_iommu_request(iommu_host_tube, &request)
1512 .map_err(|_| VirtioIOMMUVfioError::SocketFailed)?
1513 {
1514 VirtioIOMMUResponse::VfioResponse(VirtioIOMMUVfioResult::Ok) => (),
1515 resp => bail!("Unexpected message response: {:?}", resp),
1516 }
1517 }
1518
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08001519 hp_bus_lock.hot_unplug(pci_addr);
Xiong Zhang2d45b912021-05-13 16:22:25 +08001520 sys_allocator.release_pci(pci_addr.bus, pci_addr.dev, pci_addr.func);
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08001521 return Ok(());
1522 }
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08001523 }
1524
Daniel Verkamp6b298582021-08-16 15:37:11 -07001525 Err(anyhow!("HotPlugBus hasn't been implemented"))
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08001526}
Xiong Zhang8c9fe3e2021-04-12 15:07:17 +08001527
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001528fn handle_vfio_command<V: VmArch, Vcpu: VcpuArch>(
1529 linux: &mut RunnableLinuxVm<V, Vcpu>,
1530 sys_allocator: &mut SystemAllocator,
1531 cfg: &Config,
1532 add_tubes: &mut Vec<TaggedControlTube>,
Haiwei Lie2dffbf2022-02-18 14:30:56 +08001533 iommu_host_tube: &Option<Tube>,
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001534 vfio_path: &Path,
1535 add: bool,
1536) -> VmResponse {
1537 let ret = if add {
Haiwei Lie2dffbf2022-02-18 14:30:56 +08001538 add_vfio_device(
1539 linux,
1540 sys_allocator,
1541 cfg,
1542 add_tubes,
1543 iommu_host_tube,
1544 vfio_path,
1545 )
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001546 } else {
Haiwei Lie2dffbf2022-02-18 14:30:56 +08001547 remove_vfio_device(linux, sys_allocator, iommu_host_tube, vfio_path)
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001548 };
1549
1550 match ret {
1551 Ok(()) => VmResponse::Ok,
1552 Err(e) => {
1553 error!("hanlde_vfio_command failure: {}", e);
1554 add_tubes.clear();
1555 VmResponse::Err(base::Error::new(libc::EINVAL))
1556 }
1557 }
1558}
1559
Zach Reiznerdc748482021-04-14 13:59:30 -07001560fn run_control<V: VmArch + 'static, Vcpu: VcpuArch + 'static>(
1561 mut linux: RunnableLinuxVm<V, Vcpu>,
1562 mut sys_allocator: SystemAllocator,
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001563 cfg: Config,
Zach Reiznera60744b2019-02-13 17:33:32 -08001564 control_server_socket: Option<UnlinkUnixSeqpacketListener>,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001565 mut control_tubes: Vec<TaggedControlTube>,
Andrew Walbran3cd93602022-01-25 13:59:23 +00001566 balloon_host_tube: Option<Tube>,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001567 disk_host_tubes: &[Tube],
Daniel Verkampf1439d42021-05-21 13:55:10 -07001568 #[cfg(feature = "usb")] usb_control_tube: Tube,
Zach Reiznerdc748482021-04-14 13:59:30 -07001569 exit_evt: Event,
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08001570 reset_evt: Event,
Andrew Walbran1a19c672022-01-24 17:24:10 +00001571 crash_evt: Event,
Vineeth Pillai9a3d2dc2022-02-18 14:10:16 +00001572 panic_rdtube: Tube,
Zach Reizner55a9e502018-10-03 10:22:32 -07001573 sigchld_fd: SignalFd,
Lingfeng Yangd6ac1ab2020-01-31 13:55:35 -08001574 map_request: Arc<Mutex<Option<ExternalMapping>>>,
Gurchetan Singh293913c2020-12-09 10:44:13 -08001575 mut gralloc: RutabagaGralloc,
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +08001576 kvm_vcpu_ids: Vec<usize>,
Haiwei Lie2dffbf2022-02-18 14:30:56 +08001577 iommu_host_tube: Option<Tube>,
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08001578) -> Result<ExitState> {
Zach Reizner5bed0d22018-03-28 02:31:11 -07001579 #[derive(PollToken)]
1580 enum Token {
1581 Exit,
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08001582 Reset,
Andrew Walbran1a19c672022-01-24 17:24:10 +00001583 Crash,
Vineeth Pillai9a3d2dc2022-02-18 14:10:16 +00001584 Panic,
Chuanxiao Dong546f01c2020-02-12 21:58:47 +08001585 Suspend,
Zach Reizner5bed0d22018-03-28 02:31:11 -07001586 ChildSignal,
Colin Downs-Razoukbd532762020-09-08 15:49:35 -07001587 IrqFd { index: IrqEventIndex },
Zach Reiznera60744b2019-02-13 17:33:32 -08001588 VmControlServer,
Zach Reizner5bed0d22018-03-28 02:31:11 -07001589 VmControl { index: usize },
Tomasz Nowicki98801002022-02-23 21:00:00 +00001590 DelayedIrqFd,
Zach Reizner5bed0d22018-03-28 02:31:11 -07001591 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08001592
Zach Reizner19ad1f32019-12-12 18:58:50 -08001593 stdin()
Zach Reizner39aa26b2017-12-12 18:03:23 -08001594 .set_raw_mode()
1595 .expect("failed to set terminal raw mode");
1596
Michael Hoylee392c462020-10-07 03:29:24 -07001597 let wait_ctx = WaitContext::build_with(&[
Zach Reiznerdc748482021-04-14 13:59:30 -07001598 (&exit_evt, Token::Exit),
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08001599 (&reset_evt, Token::Reset),
Andrew Walbran1a19c672022-01-24 17:24:10 +00001600 (&crash_evt, Token::Crash),
Vineeth Pillai9a3d2dc2022-02-18 14:10:16 +00001601 (&panic_rdtube, Token::Panic),
Chuanxiao Dong546f01c2020-02-12 21:58:47 +08001602 (&linux.suspend_evt, Token::Suspend),
Zach Reiznerb2110be2019-07-23 15:55:03 -07001603 (&sigchld_fd, Token::ChildSignal),
1604 ])
Daniel Verkamp6b298582021-08-16 15:37:11 -07001605 .context("failed to add descriptor to wait context")?;
Zach Reiznerb2110be2019-07-23 15:55:03 -07001606
Zach Reiznera60744b2019-02-13 17:33:32 -08001607 if let Some(socket_server) = &control_server_socket {
Michael Hoylee392c462020-10-07 03:29:24 -07001608 wait_ctx
Zach Reiznera60744b2019-02-13 17:33:32 -08001609 .add(socket_server, Token::VmControlServer)
Daniel Verkamp6b298582021-08-16 15:37:11 -07001610 .context("failed to add descriptor to wait context")?;
Zach Reiznera60744b2019-02-13 17:33:32 -08001611 }
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001612 for (index, socket) in control_tubes.iter().enumerate() {
Michael Hoylee392c462020-10-07 03:29:24 -07001613 wait_ctx
Zach Reizner55a9e502018-10-03 10:22:32 -07001614 .add(socket.as_ref(), Token::VmControl { index })
Daniel Verkamp6b298582021-08-16 15:37:11 -07001615 .context("failed to add descriptor to wait context")?;
Zach Reizner39aa26b2017-12-12 18:03:23 -08001616 }
1617
Steven Richmanf32d0b42020-06-20 21:45:32 -07001618 let events = linux
1619 .irq_chip
1620 .irq_event_tokens()
Daniel Verkamp6b298582021-08-16 15:37:11 -07001621 .context("failed to add descriptor to wait context")?;
Steven Richmanf32d0b42020-06-20 21:45:32 -07001622
Colin Downs-Razoukbd532762020-09-08 15:49:35 -07001623 for (index, _gsi, evt) in events {
Michael Hoylee392c462020-10-07 03:29:24 -07001624 wait_ctx
Colin Downs-Razoukbd532762020-09-08 15:49:35 -07001625 .add(&evt, Token::IrqFd { index })
Daniel Verkamp6b298582021-08-16 15:37:11 -07001626 .context("failed to add descriptor to wait context")?;
Zhuocheng Dingb9f4c9b2019-12-02 15:50:28 +08001627 }
1628
Tomasz Nowicki98801002022-02-23 21:00:00 +00001629 if let Some(delayed_ioapic_irq_trigger) = linux.irq_chip.irq_delayed_event_token()? {
1630 wait_ctx
1631 .add(&delayed_ioapic_irq_trigger, Token::DelayedIrqFd)
1632 .context("failed to add descriptor to wait context")?;
1633 }
1634
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001635 if cfg.sandbox {
Lepton Wu20333e42019-03-14 10:48:03 -07001636 // Before starting VCPUs, in case we started with some capabilities, drop them all.
Daniel Verkamp6b298582021-08-16 15:37:11 -07001637 drop_capabilities().context("failed to drop process capabilities")?;
Lepton Wu20333e42019-03-14 10:48:03 -07001638 }
Dmitry Torokhov71006072019-03-06 10:56:51 -08001639
Keiichi Watanabec5262e92020-10-21 15:57:33 +09001640 #[cfg(all(target_arch = "x86_64", feature = "gdb"))]
1641 // Create a channel for GDB thread.
1642 let (to_gdb_channel, from_vcpu_channel) = if linux.gdb.is_some() {
1643 let (s, r) = mpsc::channel();
1644 (Some(s), Some(r))
1645 } else {
1646 (None, None)
1647 };
1648
Steven Richmanf32d0b42020-06-20 21:45:32 -07001649 let mut vcpu_handles = Vec::with_capacity(linux.vcpu_count);
1650 let vcpu_thread_barrier = Arc::new(Barrier::new(linux.vcpu_count + 1));
Steven Richmanf32d0b42020-06-20 21:45:32 -07001651 let use_hypervisor_signals = !linux
1652 .vm
1653 .get_hypervisor()
Andrew Walbran985491a2022-01-27 13:47:40 +00001654 .check_capability(HypervisorCap::ImmediateExit);
Anton Romanov5acc0f52022-01-28 00:18:11 +00001655 vcpu::setup_vcpu_signal_handler::<Vcpu>(use_hypervisor_signals)?;
Steven Richmanf32d0b42020-06-20 21:45:32 -07001656
Zach Reizner304e7312020-09-29 16:00:24 -07001657 let vcpus: Vec<Option<_>> = match linux.vcpus.take() {
Andrew Walbran9cfdbd92021-01-11 17:40:34 +00001658 Some(vec) => vec.into_iter().map(Some).collect(),
Steven Richmanf32d0b42020-06-20 21:45:32 -07001659 None => iter::repeat_with(|| None).take(linux.vcpu_count).collect(),
1660 };
Yusuke Sato31e136a2021-08-18 11:51:38 -07001661 // Enable core scheduling before creating vCPUs so that the cookie will be
1662 // shared by all vCPU threads.
1663 // TODO(b/199312402): Avoid enabling core scheduling for the crosvm process
1664 // itself for even better performance. Only vCPUs need the feature.
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001665 if cfg.per_vm_core_scheduling {
Yusuke Sato31e136a2021-08-18 11:51:38 -07001666 if let Err(e) = enable_core_scheduling() {
1667 error!("Failed to enable core scheduling: {}", e);
1668 }
1669 }
Vineeth Pillai2b6855e2022-01-12 16:57:22 +00001670 let vcpu_cgroup_tasks_file = match &cfg.vcpu_cgroup_path {
1671 None => None,
1672 Some(cgroup_path) => {
1673 // Move main process to cgroup_path
1674 let mut f = File::create(&cgroup_path.join("tasks"))?;
1675 f.write_all(process::id().to_string().as_bytes())?;
1676 Some(f)
1677 }
1678 };
Daniel Verkamp94c35272019-09-12 13:31:30 -07001679 for (cpu_id, vcpu) in vcpus.into_iter().enumerate() {
Dylan Reidb0492662019-05-17 14:50:13 -07001680 let (to_vcpu_channel, from_main_channel) = mpsc::channel();
Daniel Verkampc677fb42020-09-08 13:47:49 -07001681 let vcpu_affinity = match linux.vcpu_affinity.clone() {
1682 Some(VcpuAffinity::Global(v)) => v,
1683 Some(VcpuAffinity::PerVcpu(mut m)) => m.remove(&cpu_id).unwrap_or_default(),
1684 None => Default::default(),
1685 };
Anton Romanov5acc0f52022-01-28 00:18:11 +00001686 let handle = vcpu::run_vcpu(
Steven Richmanf32d0b42020-06-20 21:45:32 -07001687 cpu_id,
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +08001688 kvm_vcpu_ids[cpu_id],
Zach Reizner55a9e502018-10-03 10:22:32 -07001689 vcpu,
Daniel Verkamp6b298582021-08-16 15:37:11 -07001690 linux.vm.try_clone().context("failed to clone vm")?,
1691 linux
1692 .irq_chip
1693 .try_box_clone()
1694 .context("failed to clone irqchip")?,
Steven Richmanf32d0b42020-06-20 21:45:32 -07001695 linux.vcpu_count,
Kansho Nishidaab205af2020-08-13 18:17:50 +09001696 linux.rt_cpus.contains(&cpu_id),
Daniel Verkampc677fb42020-09-08 13:47:49 -07001697 vcpu_affinity,
Suleiman Souhlal63630e82021-02-18 11:53:11 +09001698 linux.delay_rt,
Suleiman Souhlal015c3c12020-10-07 14:15:41 +09001699 linux.no_smt,
Zach Reizner55a9e502018-10-03 10:22:32 -07001700 vcpu_thread_barrier.clone(),
Steven Richmanf32d0b42020-06-20 21:45:32 -07001701 linux.has_bios,
Colin Downs-Razouk11bed5e2021-11-02 09:33:14 -07001702 (*linux.io_bus).clone(),
1703 (*linux.mmio_bus).clone(),
Daniel Verkamp6b298582021-08-16 15:37:11 -07001704 exit_evt.try_clone().context("failed to clone event")?,
Andrew Walbranb28ae8e2022-01-17 14:33:10 +00001705 reset_evt.try_clone().context("failed to clone event")?,
Andrew Walbran1a19c672022-01-24 17:24:10 +00001706 crash_evt.try_clone().context("failed to clone event")?,
Steven Richmanf32d0b42020-06-20 21:45:32 -07001707 linux.vm.check_capability(VmCap::PvClockSuspend),
Dylan Reidb0492662019-05-17 14:50:13 -07001708 from_main_channel,
Steven Richmanf32d0b42020-06-20 21:45:32 -07001709 use_hypervisor_signals,
Keiichi Watanabec5262e92020-10-21 15:57:33 +09001710 #[cfg(all(target_arch = "x86_64", feature = "gdb"))]
1711 to_gdb_channel.clone(),
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001712 cfg.per_vm_core_scheduling,
1713 cfg.host_cpu_topology,
Zide Chen344e2432022-01-28 14:58:53 -08001714 cfg.privileged_vm,
Vineeth Pillai2b6855e2022-01-12 16:57:22 +00001715 match vcpu_cgroup_tasks_file {
1716 None => None,
1717 Some(ref f) => Some(
1718 f.try_clone()
1719 .context("failed to clone vcpu cgroup tasks file")?,
1720 ),
1721 },
Zach Reizner55a9e502018-10-03 10:22:32 -07001722 )?;
Dylan Reidb0492662019-05-17 14:50:13 -07001723 vcpu_handles.push((handle, to_vcpu_channel));
Dylan Reid059a1882018-07-23 17:58:09 -07001724 }
Steven Richmanf32d0b42020-06-20 21:45:32 -07001725
Keiichi Watanabec5262e92020-10-21 15:57:33 +09001726 #[cfg(all(target_arch = "x86_64", feature = "gdb"))]
1727 // Spawn GDB thread.
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001728 if let Some((gdb_port_num, gdb_control_tube)) = linux.gdb.take() {
Keiichi Watanabec5262e92020-10-21 15:57:33 +09001729 let to_vcpu_channels = vcpu_handles
1730 .iter()
1731 .map(|(_handle, channel)| channel.clone())
1732 .collect();
1733 let target = GdbStub::new(
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001734 gdb_control_tube,
Keiichi Watanabec5262e92020-10-21 15:57:33 +09001735 to_vcpu_channels,
1736 from_vcpu_channel.unwrap(), // Must succeed to unwrap()
1737 );
1738 thread::Builder::new()
1739 .name("gdb".to_owned())
1740 .spawn(move || gdb_thread(target, gdb_port_num))
Daniel Verkamp6b298582021-08-16 15:37:11 -07001741 .context("failed to spawn GDB thread")?;
Keiichi Watanabec5262e92020-10-21 15:57:33 +09001742 };
1743
Dylan Reid059a1882018-07-23 17:58:09 -07001744 vcpu_thread_barrier.wait();
1745
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08001746 let mut exit_state = ExitState::Stop;
Charles William Dick54045012021-07-27 19:11:53 +09001747 let mut balloon_stats_id: u64 = 0;
1748
Michael Hoylee392c462020-10-07 03:29:24 -07001749 'wait: loop {
Zach Reizner5bed0d22018-03-28 02:31:11 -07001750 let events = {
Michael Hoylee392c462020-10-07 03:29:24 -07001751 match wait_ctx.wait() {
Zach Reizner39aa26b2017-12-12 18:03:23 -08001752 Ok(v) => v,
1753 Err(e) => {
David Tolnayb4bd00f2019-02-12 17:51:26 -08001754 error!("failed to poll: {}", e);
Zach Reizner39aa26b2017-12-12 18:03:23 -08001755 break;
1756 }
1757 }
1758 };
Zach Reiznera60744b2019-02-13 17:33:32 -08001759
1760 let mut vm_control_indices_to_remove = Vec::new();
Michael Hoylee392c462020-10-07 03:29:24 -07001761 for event in events.iter().filter(|e| e.is_readable) {
1762 match event.token {
Zach Reizner5bed0d22018-03-28 02:31:11 -07001763 Token::Exit => {
Zach Reizner39aa26b2017-12-12 18:03:23 -08001764 info!("vcpu requested shutdown");
Michael Hoylee392c462020-10-07 03:29:24 -07001765 break 'wait;
Zach Reizner39aa26b2017-12-12 18:03:23 -08001766 }
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08001767 Token::Reset => {
1768 info!("vcpu requested reset");
1769 exit_state = ExitState::Reset;
1770 break 'wait;
1771 }
Andrew Walbran1a19c672022-01-24 17:24:10 +00001772 Token::Crash => {
1773 info!("vcpu crashed");
1774 exit_state = ExitState::Crash;
1775 break 'wait;
1776 }
Vineeth Pillai9a3d2dc2022-02-18 14:10:16 +00001777 Token::Panic => {
1778 let mut break_to_wait: bool = true;
1779 match panic_rdtube.recv::<u8>() {
1780 Ok(panic_code) => {
1781 let panic_code = PvPanicCode::from_u8(panic_code);
1782 info!("Guest reported panic [Code: {}]", panic_code);
1783 if panic_code == PvPanicCode::CrashLoaded {
1784 // VM is booting to crash kernel.
1785 break_to_wait = false;
1786 }
1787 }
1788 Err(e) => {
1789 warn!("failed to recv panic event: {} ", e);
1790 }
1791 }
1792 if break_to_wait {
1793 exit_state = ExitState::GuestPanic;
1794 break 'wait;
1795 }
1796 }
Chuanxiao Dong546f01c2020-02-12 21:58:47 +08001797 Token::Suspend => {
1798 info!("VM requested suspend");
1799 linux.suspend_evt.read().unwrap();
Anton Romanov5acc0f52022-01-28 00:18:11 +00001800 vcpu::kick_all_vcpus(
Zach Reiznerdc748482021-04-14 13:59:30 -07001801 &vcpu_handles,
1802 linux.irq_chip.as_irq_chip(),
Daniel Verkamp29409802021-02-24 14:46:19 -08001803 VcpuControl::RunState(VmRunMode::Suspending),
Zach Reiznerdc748482021-04-14 13:59:30 -07001804 );
Chuanxiao Dong546f01c2020-02-12 21:58:47 +08001805 }
Zach Reizner5bed0d22018-03-28 02:31:11 -07001806 Token::ChildSignal => {
Zach Reizner39aa26b2017-12-12 18:03:23 -08001807 // Print all available siginfo structs, then exit the loop.
Daniel Verkamp6b298582021-08-16 15:37:11 -07001808 while let Some(siginfo) =
1809 sigchld_fd.read().context("failed to create signalfd")?
1810 {
Zach Reizner3ba00982019-01-23 19:04:43 -08001811 let pid = siginfo.ssi_pid;
1812 let pid_label = match linux.pid_debug_label_map.get(&pid) {
1813 Some(label) => format!("{} (pid {})", label, pid),
1814 None => format!("pid {}", pid),
1815 };
David Tolnayf5032762018-12-03 10:46:45 -08001816 error!(
1817 "child {} died: signo {}, status {}, code {}",
Zach Reizner3ba00982019-01-23 19:04:43 -08001818 pid_label, siginfo.ssi_signo, siginfo.ssi_status, siginfo.ssi_code
David Tolnayf5032762018-12-03 10:46:45 -08001819 );
Zach Reizner39aa26b2017-12-12 18:03:23 -08001820 }
Michael Hoylee392c462020-10-07 03:29:24 -07001821 break 'wait;
Zach Reizner39aa26b2017-12-12 18:03:23 -08001822 }
Colin Downs-Razoukbd532762020-09-08 15:49:35 -07001823 Token::IrqFd { index } => {
1824 if let Err(e) = linux.irq_chip.service_irq_event(index) {
1825 error!("failed to signal irq {}: {}", index, e);
Zhuocheng Dingb9f4c9b2019-12-02 15:50:28 +08001826 }
1827 }
Tomasz Nowicki98801002022-02-23 21:00:00 +00001828 Token::DelayedIrqFd => {
1829 if let Err(e) = linux.irq_chip.process_delayed_irq_events() {
1830 warn!("can't deliver delayed irqs: {}", e);
1831 }
1832 }
Zach Reiznera60744b2019-02-13 17:33:32 -08001833 Token::VmControlServer => {
1834 if let Some(socket_server) = &control_server_socket {
1835 match socket_server.accept() {
1836 Ok(socket) => {
Michael Hoylee392c462020-10-07 03:29:24 -07001837 wait_ctx
Zach Reiznera60744b2019-02-13 17:33:32 -08001838 .add(
1839 &socket,
1840 Token::VmControl {
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001841 index: control_tubes.len(),
Zach Reiznera60744b2019-02-13 17:33:32 -08001842 },
1843 )
Daniel Verkamp6b298582021-08-16 15:37:11 -07001844 .context("failed to add descriptor to wait context")?;
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001845 control_tubes.push(TaggedControlTube::Vm(Tube::new(socket)));
Zach Reiznera60744b2019-02-13 17:33:32 -08001846 }
1847 Err(e) => error!("failed to accept socket: {}", e),
1848 }
1849 }
1850 }
Zach Reizner5bed0d22018-03-28 02:31:11 -07001851 Token::VmControl { index } => {
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001852 let mut add_tubes = Vec::new();
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001853 if let Some(socket) = control_tubes.get(index) {
Jakub Starond99cd0a2019-04-11 14:09:39 -07001854 match socket {
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001855 TaggedControlTube::Vm(tube) => match tube.recv::<VmRequest>() {
Jakub Starond99cd0a2019-04-11 14:09:39 -07001856 Ok(request) => {
1857 let mut run_mode_opt = None;
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001858 let response = match request {
1859 VmRequest::VfioCommand { vfio_path, add } => {
1860 handle_vfio_command(
1861 &mut linux,
1862 &mut sys_allocator,
1863 &cfg,
1864 &mut add_tubes,
Haiwei Lie2dffbf2022-02-18 14:30:56 +08001865 &iommu_host_tube,
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001866 &vfio_path,
1867 add,
1868 )
1869 }
1870 _ => request.execute(
1871 &mut run_mode_opt,
Andrew Walbran3cd93602022-01-25 13:59:23 +00001872 balloon_host_tube.as_ref(),
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001873 &mut balloon_stats_id,
1874 disk_host_tubes,
Peter Fang6ca03232021-12-20 02:17:21 -08001875 &mut linux.pm,
Xiong Zhangc78e72b2021-04-08 11:31:41 +08001876 #[cfg(feature = "usb")]
1877 Some(&usb_control_tube),
1878 #[cfg(not(feature = "usb"))]
1879 None,
1880 &mut linux.bat_control,
1881 &vcpu_handles,
1882 ),
1883 };
1884
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001885 if let Err(e) = tube.send(&response) {
Jakub Starond99cd0a2019-04-11 14:09:39 -07001886 error!("failed to send VmResponse: {}", e);
1887 }
1888 if let Some(run_mode) = run_mode_opt {
1889 info!("control socket changed run mode to {}", run_mode);
1890 match run_mode {
1891 VmRunMode::Exiting => {
Michael Hoylee392c462020-10-07 03:29:24 -07001892 break 'wait;
Jakub Starond99cd0a2019-04-11 14:09:39 -07001893 }
Keiichi Watanabec5262e92020-10-21 15:57:33 +09001894 other => {
Chuanxiao Dong2bbe85c2020-11-12 17:18:07 +08001895 if other == VmRunMode::Running {
Daniel Verkampda4e8a92021-07-21 13:49:02 -07001896 for dev in &linux.resume_notify_devices {
1897 dev.lock().resume_imminent();
1898 }
Chuanxiao Dong546f01c2020-02-12 21:58:47 +08001899 }
Anton Romanov5acc0f52022-01-28 00:18:11 +00001900 vcpu::kick_all_vcpus(
Steven Richman11dc6712020-09-02 15:39:14 -07001901 &vcpu_handles,
Zach Reiznerdc748482021-04-14 13:59:30 -07001902 linux.irq_chip.as_irq_chip(),
Daniel Verkamp29409802021-02-24 14:46:19 -08001903 VcpuControl::RunState(other),
Steven Richman11dc6712020-09-02 15:39:14 -07001904 );
Zach Reizner6a8fdd92019-01-16 14:38:41 -08001905 }
1906 }
1907 }
Zach Reizner5bed0d22018-03-28 02:31:11 -07001908 }
Jakub Starond99cd0a2019-04-11 14:09:39 -07001909 Err(e) => {
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001910 if let TubeError::Disconnected = e {
Jakub Starond99cd0a2019-04-11 14:09:39 -07001911 vm_control_indices_to_remove.push(index);
1912 } else {
1913 error!("failed to recv VmRequest: {}", e);
1914 }
Zach Reiznera60744b2019-02-13 17:33:32 -08001915 }
Jakub Starond99cd0a2019-04-11 14:09:39 -07001916 },
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001917 TaggedControlTube::VmMemory(tube) => {
1918 match tube.recv::<VmMemoryRequest>() {
1919 Ok(request) => {
1920 let response = request.execute(
1921 &mut linux.vm,
Zach Reiznerdc748482021-04-14 13:59:30 -07001922 &mut sys_allocator,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001923 Arc::clone(&map_request),
1924 &mut gralloc,
1925 );
1926 if let Err(e) = tube.send(&response) {
1927 error!("failed to send VmMemoryControlResponse: {}", e);
1928 }
1929 }
1930 Err(e) => {
1931 if let TubeError::Disconnected = e {
1932 vm_control_indices_to_remove.push(index);
1933 } else {
1934 error!("failed to recv VmMemoryControlRequest: {}", e);
1935 }
Jakub Starond99cd0a2019-04-11 14:09:39 -07001936 }
1937 }
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001938 }
1939 TaggedControlTube::VmIrq(tube) => match tube.recv::<VmIrqRequest>() {
Xiong Zhang2515b752019-09-19 10:29:02 +08001940 Ok(request) => {
Steven Richmanf32d0b42020-06-20 21:45:32 -07001941 let response = {
1942 let irq_chip = &mut linux.irq_chip;
1943 request.execute(
1944 |setup| match setup {
1945 IrqSetup::Event(irq, ev) => {
Colin Downs-Razoukbd532762020-09-08 15:49:35 -07001946 if let Some(event_index) = irq_chip
1947 .register_irq_event(irq, ev, None)?
1948 {
1949 match wait_ctx.add(
1950 ev,
1951 Token::IrqFd {
1952 index: event_index
1953 },
1954 ) {
1955 Err(e) => {
1956 warn!("failed to add IrqFd to poll context: {}", e);
1957 Err(e)
1958 },
1959 Ok(_) => {
1960 Ok(())
1961 }
1962 }
1963 } else {
1964 Ok(())
1965 }
Steven Richmanf32d0b42020-06-20 21:45:32 -07001966 }
1967 IrqSetup::Route(route) => irq_chip.route_irq(route),
Xiong Zhang4fbc5542021-06-01 11:29:14 +08001968 IrqSetup::UnRegister(irq, ev) => irq_chip.unregister_irq_event(irq, ev),
Steven Richmanf32d0b42020-06-20 21:45:32 -07001969 },
Zach Reiznerdc748482021-04-14 13:59:30 -07001970 &mut sys_allocator,
Steven Richmanf32d0b42020-06-20 21:45:32 -07001971 )
1972 };
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001973 if let Err(e) = tube.send(&response) {
Xiong Zhang2515b752019-09-19 10:29:02 +08001974 error!("failed to send VmIrqResponse: {}", e);
1975 }
1976 }
1977 Err(e) => {
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001978 if let TubeError::Disconnected = e {
Xiong Zhang2515b752019-09-19 10:29:02 +08001979 vm_control_indices_to_remove.push(index);
1980 } else {
1981 error!("failed to recv VmIrqRequest: {}", e);
1982 }
1983 }
1984 },
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001985 TaggedControlTube::VmMsync(tube) => {
1986 match tube.recv::<VmMsyncRequest>() {
1987 Ok(request) => {
1988 let response = request.execute(&mut linux.vm);
1989 if let Err(e) = tube.send(&response) {
1990 error!("failed to send VmMsyncResponse: {}", e);
1991 }
1992 }
1993 Err(e) => {
1994 if let TubeError::Disconnected = e {
1995 vm_control_indices_to_remove.push(index);
1996 } else {
1997 error!("failed to recv VmMsyncRequest: {}", e);
1998 }
Daniel Verkampe1980a92020-02-07 11:00:55 -08001999 }
2000 }
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002001 }
2002 TaggedControlTube::Fs(tube) => match tube.recv::<FsMappingRequest>() {
Keiichi Watanabeeefe7fb2020-11-17 17:58:35 +09002003 Ok(request) => {
2004 let response =
Zach Reiznerdc748482021-04-14 13:59:30 -07002005 request.execute(&mut linux.vm, &mut sys_allocator);
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002006 if let Err(e) = tube.send(&response) {
Keiichi Watanabeeefe7fb2020-11-17 17:58:35 +09002007 error!("failed to send VmResponse: {}", e);
2008 }
2009 }
2010 Err(e) => {
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002011 if let TubeError::Disconnected = e {
Keiichi Watanabeeefe7fb2020-11-17 17:58:35 +09002012 vm_control_indices_to_remove.push(index);
2013 } else {
2014 error!("failed to recv VmResponse: {}", e);
2015 }
2016 }
2017 },
Zach Reizner39aa26b2017-12-12 18:03:23 -08002018 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08002019 }
Xiong Zhangc78e72b2021-04-08 11:31:41 +08002020 if !add_tubes.is_empty() {
2021 for (idx, socket) in add_tubes.iter().enumerate() {
2022 wait_ctx
2023 .add(
2024 socket.as_ref(),
2025 Token::VmControl {
2026 index: idx + control_tubes.len(),
2027 },
2028 )
2029 .context(
2030 "failed to add hotplug vfio-pci descriptor ot wait context",
2031 )?;
2032 }
2033 control_tubes.append(&mut add_tubes);
2034 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08002035 }
Zach Reizner5bed0d22018-03-28 02:31:11 -07002036 }
2037 }
Zach Reiznera60744b2019-02-13 17:33:32 -08002038
Vikram Auradkarede68c72021-07-01 14:33:54 -07002039 // It's possible more data is readable and buffered while the socket is hungup,
2040 // so don't delete the tube from the poll context until we're sure all the
2041 // data is read.
2042 // Below case covers a condition where we have received a hungup event and the tube is not
2043 // readable.
2044 // In case of readable tube, once all data is read, any attempt to read more data on hungup
2045 // tube should fail. On such failure, we get Disconnected error and index gets added to
2046 // vm_control_indices_to_remove by the time we reach here.
2047 for event in events.iter().filter(|e| e.is_hungup && !e.is_readable) {
2048 if let Token::VmControl { index } = event.token {
2049 vm_control_indices_to_remove.push(index);
Zach Reizner39aa26b2017-12-12 18:03:23 -08002050 }
2051 }
Zach Reiznera60744b2019-02-13 17:33:32 -08002052
2053 // Sort in reverse so the highest indexes are removed first. This removal algorithm
Zide Chen89584072019-11-14 10:33:51 -08002054 // preserves correct indexes as each element is removed.
Daniel Verkamp8c2f0002020-08-31 15:13:35 -07002055 vm_control_indices_to_remove.sort_unstable_by_key(|&k| Reverse(k));
Zach Reiznera60744b2019-02-13 17:33:32 -08002056 vm_control_indices_to_remove.dedup();
2057 for index in vm_control_indices_to_remove {
Michael Hoylee392c462020-10-07 03:29:24 -07002058 // Delete the socket from the `wait_ctx` synchronously. Otherwise, the kernel will do
2059 // this automatically when the FD inserted into the `wait_ctx` is closed after this
Zide Chen89584072019-11-14 10:33:51 -08002060 // if-block, but this removal can be deferred unpredictably. In some instances where the
Michael Hoylee392c462020-10-07 03:29:24 -07002061 // system is under heavy load, we can even get events returned by `wait_ctx` for an FD
Zide Chen89584072019-11-14 10:33:51 -08002062 // that has already been closed. Because the token associated with that spurious event
2063 // now belongs to a different socket, the control loop will start to interact with
2064 // sockets that might not be ready to use. This can cause incorrect hangup detection or
2065 // blocking on a socket that will never be ready. See also: crbug.com/1019986
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002066 if let Some(socket) = control_tubes.get(index) {
Daniel Verkamp6b298582021-08-16 15:37:11 -07002067 wait_ctx
2068 .delete(socket)
2069 .context("failed to remove descriptor from wait context")?;
Zide Chen89584072019-11-14 10:33:51 -08002070 }
2071
2072 // This line implicitly drops the socket at `index` when it gets returned by
2073 // `swap_remove`. After this line, the socket at `index` is not the one from
2074 // `vm_control_indices_to_remove`. Because of this socket's change in index, we need to
Michael Hoylee392c462020-10-07 03:29:24 -07002075 // use `wait_ctx.modify` to change the associated index in its `Token::VmControl`.
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002076 control_tubes.swap_remove(index);
2077 if let Some(tube) = control_tubes.get(index) {
Michael Hoylee392c462020-10-07 03:29:24 -07002078 wait_ctx
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002079 .modify(tube, EventType::Read, Token::VmControl { index })
Daniel Verkamp6b298582021-08-16 15:37:11 -07002080 .context("failed to add descriptor to wait context")?;
Zach Reiznera60744b2019-02-13 17:33:32 -08002081 }
2082 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08002083 }
2084
Anton Romanov5acc0f52022-01-28 00:18:11 +00002085 vcpu::kick_all_vcpus(
Zach Reiznerdc748482021-04-14 13:59:30 -07002086 &vcpu_handles,
2087 linux.irq_chip.as_irq_chip(),
Daniel Verkamp29409802021-02-24 14:46:19 -08002088 VcpuControl::RunState(VmRunMode::Exiting),
Zach Reiznerdc748482021-04-14 13:59:30 -07002089 );
Steven Richman11dc6712020-09-02 15:39:14 -07002090 for (handle, _) in vcpu_handles {
2091 if let Err(e) = handle.join() {
2092 error!("failed to join vcpu thread: {:?}", e);
Zach Reizner39aa26b2017-12-12 18:03:23 -08002093 }
2094 }
2095
Daniel Verkamp94c35272019-09-12 13:31:30 -07002096 // Explicitly drop the VM structure here to allow the devices to clean up before the
2097 // control sockets are closed when this function exits.
2098 mem::drop(linux);
2099
Zach Reizner19ad1f32019-12-12 18:58:50 -08002100 stdin()
Zach Reizner39aa26b2017-12-12 18:03:23 -08002101 .set_canon_mode()
2102 .expect("failed to restore canonical mode for terminal");
2103
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08002104 Ok(exit_state)
Zach Reizner39aa26b2017-12-12 18:03:23 -08002105}
Daniel Verkamp5586ff52022-02-24 16:34:55 -08002106
2107#[cfg(test)]
2108mod tests {
2109 use super::*;
2110
2111 // Create a file-backed mapping parameters struct with the given `address` and `size` and other
2112 // parameters set to default values.
2113 fn test_file_backed_mapping(address: u64, size: u64) -> FileBackedMappingParameters {
2114 FileBackedMappingParameters {
2115 address,
2116 size,
2117 path: PathBuf::new(),
2118 offset: 0,
2119 writable: false,
2120 sync: false,
2121 }
2122 }
2123
2124 #[test]
2125 fn guest_mem_file_backed_mappings_overlap() {
2126 // Base case: no file mappings; output layout should be identical.
2127 assert_eq!(
2128 punch_holes_in_guest_mem_layout_for_mappings(
2129 vec![
2130 (GuestAddress(0), 0xD000_0000),
2131 (GuestAddress(0x1_0000_0000), 0x8_0000),
2132 ],
2133 &[]
2134 ),
2135 vec![
2136 (GuestAddress(0), 0xD000_0000),
2137 (GuestAddress(0x1_0000_0000), 0x8_0000),
2138 ]
2139 );
2140
2141 // File mapping that does not overlap guest memory.
2142 assert_eq!(
2143 punch_holes_in_guest_mem_layout_for_mappings(
2144 vec![
2145 (GuestAddress(0), 0xD000_0000),
2146 (GuestAddress(0x1_0000_0000), 0x8_0000),
2147 ],
2148 &[test_file_backed_mapping(0xD000_0000, 0x1000)]
2149 ),
2150 vec![
2151 (GuestAddress(0), 0xD000_0000),
2152 (GuestAddress(0x1_0000_0000), 0x8_0000),
2153 ]
2154 );
2155
2156 // File mapping at the start of the low address space region.
2157 assert_eq!(
2158 punch_holes_in_guest_mem_layout_for_mappings(
2159 vec![
2160 (GuestAddress(0), 0xD000_0000),
2161 (GuestAddress(0x1_0000_0000), 0x8_0000),
2162 ],
2163 &[test_file_backed_mapping(0, 0x2000)]
2164 ),
2165 vec![
2166 (GuestAddress(0x2000), 0xD000_0000 - 0x2000),
2167 (GuestAddress(0x1_0000_0000), 0x8_0000),
2168 ]
2169 );
2170
2171 // File mapping at the end of the low address space region.
2172 assert_eq!(
2173 punch_holes_in_guest_mem_layout_for_mappings(
2174 vec![
2175 (GuestAddress(0), 0xD000_0000),
2176 (GuestAddress(0x1_0000_0000), 0x8_0000),
2177 ],
2178 &[test_file_backed_mapping(0xD000_0000 - 0x2000, 0x2000)]
2179 ),
2180 vec![
2181 (GuestAddress(0), 0xD000_0000 - 0x2000),
2182 (GuestAddress(0x1_0000_0000), 0x8_0000),
2183 ]
2184 );
2185
2186 // File mapping fully contained within the middle of the low address space region.
2187 assert_eq!(
2188 punch_holes_in_guest_mem_layout_for_mappings(
2189 vec![
2190 (GuestAddress(0), 0xD000_0000),
2191 (GuestAddress(0x1_0000_0000), 0x8_0000),
2192 ],
2193 &[test_file_backed_mapping(0x1000, 0x2000)]
2194 ),
2195 vec![
2196 (GuestAddress(0), 0x1000),
2197 (GuestAddress(0x3000), 0xD000_0000 - 0x3000),
2198 (GuestAddress(0x1_0000_0000), 0x8_0000),
2199 ]
2200 );
2201
2202 // File mapping at the start of the high address space region.
2203 assert_eq!(
2204 punch_holes_in_guest_mem_layout_for_mappings(
2205 vec![
2206 (GuestAddress(0), 0xD000_0000),
2207 (GuestAddress(0x1_0000_0000), 0x8_0000),
2208 ],
2209 &[test_file_backed_mapping(0x1_0000_0000, 0x2000)]
2210 ),
2211 vec![
2212 (GuestAddress(0), 0xD000_0000),
2213 (GuestAddress(0x1_0000_2000), 0x8_0000 - 0x2000),
2214 ]
2215 );
2216
2217 // File mapping at the end of the high address space region.
2218 assert_eq!(
2219 punch_holes_in_guest_mem_layout_for_mappings(
2220 vec![
2221 (GuestAddress(0), 0xD000_0000),
2222 (GuestAddress(0x1_0000_0000), 0x8_0000),
2223 ],
2224 &[test_file_backed_mapping(0x1_0008_0000 - 0x2000, 0x2000)]
2225 ),
2226 vec![
2227 (GuestAddress(0), 0xD000_0000),
2228 (GuestAddress(0x1_0000_0000), 0x8_0000 - 0x2000),
2229 ]
2230 );
2231
2232 // File mapping fully contained within the middle of the high address space region.
2233 assert_eq!(
2234 punch_holes_in_guest_mem_layout_for_mappings(
2235 vec![
2236 (GuestAddress(0), 0xD000_0000),
2237 (GuestAddress(0x1_0000_0000), 0x8_0000),
2238 ],
2239 &[test_file_backed_mapping(0x1_0000_1000, 0x2000)]
2240 ),
2241 vec![
2242 (GuestAddress(0), 0xD000_0000),
2243 (GuestAddress(0x1_0000_0000), 0x1000),
2244 (GuestAddress(0x1_0000_3000), 0x8_0000 - 0x3000),
2245 ]
2246 );
2247
2248 // File mapping overlapping two guest memory regions.
2249 assert_eq!(
2250 punch_holes_in_guest_mem_layout_for_mappings(
2251 vec![
2252 (GuestAddress(0), 0xD000_0000),
2253 (GuestAddress(0x1_0000_0000), 0x8_0000),
2254 ],
2255 &[test_file_backed_mapping(0xA000_0000, 0x60002000)]
2256 ),
2257 vec![
2258 (GuestAddress(0), 0xA000_0000),
2259 (GuestAddress(0x1_0000_2000), 0x8_0000 - 0x2000),
2260 ]
2261 );
2262 }
2263}