blob: 4dcd72abe883293d49eb893d46566fc9516eb0ec [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
Hikaru Nishida584e52c2021-04-27 17:37:08 +09005use std::cmp::Reverse;
Chia-I Wu7f0f7c12022-01-12 10:42:18 -08006use std::collections::{BTreeMap, HashSet};
Jakub Starona3411ea2019-04-24 10:55:25 -07007use std::convert::TryFrom;
John Batesb220eac2020-09-14 17:03:02 -07008#[cfg(feature = "gpu")]
9use std::env;
Dylan Reid059a1882018-07-23 17:58:09 -070010use std::fs::{File, OpenOptions};
Federico 'Morg' Pareschia1184822021-09-09 10:52:58 +090011use std::io::stdin;
Steven Richmanf32d0b42020-06-20 21:45:32 -070012use std::iter;
Daniel Verkamp94c35272019-09-12 13:31:30 -070013use std::mem;
David Tolnay2b089fc2019-03-04 15:33:22 -080014use std::net::Ipv4Addr;
Abhishek Bhardwaj103c1b72021-11-01 15:52:23 -070015use std::os::unix::net::UnixListener;
Christian Blichmann50f95912021-11-05 16:59:39 +010016use std::os::unix::{io::FromRawFd, net::UnixStream, prelude::OpenOptionsExt};
Zach Reizner39aa26b2017-12-12 18:03:23 -080017use std::path::{Path, PathBuf};
Chirantan Ekbote448516e2018-07-24 16:07:42 -070018use std::str;
Dylan Reidb0492662019-05-17 14:50:13 -070019use std::sync::{mpsc, Arc, Barrier};
Hikaru Nishida584e52c2021-04-27 17:37:08 +090020use std::time::Duration;
Dylan Reidb0492662019-05-17 14:50:13 -070021
Zach Reizner39aa26b2017-12-12 18:03:23 -080022use std::thread;
23use std::thread::JoinHandle;
24
Daniel Verkamp6b298582021-08-16 15:37:11 -070025use libc::{self, c_int, gid_t, uid_t};
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};
Chirantan Ekbote2ee9dcd2021-05-26 18:21:44 +090030use base::net::{UnixSeqpacket, UnixSeqpacketListener, UnlinkUnixSeqpacketListener};
Zach Reiznerd49bcdb2021-01-07 08:30:28 -080031use base::*;
Keiichi Watanabe553d2192021-08-16 16:42:27 +090032use devices::serial_device::{SerialHardware, SerialParameters};
Zide Chenafdb9382021-06-17 12:04:43 -070033use devices::vfio::{VfioCommonSetup, VfioCommonTrait};
Woody Chow0b2b6062021-09-03 15:40:02 +090034#[cfg(feature = "audio_cras")]
35use devices::virtio::snd::cras_backend::Parameters as CrasSndParameters;
Abhishek Bhardwaj103c1b72021-11-01 15:52:23 -070036use devices::virtio::vhost::user::proxy::VirtioVhostUser;
Woody Chow1b16db12021-04-02 16:59:59 +090037#[cfg(feature = "audio")]
38use devices::virtio::vhost::user::vmm::Snd as VhostUserSnd;
Keiichi Watanabefb36e0c2021-08-13 18:48:31 +090039use devices::virtio::vhost::user::vmm::{
Richard5afeafa2021-07-26 19:02:09 -070040 Block as VhostUserBlock, Console as VhostUserConsole, Fs as VhostUserFs,
Chirantan Ekbote84091e52021-09-10 18:43:17 +090041 Mac80211Hwsim as VhostUserMac80211Hwsim, Net as VhostUserNet, Vsock as VhostUserVsock,
42 Wl as VhostUserWl,
Keiichi Watanabe60686582021-03-12 04:53:51 +090043};
Alexandre Courbotb42b3e52021-07-09 23:38:57 +090044#[cfg(any(feature = "video-decoder", feature = "video-encoder"))]
45use devices::virtio::VideoBackendType;
Daniel Verkampa7b6a1c2020-03-09 13:16:46 -070046use devices::virtio::{self, Console, VirtioDevice};
Chirantan Ekbote44292f52021-06-25 18:31:41 +090047#[cfg(feature = "gpu")]
48use devices::virtio::{
Chia-I Wu16fb6592021-11-10 11:45:32 -080049 gpu::{GpuRenderServerParameters, DEFAULT_DISPLAY_HEIGHT, DEFAULT_DISPLAY_WIDTH},
Chirantan Ekbote44292f52021-06-25 18:31:41 +090050 vhost::user::vmm::Gpu as VhostUserGpu,
51 EventDevice,
52};
paulhsiace17e6e2020-08-28 18:37:45 +080053#[cfg(feature = "audio")]
54use devices::Ac97Dev;
Xiong Zhang17b0daf2019-04-23 17:14:50 +080055use devices::{
Xiong Zhangf82f2dc2021-05-21 16:54:12 +080056 self, BusDeviceObj, HostHotPlugKey, HotPlugBus, IrqChip, IrqEventIndex, KvmKernelIrqChip,
57 PciAddress, PciBridge, PciDevice, PcieRootPort, StubPciDevice, VcpuRunState, VfioContainer,
58 VfioDevice, VfioPciDevice, VfioPlatformDevice, VirtioPciDevice,
Xiong Zhang17b0daf2019-04-23 17:14:50 +080059};
Daniel Verkampf1439d42021-05-21 13:55:10 -070060#[cfg(feature = "usb")]
61use devices::{HostBackendDeviceProvider, XhciController};
Steven Richmanf32d0b42020-06-20 21:45:32 -070062use hypervisor::kvm::{Kvm, KvmVcpu, KvmVm};
Andrew Walbran00f1c9f2021-12-10 17:13:08 +000063use hypervisor::{HypervisorCap, ProtectionType, Vcpu, VcpuExit, VcpuRunHandle, Vm, VmCap};
Allen Webbf3024c82020-06-19 07:19:48 -070064use minijail::{self, Minijail};
Richard5afeafa2021-07-26 19:02:09 -070065use net_util::{MacAddress, Tap};
Xiong Zhang87a3b442019-10-29 17:32:44 +080066use resources::{Alloc, MmioType, SystemAllocator};
Gurchetan Singh293913c2020-12-09 10:44:13 -080067use rutabaga_gfx::RutabagaGralloc;
Dylan Reidb0492662019-05-17 14:50:13 -070068use sync::Mutex;
Zach Reiznerd49bcdb2021-01-07 08:30:28 -080069use vm_control::*;
Sergey Senozhatskyd78d05b2021-04-13 20:59:58 +090070use vm_memory::{GuestAddress, GuestMemory, MemoryPolicy};
Zach Reizner39aa26b2017-12-12 18:03:23 -080071
Keiichi Watanabec5262e92020-10-21 15:57:33 +090072#[cfg(all(target_arch = "x86_64", feature = "gdb"))]
73use crate::gdb::{gdb_thread, GdbStub};
Keiichi Watanabef3a37f42021-01-21 15:41:11 +090074use crate::{
Tomasz Nowicki71aca792021-06-09 18:53:49 +000075 Config, DiskOption, Executable, SharedDir, SharedDirKind, TouchDeviceOption, VfioType,
Christian Blichmann50f95912021-11-05 16:59:39 +010076 VhostUserFsOption, VhostUserOption, VhostUserWlOption, VhostVsockDeviceParameter,
Keiichi Watanabef3a37f42021-01-21 15:41:11 +090077};
Daniel Verkampa7b6a1c2020-03-09 13:16:46 -070078use arch::{
Keiichi Watanabe553d2192021-08-16 16:42:27 +090079 self, LinuxArch, RunnableLinuxVm, VcpuAffinity, VirtioDeviceStub, VmComponents, VmImage,
Daniel Verkampa7b6a1c2020-03-09 13:16:46 -070080};
Sonny Raoed517d12018-02-13 22:09:43 -080081
Sonny Rao2ffa0cb2018-02-26 17:27:40 -080082#[cfg(any(target_arch = "arm", target_arch = "aarch64"))]
Steven Richmanf32d0b42020-06-20 21:45:32 -070083use {
84 aarch64::AArch64 as Arch,
Steven Richman11dc6712020-09-02 15:39:14 -070085 devices::IrqChipAArch64 as IrqChipArch,
Steven Richmanf32d0b42020-06-20 21:45:32 -070086 hypervisor::{VcpuAArch64 as VcpuArch, VmAArch64 as VmArch},
87};
Zach Reizner55a9e502018-10-03 10:22:32 -070088#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
Steven Richmanf32d0b42020-06-20 21:45:32 -070089use {
Steven Richman11dc6712020-09-02 15:39:14 -070090 devices::{IrqChipX86_64 as IrqChipArch, KvmSplitIrqChip},
91 hypervisor::{VcpuX86_64 as VcpuArch, VmX86_64 as VmArch},
Steven Richmanf32d0b42020-06-20 21:45:32 -070092 x86_64::X8664arch as Arch,
93};
Zach Reizner39aa26b2017-12-12 18:03:23 -080094
Zach Reiznerd49bcdb2021-01-07 08:30:28 -080095enum TaggedControlTube {
96 Fs(Tube),
97 Vm(Tube),
98 VmMemory(Tube),
99 VmIrq(Tube),
100 VmMsync(Tube),
Jakub Starond99cd0a2019-04-11 14:09:39 -0700101}
102
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800103impl AsRef<Tube> for TaggedControlTube {
104 fn as_ref(&self) -> &Tube {
105 use self::TaggedControlTube::*;
Jakub Starond99cd0a2019-04-11 14:09:39 -0700106 match &self {
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800107 Fs(tube) | Vm(tube) | VmMemory(tube) | VmIrq(tube) | VmMsync(tube) => tube,
Jakub Starond99cd0a2019-04-11 14:09:39 -0700108 }
109 }
110}
111
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800112impl AsRawDescriptor for TaggedControlTube {
Michael Hoylee392c462020-10-07 03:29:24 -0700113 fn as_raw_descriptor(&self) -> RawDescriptor {
Michael Hoylea596a072020-11-10 19:32:45 -0800114 self.as_ref().as_raw_descriptor()
Jakub Starond99cd0a2019-04-11 14:09:39 -0700115 }
116}
117
Matt Delcoc24ad782020-02-14 13:24:36 -0800118struct SandboxConfig<'a> {
119 limit_caps: bool,
120 log_failures: bool,
121 seccomp_policy: &'a Path,
122 uid_map: Option<&'a str>,
123 gid_map: Option<&'a str>,
124}
125
Zach Reizner44863792019-06-26 14:22:08 -0700126fn create_base_minijail(
127 root: &Path,
Matt Delcoc24ad782020-02-14 13:24:36 -0800128 r_limit: Option<u64>,
129 config: Option<&SandboxConfig>,
Zach Reizner44863792019-06-26 14:22:08 -0700130) -> Result<Minijail> {
Zach Reizner39aa26b2017-12-12 18:03:23 -0800131 // All child jails run in a new user namespace without any users mapped,
132 // they run as nobody unless otherwise configured.
Daniel Verkamp6b298582021-08-16 15:37:11 -0700133 let mut j = Minijail::new().context("failed to jail device")?;
Matt Delcoc24ad782020-02-14 13:24:36 -0800134
135 if let Some(config) = config {
136 j.namespace_pids();
137 j.namespace_user();
138 j.namespace_user_disable_setgroups();
139 if config.limit_caps {
140 // Don't need any capabilities.
141 j.use_caps(0);
142 }
143 if let Some(uid_map) = config.uid_map {
Daniel Verkamp6b298582021-08-16 15:37:11 -0700144 j.uidmap(uid_map).context("error setting UID map")?;
Matt Delcoc24ad782020-02-14 13:24:36 -0800145 }
146 if let Some(gid_map) = config.gid_map {
Daniel Verkamp6b298582021-08-16 15:37:11 -0700147 j.gidmap(gid_map).context("error setting GID map")?;
Matt Delcoc24ad782020-02-14 13:24:36 -0800148 }
Chirantan Ekbotef84c2292020-02-21 16:37:27 +0900149 // Run in a new mount namespace.
150 j.namespace_vfs();
151
Matt Delcoc24ad782020-02-14 13:24:36 -0800152 // Run in an empty network namespace.
153 j.namespace_net();
Chirantan Ekbotef84c2292020-02-21 16:37:27 +0900154
155 // Don't allow the device to gain new privileges.
Matt Delcoc24ad782020-02-14 13:24:36 -0800156 j.no_new_privs();
157
158 // By default we'll prioritize using the pre-compiled .bpf over the .policy
159 // file (the .bpf is expected to be compiled using "trap" as the failure
160 // behavior instead of the default "kill" behavior).
161 // Refer to the code comment for the "seccomp-log-failures"
162 // command-line parameter for an explanation about why the |log_failures|
163 // flag forces the use of .policy files (and the build-time alternative to
164 // this run-time flag).
165 let bpf_policy_file = config.seccomp_policy.with_extension("bpf");
166 if bpf_policy_file.exists() && !config.log_failures {
167 j.parse_seccomp_program(&bpf_policy_file)
Daniel Verkamp6b298582021-08-16 15:37:11 -0700168 .context("failed to parse precompiled seccomp policy")?;
Matt Delcoc24ad782020-02-14 13:24:36 -0800169 } else {
170 // Use TSYNC only for the side effect of it using SECCOMP_RET_TRAP,
171 // which will correctly kill the entire device process if a worker
172 // thread commits a seccomp violation.
173 j.set_seccomp_filter_tsync();
174 if config.log_failures {
175 j.log_seccomp_filter_failures();
176 }
177 j.parse_seccomp_filters(&config.seccomp_policy.with_extension("policy"))
Daniel Verkamp6b298582021-08-16 15:37:11 -0700178 .context("failed to parse seccomp policy")?;
Matt Delcoc24ad782020-02-14 13:24:36 -0800179 }
180 j.use_seccomp_filter();
181 // Don't do init setup.
182 j.run_as_init();
183 }
184
Chirantan Ekbotef84c2292020-02-21 16:37:27 +0900185 // Only pivot_root if we are not re-using the current root directory.
186 if root != Path::new("/") {
187 // It's safe to call `namespace_vfs` multiple times.
188 j.namespace_vfs();
Daniel Verkamp6b298582021-08-16 15:37:11 -0700189 j.enter_pivot_root(root)
190 .context("failed to pivot root device")?;
Chirantan Ekbotef84c2292020-02-21 16:37:27 +0900191 }
Matt Delco45caf912019-11-13 08:11:09 -0800192
Matt Delcoc24ad782020-02-14 13:24:36 -0800193 // Most devices don't need to open many fds.
194 let limit = if let Some(r) = r_limit { r } else { 1024u64 };
195 j.set_rlimit(libc::RLIMIT_NOFILE as i32, limit, limit)
Daniel Verkamp6b298582021-08-16 15:37:11 -0700196 .context("error setting max open files")?;
Matt Delcoc24ad782020-02-14 13:24:36 -0800197
Zach Reizner39aa26b2017-12-12 18:03:23 -0800198 Ok(j)
199}
200
Jianxun Zhang8f4d7682019-02-21 12:55:31 -0800201fn simple_jail(cfg: &Config, policy: &str) -> Result<Option<Minijail>> {
Lepton Wu9105e9f2019-03-14 11:38:31 -0700202 if cfg.sandbox {
Jianxun Zhang8f4d7682019-02-21 12:55:31 -0800203 let pivot_root: &str = option_env!("DEFAULT_PIVOT_ROOT").unwrap_or("/var/empty");
204 // A directory for a jailed device's pivot root.
205 let root_path = Path::new(pivot_root);
206 if !root_path.exists() {
Daniel Verkamp6b298582021-08-16 15:37:11 -0700207 bail!("{} doesn't exist, can't jail devices", pivot_root);
Jianxun Zhang8f4d7682019-02-21 12:55:31 -0800208 }
209 let policy_path: PathBuf = cfg.seccomp_policy_dir.join(policy);
Matt Delcoc24ad782020-02-14 13:24:36 -0800210 let config = SandboxConfig {
211 limit_caps: true,
212 log_failures: cfg.seccomp_log_failures,
213 seccomp_policy: &policy_path,
214 uid_map: None,
215 gid_map: None,
216 };
217 Ok(Some(create_base_minijail(root_path, None, Some(&config))?))
Jianxun Zhang8f4d7682019-02-21 12:55:31 -0800218 } else {
219 Ok(None)
220 }
221}
222
Daniel Verkamp6b298582021-08-16 15:37:11 -0700223type DeviceResult<T = VirtioDeviceStub> = Result<T>;
David Tolnay2b089fc2019-03-04 15:33:22 -0800224
Andrew Walbran4cad30a2021-06-28 15:58:08 +0000225fn create_block_device(cfg: &Config, disk: &DiskOption, disk_device_tube: Tube) -> DeviceResult {
Junichi Uekawa7bea39f2021-07-16 14:05:06 +0900226 let raw_image: File = open_file(&disk.path, disk.read_only, disk.o_direct)
Daniel Verkamp6b298582021-08-16 15:37:11 -0700227 .with_context(|| format!("failed to load disk image {}", disk.path.display()))?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800228 // Lock the disk image to prevent other crosvm instances from using it.
229 let lock_op = if disk.read_only {
230 FlockOperation::LockShared
231 } else {
232 FlockOperation::LockExclusive
233 };
Daniel Verkamp6b298582021-08-16 15:37:11 -0700234 flock(&raw_image, lock_op, true).context("failed to lock disk image")?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800235
Junichi Uekawa52437db2021-09-29 17:33:07 +0900236 info!("Trying to attach block device: {}", disk.path.display());
Daniel Verkamp6b298582021-08-16 15:37:11 -0700237 let dev = if disk::async_ok(&raw_image).context("failed to check disk async_ok")? {
238 let async_file = disk::create_async_disk_file(raw_image)
239 .context("failed to create async virtual disk")?;
Dylan Reid503c5ab2020-07-17 11:20:07 -0700240 Box::new(
241 virtio::BlockAsync::new(
242 virtio::base_features(cfg.protected_vm),
243 async_file,
244 disk.read_only,
245 disk.sparse,
246 disk.block_size,
Daniel Verkampdd0ee592021-03-29 13:05:22 -0700247 disk.id,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800248 Some(disk_device_tube),
Dylan Reid503c5ab2020-07-17 11:20:07 -0700249 )
Daniel Verkamp6b298582021-08-16 15:37:11 -0700250 .context("failed to create block device")?,
Dylan Reid503c5ab2020-07-17 11:20:07 -0700251 ) as Box<dyn VirtioDevice>
252 } else {
Daniel Verkampeb1640e2021-09-07 14:09:31 -0700253 let disk_file = disk::create_disk_file(raw_image, disk::MAX_NESTING_DEPTH)
Daniel Verkamp6b298582021-08-16 15:37:11 -0700254 .context("failed to create virtual disk")?;
Dylan Reid503c5ab2020-07-17 11:20:07 -0700255 Box::new(
256 virtio::Block::new(
257 virtio::base_features(cfg.protected_vm),
258 disk_file,
259 disk.read_only,
260 disk.sparse,
261 disk.block_size,
262 disk.id,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800263 Some(disk_device_tube),
Dylan Reid503c5ab2020-07-17 11:20:07 -0700264 )
Daniel Verkamp6b298582021-08-16 15:37:11 -0700265 .context("failed to create block device")?,
Dylan Reid503c5ab2020-07-17 11:20:07 -0700266 ) as Box<dyn VirtioDevice>
267 };
David Tolnay2b089fc2019-03-04 15:33:22 -0800268
269 Ok(VirtioDeviceStub {
Dylan Reid503c5ab2020-07-17 11:20:07 -0700270 dev,
Daniel Verkamp166d1dd2021-08-19 17:05:29 -0700271 jail: simple_jail(cfg, "block_device")?,
David Tolnay2b089fc2019-03-04 15:33:22 -0800272 })
273}
274
Keiichi Watanabef3a37f42021-01-21 15:41:11 +0900275fn create_vhost_user_block_device(cfg: &Config, opt: &VhostUserOption) -> DeviceResult {
276 let dev = VhostUserBlock::new(virtio::base_features(cfg.protected_vm), &opt.socket)
Daniel Verkamp6b298582021-08-16 15:37:11 -0700277 .context("failed to set up vhost-user block device")?;
Keiichi Watanabef3a37f42021-01-21 15:41:11 +0900278
279 Ok(VirtioDeviceStub {
280 dev: Box::new(dev),
281 // no sandbox here because virtqueue handling is exported to a different process.
282 jail: None,
283 })
284}
285
Federico 'Morg' Pareschi70fc7de2021-04-08 15:43:13 +0900286fn create_vhost_user_console_device(cfg: &Config, opt: &VhostUserOption) -> DeviceResult {
287 let dev = VhostUserConsole::new(virtio::base_features(cfg.protected_vm), &opt.socket)
Daniel Verkamp6b298582021-08-16 15:37:11 -0700288 .context("failed to set up vhost-user console device")?;
Federico 'Morg' Pareschi70fc7de2021-04-08 15:43:13 +0900289
290 Ok(VirtioDeviceStub {
291 dev: Box::new(dev),
292 // no sandbox here because virtqueue handling is exported to a different process.
293 jail: None,
294 })
295}
296
Woody Chow5890b702021-02-12 14:57:02 +0900297fn create_vhost_user_fs_device(cfg: &Config, option: &VhostUserFsOption) -> DeviceResult {
298 let dev = VhostUserFs::new(
299 virtio::base_features(cfg.protected_vm),
300 &option.socket,
301 &option.tag,
302 )
Daniel Verkamp6b298582021-08-16 15:37:11 -0700303 .context("failed to set up vhost-user fs device")?;
Woody Chow5890b702021-02-12 14:57:02 +0900304
305 Ok(VirtioDeviceStub {
306 dev: Box::new(dev),
307 // no sandbox here because virtqueue handling is exported to a different process.
308 jail: None,
309 })
310}
311
JaeMan Parkeb9cc532021-07-02 15:02:59 +0900312fn create_vhost_user_mac80211_hwsim_device(cfg: &Config, opt: &VhostUserOption) -> DeviceResult {
313 let dev = VhostUserMac80211Hwsim::new(virtio::base_features(cfg.protected_vm), &opt.socket)
Daniel Verkamp6b298582021-08-16 15:37:11 -0700314 .context("failed to set up vhost-user mac80211_hwsim device")?;
JaeMan Parkeb9cc532021-07-02 15:02:59 +0900315
316 Ok(VirtioDeviceStub {
317 dev: Box::new(dev),
318 // no sandbox here because virtqueue handling is exported to a different process.
319 jail: None,
320 })
321}
322
Woody Chow1b16db12021-04-02 16:59:59 +0900323#[cfg(feature = "audio")]
324fn create_vhost_user_snd_device(cfg: &Config, option: &VhostUserOption) -> DeviceResult {
325 let dev = VhostUserSnd::new(virtio::base_features(cfg.protected_vm), &option.socket)
Daniel Verkamp6b298582021-08-16 15:37:11 -0700326 .context("failed to set up vhost-user snd device")?;
Woody Chow1b16db12021-04-02 16:59:59 +0900327
328 Ok(VirtioDeviceStub {
329 dev: Box::new(dev),
330 // no sandbox here because virtqueue handling is exported to a different process.
331 jail: None,
332 })
333}
334
Abhishek Bhardwaj103c1b72021-11-01 15:52:23 -0700335fn create_vvu_proxy_device(cfg: &Config, opt: &VhostUserOption) -> DeviceResult {
336 let listener = UnixListener::bind(&opt.socket).map_err(|e| {
337 error!("failed to bind listener for vvu proxy device: {}", e);
338 e
339 })?;
340
341 let dev = VirtioVhostUser::new(virtio::base_features(cfg.protected_vm), listener)
342 .context("failed to create VVU proxy device")?;
343
344 Ok(VirtioDeviceStub {
345 dev: Box::new(dev),
346 jail: simple_jail(cfg, "vvu_proxy_device")?,
347 })
348}
349
David Tolnay2b089fc2019-03-04 15:33:22 -0800350fn create_rng_device(cfg: &Config) -> DeviceResult {
Daniel Verkamp6b298582021-08-16 15:37:11 -0700351 let dev = virtio::Rng::new(virtio::base_features(cfg.protected_vm))
352 .context("failed to set up rng")?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800353
354 Ok(VirtioDeviceStub {
355 dev: Box::new(dev),
Daniel Verkamp166d1dd2021-08-19 17:05:29 -0700356 jail: simple_jail(cfg, "rng_device")?,
David Tolnay2b089fc2019-03-04 15:33:22 -0800357 })
358}
359
Woody Chow737ff122021-03-22 17:49:57 +0900360#[cfg(feature = "audio_cras")]
Woody Chow0b2b6062021-09-03 15:40:02 +0900361fn create_cras_snd_device(cfg: &Config, cras_snd: CrasSndParameters) -> DeviceResult {
362 let dev = virtio::snd::cras_backend::VirtioSndCras::new(
363 virtio::base_features(cfg.protected_vm),
364 cras_snd,
365 )
Daniel Verkamp6b298582021-08-16 15:37:11 -0700366 .context("failed to create cras sound device")?;
Woody Chow737ff122021-03-22 17:49:57 +0900367
368 let jail = match simple_jail(&cfg, "cras_snd_device")? {
369 Some(mut jail) => {
370 // Create a tmpfs in the device's root directory for cras_snd_device.
371 // The size is 20*1024, or 20 KB.
372 jail.mount_with_data(
373 Path::new("none"),
374 Path::new("/"),
375 "tmpfs",
376 (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as usize,
377 "size=20480",
378 )?;
379
380 let run_cras_path = Path::new("/run/cras");
381 jail.mount_bind(run_cras_path, run_cras_path, true)?;
382
383 add_current_user_to_jail(&mut jail)?;
384
385 Some(jail)
386 }
387 None => None,
388 };
389
390 Ok(VirtioDeviceStub {
391 dev: Box::new(dev),
392 jail,
393 })
394}
395
David Tolnay2b089fc2019-03-04 15:33:22 -0800396#[cfg(feature = "tpm")]
397fn create_tpm_device(cfg: &Config) -> DeviceResult {
398 use std::ffi::CString;
399 use std::fs;
400 use std::process;
David Tolnay2b089fc2019-03-04 15:33:22 -0800401
402 let tpm_storage: PathBuf;
Daniel Verkamp166d1dd2021-08-19 17:05:29 -0700403 let mut tpm_jail = simple_jail(cfg, "tpm_device")?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800404
405 match &mut tpm_jail {
406 Some(jail) => {
407 // Create a tmpfs in the device's root directory for tpm
408 // simulator storage. The size is 20*1024, or 20 KB.
409 jail.mount_with_data(
410 Path::new("none"),
411 Path::new("/"),
412 "tmpfs",
413 (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as usize,
414 "size=20480",
415 )?;
416
Fergus Dall51200512021-08-19 12:54:26 +1000417 let crosvm_ids = add_current_user_to_jail(jail)?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800418
419 let pid = process::id();
420 let tpm_pid_dir = format!("/run/vm/tpm.{}", pid);
421 tpm_storage = Path::new(&tpm_pid_dir).to_owned();
Daniel Verkamp6b298582021-08-16 15:37:11 -0700422 fs::create_dir_all(&tpm_storage).with_context(|| {
423 format!("failed to create tpm storage dir {}", tpm_storage.display())
424 })?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800425 let tpm_pid_dir_c = CString::new(tpm_pid_dir).expect("no nul bytes");
David Tolnayfd0971d2019-03-04 17:15:57 -0800426 chown(&tpm_pid_dir_c, crosvm_ids.uid, crosvm_ids.gid)
Daniel Verkamp6b298582021-08-16 15:37:11 -0700427 .context("failed to chown tpm storage")?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800428
429 jail.mount_bind(&tpm_storage, &tpm_storage, true)?;
430 }
431 None => {
432 // Path used inside cros_sdk which does not have /run/vm.
433 tpm_storage = Path::new("/tmp/tpm-simulator").to_owned();
434 }
435 }
436
437 let dev = virtio::Tpm::new(tpm_storage);
438
439 Ok(VirtioDeviceStub {
440 dev: Box::new(dev),
441 jail: tpm_jail,
442 })
443}
444
Jorge E. Moreira6635ca42021-04-28 13:11:41 -0700445fn create_single_touch_device(
446 cfg: &Config,
447 single_touch_spec: &TouchDeviceOption,
448 idx: u32,
449) -> DeviceResult {
Kaiyi Libccb4eb2020-02-06 17:53:11 -0800450 let socket = single_touch_spec
451 .get_path()
452 .into_unix_stream()
453 .map_err(|e| {
454 error!("failed configuring virtio single touch: {:?}", e);
455 e
456 })?;
Jorge E. Moreira99d3f082019-03-07 10:59:54 -0800457
Kaiyi Libccb4eb2020-02-06 17:53:11 -0800458 let (width, height) = single_touch_spec.get_size();
Noah Goldd4ca29b2020-10-27 12:21:52 -0700459 let dev = virtio::new_single_touch(
Jorge E. Moreira6635ca42021-04-28 13:11:41 -0700460 idx,
Noah Goldd4ca29b2020-10-27 12:21:52 -0700461 socket,
462 width,
463 height,
464 virtio::base_features(cfg.protected_vm),
465 )
Daniel Verkamp6b298582021-08-16 15:37:11 -0700466 .context("failed to set up input device")?;
Jorge E. Moreira99d3f082019-03-07 10:59:54 -0800467 Ok(VirtioDeviceStub {
468 dev: Box::new(dev),
Daniel Verkamp166d1dd2021-08-19 17:05:29 -0700469 jail: simple_jail(cfg, "input_device")?,
Jorge E. Moreira99d3f082019-03-07 10:59:54 -0800470 })
471}
472
Jorge E. Moreira6635ca42021-04-28 13:11:41 -0700473fn create_multi_touch_device(
474 cfg: &Config,
475 multi_touch_spec: &TouchDeviceOption,
476 idx: u32,
477) -> DeviceResult {
Tristan Muntsinger486cffc2020-09-29 22:05:41 +0000478 let socket = multi_touch_spec
479 .get_path()
480 .into_unix_stream()
481 .map_err(|e| {
482 error!("failed configuring virtio multi touch: {:?}", e);
483 e
484 })?;
485
486 let (width, height) = multi_touch_spec.get_size();
487 let dev = virtio::new_multi_touch(
Jorge E. Moreira6635ca42021-04-28 13:11:41 -0700488 idx,
Tristan Muntsinger486cffc2020-09-29 22:05:41 +0000489 socket,
490 width,
491 height,
492 virtio::base_features(cfg.protected_vm),
493 )
Daniel Verkamp6b298582021-08-16 15:37:11 -0700494 .context("failed to set up input device")?;
Tristan Muntsinger486cffc2020-09-29 22:05:41 +0000495
496 Ok(VirtioDeviceStub {
497 dev: Box::new(dev),
Daniel Verkamp166d1dd2021-08-19 17:05:29 -0700498 jail: simple_jail(cfg, "input_device")?,
Tristan Muntsinger486cffc2020-09-29 22:05:41 +0000499 })
500}
501
Jorge E. Moreira6635ca42021-04-28 13:11:41 -0700502fn create_trackpad_device(
503 cfg: &Config,
504 trackpad_spec: &TouchDeviceOption,
505 idx: u32,
506) -> DeviceResult {
Kaiyi Libccb4eb2020-02-06 17:53:11 -0800507 let socket = trackpad_spec.get_path().into_unix_stream().map_err(|e| {
Maciek Swiechc3011222021-11-24 21:01:04 +0000508 error!("failed configuring virtio trackpad: {:#}", e);
David Tolnay2b089fc2019-03-04 15:33:22 -0800509 e
510 })?;
511
Kaiyi Libccb4eb2020-02-06 17:53:11 -0800512 let (width, height) = trackpad_spec.get_size();
Noah Goldd4ca29b2020-10-27 12:21:52 -0700513 let dev = virtio::new_trackpad(
Jorge E. Moreira6635ca42021-04-28 13:11:41 -0700514 idx,
Noah Goldd4ca29b2020-10-27 12:21:52 -0700515 socket,
516 width,
517 height,
518 virtio::base_features(cfg.protected_vm),
519 )
Daniel Verkamp6b298582021-08-16 15:37:11 -0700520 .context("failed to set up input device")?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800521
522 Ok(VirtioDeviceStub {
523 dev: Box::new(dev),
Daniel Verkamp166d1dd2021-08-19 17:05:29 -0700524 jail: simple_jail(cfg, "input_device")?,
David Tolnay2b089fc2019-03-04 15:33:22 -0800525 })
526}
527
Jorge E. Moreira6635ca42021-04-28 13:11:41 -0700528fn create_mouse_device<T: IntoUnixStream>(cfg: &Config, mouse_socket: T, idx: u32) -> DeviceResult {
Zach Reizner65b98f12019-11-22 17:34:58 -0800529 let socket = mouse_socket.into_unix_stream().map_err(|e| {
Maciek Swiechc3011222021-11-24 21:01:04 +0000530 error!("failed configuring virtio mouse: {:#}", e);
David Tolnay2b089fc2019-03-04 15:33:22 -0800531 e
532 })?;
533
Jorge E. Moreira6635ca42021-04-28 13:11:41 -0700534 let dev = virtio::new_mouse(idx, socket, virtio::base_features(cfg.protected_vm))
Daniel Verkamp6b298582021-08-16 15:37:11 -0700535 .context("failed to set up input device")?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800536
537 Ok(VirtioDeviceStub {
538 dev: Box::new(dev),
Daniel Verkamp166d1dd2021-08-19 17:05:29 -0700539 jail: simple_jail(cfg, "input_device")?,
David Tolnay2b089fc2019-03-04 15:33:22 -0800540 })
541}
542
Jorge E. Moreira6635ca42021-04-28 13:11:41 -0700543fn create_keyboard_device<T: IntoUnixStream>(
544 cfg: &Config,
545 keyboard_socket: T,
546 idx: u32,
547) -> DeviceResult {
Zach Reizner65b98f12019-11-22 17:34:58 -0800548 let socket = keyboard_socket.into_unix_stream().map_err(|e| {
Maciek Swiechc3011222021-11-24 21:01:04 +0000549 error!("failed configuring virtio keyboard: {:#}", e);
David Tolnay2b089fc2019-03-04 15:33:22 -0800550 e
551 })?;
552
Jorge E. Moreira6635ca42021-04-28 13:11:41 -0700553 let dev = virtio::new_keyboard(idx, socket, virtio::base_features(cfg.protected_vm))
Daniel Verkamp6b298582021-08-16 15:37:11 -0700554 .context("failed to set up input device")?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800555
556 Ok(VirtioDeviceStub {
557 dev: Box::new(dev),
Daniel Verkamp166d1dd2021-08-19 17:05:29 -0700558 jail: simple_jail(cfg, "input_device")?,
David Tolnay2b089fc2019-03-04 15:33:22 -0800559 })
560}
561
Jorge E. Moreira6635ca42021-04-28 13:11:41 -0700562fn create_switches_device<T: IntoUnixStream>(
563 cfg: &Config,
564 switches_socket: T,
565 idx: u32,
566) -> DeviceResult {
Daniel Norman5e23df72021-03-11 10:11:02 -0800567 let socket = switches_socket.into_unix_stream().map_err(|e| {
Maciek Swiechc3011222021-11-24 21:01:04 +0000568 error!("failed configuring virtio switches: {:#}", e);
Daniel Norman5e23df72021-03-11 10:11:02 -0800569 e
570 })?;
571
Jorge E. Moreira6635ca42021-04-28 13:11:41 -0700572 let dev = virtio::new_switches(idx, socket, virtio::base_features(cfg.protected_vm))
Daniel Verkamp6b298582021-08-16 15:37:11 -0700573 .context("failed to set up input device")?;
Daniel Norman5e23df72021-03-11 10:11:02 -0800574
575 Ok(VirtioDeviceStub {
576 dev: Box::new(dev),
Daniel Verkamp166d1dd2021-08-19 17:05:29 -0700577 jail: simple_jail(cfg, "input_device")?,
Daniel Norman5e23df72021-03-11 10:11:02 -0800578 })
579}
580
David Tolnay2b089fc2019-03-04 15:33:22 -0800581fn create_vinput_device(cfg: &Config, dev_path: &Path) -> DeviceResult {
582 let dev_file = OpenOptions::new()
583 .read(true)
584 .write(true)
585 .open(dev_path)
Daniel Verkamp6b298582021-08-16 15:37:11 -0700586 .with_context(|| format!("failed to open vinput device {}", dev_path.display()))?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800587
Noah Goldd4ca29b2020-10-27 12:21:52 -0700588 let dev = virtio::new_evdev(dev_file, virtio::base_features(cfg.protected_vm))
Daniel Verkamp6b298582021-08-16 15:37:11 -0700589 .context("failed to set up input device")?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800590
591 Ok(VirtioDeviceStub {
592 dev: Box::new(dev),
Daniel Verkamp166d1dd2021-08-19 17:05:29 -0700593 jail: simple_jail(cfg, "input_device")?,
David Tolnay2b089fc2019-03-04 15:33:22 -0800594 })
595}
596
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800597fn create_balloon_device(cfg: &Config, tube: Tube) -> DeviceResult {
598 let dev = virtio::Balloon::new(virtio::base_features(cfg.protected_vm), tube)
Daniel Verkamp6b298582021-08-16 15:37:11 -0700599 .context("failed to create balloon")?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800600
601 Ok(VirtioDeviceStub {
602 dev: Box::new(dev),
Daniel Verkamp166d1dd2021-08-19 17:05:29 -0700603 jail: simple_jail(cfg, "balloon_device")?,
David Tolnay2b089fc2019-03-04 15:33:22 -0800604 })
605}
606
Alexandre Courbot911773a2021-12-10 14:31:10 +0900607/// Generic method for creating a network device. `create_device` is a closure that takes the virtio
608/// features and number of queue pairs as parameters, and is responsible for creating the device
609/// itself.
610fn create_net_device<F, T>(cfg: &Config, policy: &str, create_device: F) -> DeviceResult
611where
612 F: Fn(u64, u16) -> Result<T>,
613 T: VirtioDevice + 'static,
614{
Xiong Zhang773c7072020-03-20 10:39:55 +0800615 let mut vq_pairs = cfg.net_vq_pairs.unwrap_or(1);
616 let vcpu_count = cfg.vcpu_count.unwrap_or(1);
Steven Richmanf32d0b42020-06-20 21:45:32 -0700617 if vcpu_count < vq_pairs as usize {
Alexandre Courbot911773a2021-12-10 14:31:10 +0900618 warn!("the number of net vq pairs must not exceed the vcpu count, falling back to single queue mode");
Xiong Zhang773c7072020-03-20 10:39:55 +0800619 vq_pairs = 1;
620 }
Will Deacon7d2b8ac2020-10-06 18:51:12 +0100621 let features = virtio::base_features(cfg.protected_vm);
Alexandre Courbot911773a2021-12-10 14:31:10 +0900622
623 let dev = create_device(features, vq_pairs)?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800624
625 Ok(VirtioDeviceStub {
Alexandre Courbot911773a2021-12-10 14:31:10 +0900626 dev: Box::new(dev) as Box<dyn VirtioDevice>,
627 jail: simple_jail(cfg, policy)?,
David Tolnay2b089fc2019-03-04 15:33:22 -0800628 })
629}
630
Alexandre Courbot911773a2021-12-10 14:31:10 +0900631/// Returns a network device created from a new TAP interface configured with `host_ip`, `netmask`,
632/// and `mac_address`.
633fn create_net_device_from_config(
David Tolnay2b089fc2019-03-04 15:33:22 -0800634 cfg: &Config,
635 host_ip: Ipv4Addr,
636 netmask: Ipv4Addr,
637 mac_address: MacAddress,
David Tolnay2b089fc2019-03-04 15:33:22 -0800638) -> DeviceResult {
David Tolnay2b089fc2019-03-04 15:33:22 -0800639 let policy = if cfg.vhost_net {
Matt Delco45caf912019-11-13 08:11:09 -0800640 "vhost_net_device"
David Tolnay2b089fc2019-03-04 15:33:22 -0800641 } else {
Matt Delco45caf912019-11-13 08:11:09 -0800642 "net_device"
David Tolnay2b089fc2019-03-04 15:33:22 -0800643 };
644
Alexandre Courbot911773a2021-12-10 14:31:10 +0900645 if cfg.vhost_net {
646 create_net_device(cfg, policy, |features, _vq_pairs| {
647 virtio::vhost::Net::<Tap, vhost::Net<Tap>>::new(
648 &cfg.vhost_net_device_path,
649 features,
650 host_ip,
651 netmask,
652 mac_address,
653 )
654 .context("failed to set up vhost networking")
655 })
656 } else {
657 create_net_device(cfg, policy, |features, vq_pairs| {
658 virtio::Net::<Tap>::new(features, host_ip, netmask, mac_address, vq_pairs)
659 .context("failed to create virtio network device")
660 })
661 }
662}
663
664/// Returns a network device from a file descriptor to a configured TAP interface.
665fn create_tap_net_device_from_fd(cfg: &Config, tap_fd: RawDescriptor) -> DeviceResult {
666 create_net_device(cfg, "net_device", |features, vq_pairs| {
667 // Safe because we ensure that we get a unique handle to the fd.
668 let tap = unsafe {
669 Tap::from_raw_descriptor(
670 validate_raw_descriptor(tap_fd).context("failed to validate tap descriptor")?,
671 )
672 .context("failed to create tap device")?
673 };
674
675 virtio::Net::from(features, tap, vq_pairs).context("failed to create tap net device")
David Tolnay2b089fc2019-03-04 15:33:22 -0800676 })
677}
678
Alexandre Courbot993aa7f2021-12-09 14:51:29 +0900679/// Returns a network device created by opening the persistent, configured TAP interface `tap_name`.
680fn create_tap_net_device_from_name(cfg: &Config, tap_name: &[u8]) -> DeviceResult {
681 create_net_device(cfg, "net_device", |features, vq_pairs| {
682 virtio::Net::<Tap>::new_from_name(features, tap_name, vq_pairs)
683 .context("failed to create configured virtio network device")
684 })
685}
686
Keiichi Watanabe60686582021-03-12 04:53:51 +0900687fn create_vhost_user_net_device(cfg: &Config, opt: &VhostUserOption) -> DeviceResult {
688 let dev = VhostUserNet::new(virtio::base_features(cfg.protected_vm), &opt.socket)
Daniel Verkamp6b298582021-08-16 15:37:11 -0700689 .context("failed to set up vhost-user net device")?;
Keiichi Watanabe60686582021-03-12 04:53:51 +0900690
691 Ok(VirtioDeviceStub {
692 dev: Box::new(dev),
693 // no sandbox here because virtqueue handling is exported to a different process.
694 jail: None,
695 })
696}
697
Chirantan Ekbote84091e52021-09-10 18:43:17 +0900698fn create_vhost_user_vsock_device(cfg: &Config, opt: &VhostUserOption) -> DeviceResult {
699 let dev = VhostUserVsock::new(virtio::base_features(cfg.protected_vm), &opt.socket)
Daniel Verkamp6b298582021-08-16 15:37:11 -0700700 .context("failed to set up vhost-user vsock device")?;
Chirantan Ekbote84091e52021-09-10 18:43:17 +0900701
702 Ok(VirtioDeviceStub {
703 dev: Box::new(dev),
704 // no sandbox here because virtqueue handling is exported to a different process.
705 jail: None,
706 })
707}
708
Chirantan Ekbote2ee9dcd2021-05-26 18:21:44 +0900709fn create_vhost_user_wl_device(cfg: &Config, opt: &VhostUserWlOption) -> DeviceResult {
710 // The crosvm wl device expects us to connect the tube before it will accept a vhost-user
711 // connection.
712 let dev = VhostUserWl::new(virtio::base_features(cfg.protected_vm), &opt.socket)
Daniel Verkamp6b298582021-08-16 15:37:11 -0700713 .context("failed to set up vhost-user wl device")?;
Chirantan Ekbote2ee9dcd2021-05-26 18:21:44 +0900714
715 Ok(VirtioDeviceStub {
716 dev: Box::new(dev),
717 // no sandbox here because virtqueue handling is exported to a different process.
718 jail: None,
719 })
720}
721
David Tolnay2b089fc2019-03-04 15:33:22 -0800722#[cfg(feature = "gpu")]
Chirantan Ekbote44292f52021-06-25 18:31:41 +0900723fn create_vhost_user_gpu_device(
724 cfg: &Config,
725 opt: &VhostUserOption,
726 host_tube: Tube,
727 device_tube: Tube,
728) -> DeviceResult {
729 // The crosvm gpu device expects us to connect the tube before it will accept a vhost-user
730 // connection.
731 let dev = VhostUserGpu::new(
732 virtio::base_features(cfg.protected_vm),
733 &opt.socket,
734 host_tube,
735 device_tube,
736 )
Daniel Verkamp6b298582021-08-16 15:37:11 -0700737 .context("failed to set up vhost-user gpu device")?;
Chirantan Ekbote44292f52021-06-25 18:31:41 +0900738
739 Ok(VirtioDeviceStub {
740 dev: Box::new(dev),
741 // no sandbox here because virtqueue handling is exported to a different process.
742 jail: None,
743 })
744}
745
Alexandre Courbot22740d82021-12-15 17:06:27 +0900746/// Mirror-mount all the directories in `dirs` into `jail` on a best-effort basis.
747///
748/// This function will not return an error if any of the directories in `dirs` is missing.
749#[cfg(any(feature = "gpu", feature = "video-decoder", feature = "video-encoder"))]
750fn jail_mount_bind_if_exists<P: AsRef<std::ffi::OsStr>>(
751 jail: &mut Minijail,
752 dirs: &[P],
753) -> Result<()> {
754 for dir in dirs {
755 let dir_path = Path::new(dir);
756 if dir_path.exists() {
757 jail.mount_bind(dir_path, dir_path, false)?;
758 }
759 }
760
761 Ok(())
762}
763
Chirantan Ekbote44292f52021-06-25 18:31:41 +0900764#[cfg(feature = "gpu")]
Chia-I Wufffb5692021-12-01 13:25:35 -0800765fn gpu_jail(cfg: &Config, policy: &str) -> Result<Option<Minijail>> {
766 match simple_jail(cfg, policy)? {
767 Some(mut jail) => {
768 // Create a tmpfs in the device's root directory so that we can bind mount the
769 // dri directory into it. The size=67108864 is size=64*1024*1024 or size=64MB.
770 jail.mount_with_data(
771 Path::new("none"),
772 Path::new("/"),
773 "tmpfs",
774 (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as usize,
775 "size=67108864",
776 )?;
777
778 // Device nodes required for DRM.
779 let sys_dev_char_path = Path::new("/sys/dev/char");
780 jail.mount_bind(sys_dev_char_path, sys_dev_char_path, false)?;
781 let sys_devices_path = Path::new("/sys/devices");
782 jail.mount_bind(sys_devices_path, sys_devices_path, false)?;
783
784 let drm_dri_path = Path::new("/dev/dri");
785 if drm_dri_path.exists() {
786 jail.mount_bind(drm_dri_path, drm_dri_path, false)?;
787 }
788
789 // If the ARM specific devices exist on the host, bind mount them in.
790 let mali0_path = Path::new("/dev/mali0");
791 if mali0_path.exists() {
792 jail.mount_bind(mali0_path, mali0_path, true)?;
793 }
794
795 let pvr_sync_path = Path::new("/dev/pvr_sync");
796 if pvr_sync_path.exists() {
797 jail.mount_bind(pvr_sync_path, pvr_sync_path, true)?;
798 }
799
800 // If the udmabuf driver exists on the host, bind mount it in.
801 let udmabuf_path = Path::new("/dev/udmabuf");
802 if udmabuf_path.exists() {
803 jail.mount_bind(udmabuf_path, udmabuf_path, true)?;
804 }
805
806 // Libraries that are required when mesa drivers are dynamically loaded.
Alexandre Courbot22740d82021-12-15 17:06:27 +0900807 jail_mount_bind_if_exists(
808 &mut jail,
809 &[
810 "/usr/lib",
811 "/usr/lib64",
812 "/lib",
813 "/lib64",
814 "/usr/share/glvnd",
815 "/usr/share/vulkan",
816 ],
817 )?;
Chia-I Wufffb5692021-12-01 13:25:35 -0800818
819 // pvr driver requires read access to /proc/self/task/*/comm.
820 let proc_path = Path::new("/proc");
821 jail.mount(
822 proc_path,
823 proc_path,
824 "proc",
825 (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC | libc::MS_RDONLY) as usize,
826 )?;
827
828 // To enable perfetto tracing, we need to give access to the perfetto service IPC
829 // endpoints.
830 let perfetto_path = Path::new("/run/perfetto");
831 if perfetto_path.exists() {
832 jail.mount_bind(perfetto_path, perfetto_path, true)?;
833 }
834
835 Ok(Some(jail))
836 }
837 None => Ok(None),
838 }
839}
840
841#[cfg(feature = "gpu")]
Chia-I Wu13ec6962022-01-12 10:42:14 -0800842struct GpuCacheInfo<'a> {
843 directory: Option<&'a str>,
844 environment: Vec<(&'a str, &'a str)>,
845}
846
847#[cfg(feature = "gpu")]
848fn get_gpu_cache_info<'a>(
849 cache_dir: Option<&'a String>,
850 cache_size: Option<&'a String>,
851 sandbox: bool,
852) -> GpuCacheInfo<'a> {
853 let mut dir = None;
854 let mut env = Vec::new();
855
856 if let Some(cache_dir) = cache_dir {
857 if !Path::new(cache_dir).exists() {
858 warn!("shader caching dir {} does not exist", cache_dir);
859 env.push(("MESA_GLSL_CACHE_DISABLE", "true"));
860 } else if cfg!(any(target_arch = "arm", target_arch = "aarch64")) && sandbox {
861 warn!("shader caching not yet supported on ARM with sandbox enabled");
862 env.push(("MESA_GLSL_CACHE_DISABLE", "true"));
863 } else {
864 dir = Some(cache_dir.as_str());
865
866 env.push(("MESA_GLSL_CACHE_DISABLE", "false"));
867 env.push(("MESA_GLSL_CACHE_DIR", cache_dir.as_str()));
868 if let Some(cache_size) = cache_size {
869 env.push(("MESA_GLSL_CACHE_MAX_SIZE", cache_size.as_str()));
870 }
871 }
872 }
873
874 GpuCacheInfo {
875 directory: dir,
876 environment: env,
877 }
878}
879
880#[cfg(feature = "gpu")]
David Tolnay2b089fc2019-03-04 15:33:22 -0800881fn create_gpu_device(
882 cfg: &Config,
Michael Hoyle685316f2020-09-16 15:29:20 -0700883 exit_evt: &Event,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800884 gpu_device_tube: Tube,
885 resource_bridges: Vec<Tube>,
Ryo Hashimoto0b788de2019-12-10 17:14:13 +0900886 wayland_socket_path: Option<&PathBuf>,
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700887 x_display: Option<String>,
Chia-I Wu16fb6592021-11-10 11:45:32 -0800888 render_server_fd: Option<SafeDescriptor>,
Zach Reizner65b98f12019-11-22 17:34:58 -0800889 event_devices: Vec<EventDevice>,
Lingfeng Yang5572c8d2020-05-05 08:40:36 -0700890 map_request: Arc<Mutex<Option<ExternalMapping>>>,
David Tolnay2b089fc2019-03-04 15:33:22 -0800891) -> DeviceResult {
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700892 let mut display_backends = vec![
893 virtio::DisplayBackend::X(x_display),
Jason Macnak60eb1fb2020-01-09 14:36:29 -0800894 virtio::DisplayBackend::Stub,
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700895 ];
896
Gurchetan Singh1bbbf1c2021-05-19 15:05:56 -0700897 let wayland_socket_dirs = cfg
898 .wayland_socket_paths
899 .iter()
900 .map(|(_name, path)| path.parent())
901 .collect::<Option<Vec<_>>>()
Daniel Verkamp6b298582021-08-16 15:37:11 -0700902 .ok_or_else(|| anyhow!("wayland socket path has no parent or file name"))?;
Gurchetan Singh1bbbf1c2021-05-19 15:05:56 -0700903
Ryo Hashimoto0b788de2019-12-10 17:14:13 +0900904 if let Some(socket_path) = wayland_socket_path {
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700905 display_backends.insert(
906 0,
Gurchetan Singh1bbbf1c2021-05-19 15:05:56 -0700907 virtio::DisplayBackend::Wayland(Some(socket_path.to_owned())),
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700908 );
909 }
910
David Tolnay2b089fc2019-03-04 15:33:22 -0800911 let dev = virtio::Gpu::new(
Daniel Verkamp6b298582021-08-16 15:37:11 -0700912 exit_evt.try_clone().context("failed to clone event")?,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800913 Some(gpu_device_tube),
Zach Reiznerd49bcdb2021-01-07 08:30:28 -0800914 resource_bridges,
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700915 display_backends,
Jason Macnakcc7070b2019-11-06 14:48:12 -0800916 cfg.gpu_parameters.as_ref().unwrap(),
Chia-I Wu16fb6592021-11-10 11:45:32 -0800917 render_server_fd,
Zach Reizner65b98f12019-11-22 17:34:58 -0800918 event_devices,
Lingfeng Yang5572c8d2020-05-05 08:40:36 -0700919 map_request,
920 cfg.sandbox,
Will Deacon7d2b8ac2020-10-06 18:51:12 +0100921 virtio::base_features(cfg.protected_vm),
Gurchetan Singh781d9752021-02-15 17:45:22 -0800922 cfg.wayland_socket_paths.clone(),
David Tolnay2b089fc2019-03-04 15:33:22 -0800923 );
924
Chia-I Wufffb5692021-12-01 13:25:35 -0800925 let jail = match gpu_jail(cfg, "gpu_device")? {
David Tolnay2b089fc2019-03-04 15:33:22 -0800926 Some(mut jail) => {
John Batesb220eac2020-09-14 17:03:02 -0700927 // Prepare GPU shader disk cache directory.
Chia-I Wu13ec6962022-01-12 10:42:14 -0800928 let (cache_dir, cache_size) = cfg
John Batesb220eac2020-09-14 17:03:02 -0700929 .gpu_parameters
930 .as_ref()
Chia-I Wu13ec6962022-01-12 10:42:14 -0800931 .map(|params| (params.cache_path.as_ref(), params.cache_size.as_ref()))
932 .unwrap();
933 let cache_info = get_gpu_cache_info(cache_dir, cache_size, cfg.sandbox);
934
935 if let Some(dir) = cache_info.directory {
936 jail.mount_bind(dir, dir, true)?;
937 }
938 for (key, val) in cache_info.environment {
939 env::set_var(key, val);
John Batesb220eac2020-09-14 17:03:02 -0700940 }
941
Gurchetan Singh1bbbf1c2021-05-19 15:05:56 -0700942 // Bind mount the wayland socket's directory into jail's root. This is necessary since
943 // each new wayland context must open() the socket. If the wayland socket is ever
944 // destroyed and remade in the same host directory, new connections will be possible
945 // without restarting the wayland device.
946 for dir in &wayland_socket_dirs {
947 jail.mount_bind(dir, dir, true)?;
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700948 }
David Tolnay2b089fc2019-03-04 15:33:22 -0800949
Fergus Dall51200512021-08-19 12:54:26 +1000950 add_current_user_to_jail(&mut jail)?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800951
952 Some(jail)
953 }
954 None => None,
955 };
956
957 Ok(VirtioDeviceStub {
958 dev: Box::new(dev),
959 jail,
960 })
961}
962
Chia-I Wu16fb6592021-11-10 11:45:32 -0800963#[cfg(feature = "gpu")]
Chia-I Wu7f0f7c12022-01-12 10:42:18 -0800964fn get_gpu_render_server_environment(cache_info: &GpuCacheInfo) -> Result<Vec<String>> {
965 let mut env = Vec::new();
966
967 let mut cache_env_keys = HashSet::with_capacity(cache_info.environment.len());
968 for (key, val) in cache_info.environment.iter() {
969 env.push(format!("{}={}", key, val));
970 cache_env_keys.insert(*key);
971 }
972
973 for (key_os, val_os) in env::vars_os() {
974 // minijail should accept OsStr rather than str...
975 let into_string_err = |_| anyhow!("invalid environment key/val");
976 let key = key_os.into_string().map_err(into_string_err)?;
977 let val = val_os.into_string().map_err(into_string_err)?;
978
979 if !cache_env_keys.contains(key.as_str()) {
980 env.push(format!("{}={}", key, val));
981 }
982 }
983
984 Ok(env)
985}
986
987#[cfg(feature = "gpu")]
Chia-I Wu16fb6592021-11-10 11:45:32 -0800988fn start_gpu_render_server(
989 cfg: &Config,
990 render_server_parameters: &GpuRenderServerParameters,
991) -> Result<SafeDescriptor> {
992 let (server_socket, client_socket) =
993 UnixSeqpacket::pair().context("failed to create render server socket")?;
994
Chia-I Wu7f0f7c12022-01-12 10:42:18 -0800995 let mut env = None;
Chia-I Wu16fb6592021-11-10 11:45:32 -0800996 let jail = match gpu_jail(cfg, "gpu_render_server")? {
997 Some(mut jail) => {
Chia-I Wu7f0f7c12022-01-12 10:42:18 -0800998 let cache_info = get_gpu_cache_info(
999 render_server_parameters.cache_path.as_ref(),
1000 render_server_parameters.cache_size.as_ref(),
1001 cfg.sandbox,
1002 );
1003
1004 if let Some(dir) = cache_info.directory {
1005 jail.mount_bind(dir, dir, true)?;
1006 }
1007
1008 if !cache_info.environment.is_empty() {
1009 env = Some(get_gpu_render_server_environment(&cache_info)?);
1010 }
Chia-I Wu16fb6592021-11-10 11:45:32 -08001011
Chia-I Wub86f7f62021-12-13 12:10:22 -08001012 // bind mount /dev/log for syslog
1013 let log_path = Path::new("/dev/log");
1014 if log_path.exists() {
1015 jail.mount_bind(log_path, log_path, true)?;
1016 }
1017
Chia-I Wu16fb6592021-11-10 11:45:32 -08001018 // Run as root in the jail to keep capabilities after execve, which is needed for
1019 // mounting to work. All capabilities will be dropped afterwards.
1020 add_current_user_as_root_to_jail(&mut jail)?;
1021
1022 jail
1023 }
1024 None => Minijail::new().context("failed to create jail")?,
1025 };
1026
1027 let inheritable_fds = [
1028 server_socket.as_raw_descriptor(),
1029 libc::STDOUT_FILENO,
1030 libc::STDERR_FILENO,
1031 ];
1032
1033 let cmd = &render_server_parameters.path;
1034 let cmd_str = cmd
1035 .to_str()
1036 .ok_or_else(|| anyhow!("invalid render server path"))?;
1037 let fd_str = server_socket.as_raw_descriptor().to_string();
1038 let args = [cmd_str, "--socket-fd", &fd_str];
1039
Chia-I Wu7f0f7c12022-01-12 10:42:18 -08001040 let mut envp: Option<Vec<&str>> = None;
1041 if let Some(ref env) = env {
1042 envp = Some(env.iter().map(AsRef::as_ref).collect());
1043 }
1044
1045 jail.run_command(minijail::Command::new_for_path(
1046 cmd,
1047 &inheritable_fds,
1048 &args,
1049 envp.as_deref(),
1050 )?)
1051 .context("failed to start gpu render server")?;
Chia-I Wu16fb6592021-11-10 11:45:32 -08001052
1053 Ok(SafeDescriptor::from(client_socket))
1054}
1055
David Tolnay2b089fc2019-03-04 15:33:22 -08001056fn create_wayland_device(
1057 cfg: &Config,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001058 control_tube: Tube,
1059 resource_bridge: Option<Tube>,
David Tolnay2b089fc2019-03-04 15:33:22 -08001060) -> DeviceResult {
Ryo Hashimoto0b788de2019-12-10 17:14:13 +09001061 let wayland_socket_dirs = cfg
1062 .wayland_socket_paths
1063 .iter()
1064 .map(|(_name, path)| path.parent())
1065 .collect::<Option<Vec<_>>>()
Daniel Verkamp6b298582021-08-16 15:37:11 -07001066 .ok_or_else(|| anyhow!("wayland socket path has no parent or file name"))?;
David Tolnay2b089fc2019-03-04 15:33:22 -08001067
Will Deacon7d2b8ac2020-10-06 18:51:12 +01001068 let features = virtio::base_features(cfg.protected_vm);
Will Deacon81d5adb2020-10-06 18:37:48 +01001069 let dev = virtio::Wl::new(
1070 features,
1071 cfg.wayland_socket_paths.clone(),
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001072 control_tube,
Will Deacon81d5adb2020-10-06 18:37:48 +01001073 resource_bridge,
1074 )
Daniel Verkamp6b298582021-08-16 15:37:11 -07001075 .context("failed to create wayland device")?;
David Tolnay2b089fc2019-03-04 15:33:22 -08001076
Daniel Verkamp166d1dd2021-08-19 17:05:29 -07001077 let jail = match simple_jail(cfg, "wl_device")? {
David Tolnay2b089fc2019-03-04 15:33:22 -08001078 Some(mut jail) => {
1079 // Create a tmpfs in the device's root directory so that we can bind mount the wayland
1080 // socket directory into it. The size=67108864 is size=64*1024*1024 or size=64MB.
1081 jail.mount_with_data(
1082 Path::new("none"),
1083 Path::new("/"),
1084 "tmpfs",
1085 (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as usize,
1086 "size=67108864",
David Tolnayfd0971d2019-03-04 17:15:57 -08001087 )?;
David Tolnay2b089fc2019-03-04 15:33:22 -08001088
1089 // Bind mount the wayland socket's directory into jail's root. This is necessary since
1090 // each new wayland context must open() the socket. If the wayland socket is ever
1091 // destroyed and remade in the same host directory, new connections will be possible
1092 // without restarting the wayland device.
Ryo Hashimoto0b788de2019-12-10 17:14:13 +09001093 for dir in &wayland_socket_dirs {
1094 jail.mount_bind(dir, dir, true)?;
1095 }
Fergus Dall51200512021-08-19 12:54:26 +10001096 add_current_user_to_jail(&mut jail)?;
David Tolnay2b089fc2019-03-04 15:33:22 -08001097
1098 Some(jail)
1099 }
1100 None => None,
1101 };
1102
1103 Ok(VirtioDeviceStub {
1104 dev: Box::new(dev),
1105 jail,
1106 })
1107}
1108
Keiichi Watanabe57df6a02019-12-06 22:24:40 +09001109#[cfg(any(feature = "video-decoder", feature = "video-encoder"))]
1110fn create_video_device(
Alexandre Courbotb42b3e52021-07-09 23:38:57 +09001111 backend: VideoBackendType,
Keiichi Watanabe57df6a02019-12-06 22:24:40 +09001112 cfg: &Config,
1113 typ: devices::virtio::VideoDeviceType,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001114 resource_bridge: Tube,
Keiichi Watanabe57df6a02019-12-06 22:24:40 +09001115) -> DeviceResult {
Daniel Verkamp166d1dd2021-08-19 17:05:29 -07001116 let jail = match simple_jail(cfg, "video_device")? {
Keiichi Watanabe57df6a02019-12-06 22:24:40 +09001117 Some(mut jail) => {
1118 match typ {
Alexandre Courbot8230abf2021-06-26 22:49:26 +09001119 #[cfg(feature = "video-decoder")]
Fergus Dall51200512021-08-19 12:54:26 +10001120 devices::virtio::VideoDeviceType::Decoder => add_current_user_to_jail(&mut jail)?,
Alexandre Courbot8230abf2021-06-26 22:49:26 +09001121 #[cfg(feature = "video-encoder")]
Fergus Dall51200512021-08-19 12:54:26 +10001122 devices::virtio::VideoDeviceType::Encoder => add_current_user_to_jail(&mut jail)?,
Keiichi Watanabe57df6a02019-12-06 22:24:40 +09001123 };
1124
1125 // Create a tmpfs in the device's root directory so that we can bind mount files.
1126 jail.mount_with_data(
1127 Path::new("none"),
1128 Path::new("/"),
1129 "tmpfs",
1130 (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as usize,
1131 "size=67108864",
1132 )?;
1133
Alexandre Courbotc02960d2021-07-11 23:06:30 +09001134 #[cfg(feature = "libvda")]
Keiichi Watanabe57df6a02019-12-06 22:24:40 +09001135 // Render node for libvda.
Alexandre Courbot54cf8342021-12-20 18:10:08 +09001136 if backend == VideoBackendType::Libvda || backend == VideoBackendType::LibvdaVd {
Chih-Yu Huangd2c2bd12021-12-06 14:09:59 +09001137 // follow the implementation at:
1138 // https://source.corp.google.com/chromeos_public/src/platform/minigbm/cros_gralloc/cros_gralloc_driver.cc;l=90;bpv=0;cl=c06cc9cccb3cf3c7f9d2aec706c27c34cd6162a0
1139 const DRM_NUM_NODES: u32 = 63;
1140 const DRM_RENDER_NODE_START: u32 = 128;
1141 for offset in 0..DRM_NUM_NODES {
1142 let path_str = format!("/dev/dri/renderD{}", DRM_RENDER_NODE_START + offset);
1143 let dev_dri_path = Path::new(&path_str);
1144 if !dev_dri_path.exists() {
1145 break;
1146 }
1147 jail.mount_bind(dev_dri_path, dev_dri_path, false)?;
1148 }
Alexandre Courbotb42b3e52021-07-09 23:38:57 +09001149 }
Keiichi Watanabe57df6a02019-12-06 22:24:40 +09001150
David Stevense341d0a2020-10-08 18:02:32 +09001151 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1152 {
1153 // Device nodes used by libdrm through minigbm in libvda on AMD devices.
1154 let sys_dev_char_path = Path::new("/sys/dev/char");
1155 jail.mount_bind(sys_dev_char_path, sys_dev_char_path, false)?;
1156 let sys_devices_path = Path::new("/sys/devices");
1157 jail.mount_bind(sys_devices_path, sys_devices_path, false)?;
1158
1159 // Required for loading dri libraries loaded by minigbm on AMD devices.
Alexandre Courbot22740d82021-12-15 17:06:27 +09001160 jail_mount_bind_if_exists(&mut jail, &["/usr/lib64"])?;
David Stevense341d0a2020-10-08 18:02:32 +09001161 }
1162
Keiichi Watanabe57df6a02019-12-06 22:24:40 +09001163 // Device nodes required by libchrome which establishes Mojo connection in libvda.
1164 let dev_urandom_path = Path::new("/dev/urandom");
1165 jail.mount_bind(dev_urandom_path, dev_urandom_path, false)?;
1166 let system_bus_socket_path = Path::new("/run/dbus/system_bus_socket");
1167 jail.mount_bind(system_bus_socket_path, system_bus_socket_path, true)?;
1168
1169 Some(jail)
1170 }
1171 None => None,
1172 };
1173
1174 Ok(VirtioDeviceStub {
1175 dev: Box::new(devices::virtio::VideoDevice::new(
Will Deacon7d2b8ac2020-10-06 18:51:12 +01001176 virtio::base_features(cfg.protected_vm),
Keiichi Watanabe57df6a02019-12-06 22:24:40 +09001177 typ,
Alexandre Courbotb42b3e52021-07-09 23:38:57 +09001178 backend,
Keiichi Watanabe57df6a02019-12-06 22:24:40 +09001179 Some(resource_bridge),
1180 )),
1181 jail,
1182 })
1183}
1184
1185#[cfg(any(feature = "video-decoder", feature = "video-encoder"))]
1186fn register_video_device(
Alexandre Courbotb42b3e52021-07-09 23:38:57 +09001187 backend: VideoBackendType,
Keiichi Watanabe57df6a02019-12-06 22:24:40 +09001188 devs: &mut Vec<VirtioDeviceStub>,
Daniel Verkampffb59122021-03-18 14:06:15 -07001189 video_tube: Tube,
Keiichi Watanabe57df6a02019-12-06 22:24:40 +09001190 cfg: &Config,
1191 typ: devices::virtio::VideoDeviceType,
Daniel Verkamp6b298582021-08-16 15:37:11 -07001192) -> Result<()> {
Alexandre Courbotb42b3e52021-07-09 23:38:57 +09001193 devs.push(create_video_device(backend, cfg, typ, video_tube)?);
Keiichi Watanabe57df6a02019-12-06 22:24:40 +09001194 Ok(())
1195}
1196
Chirantan Ekbote3e8d52b2021-09-10 18:27:16 +09001197fn create_vhost_vsock_device(cfg: &Config, cid: u64) -> DeviceResult {
Will Deacon7d2b8ac2020-10-06 18:51:12 +01001198 let features = virtio::base_features(cfg.protected_vm);
Christian Blichmann50f95912021-11-05 16:59:39 +01001199
1200 let device_file = match cfg
1201 .vhost_vsock_device
1202 .as_ref()
1203 .unwrap_or(&VhostVsockDeviceParameter::default())
1204 {
1205 VhostVsockDeviceParameter::Fd(fd) => {
1206 let fd = validate_raw_descriptor(*fd)
1207 .context("failed to validate fd for virtual socker device")?;
1208 // Safe because the `fd` is actually owned by this process and
1209 // we have a unique handle to it.
1210 unsafe { File::from_raw_fd(fd) }
1211 }
1212 VhostVsockDeviceParameter::Path(path) => OpenOptions::new()
1213 .read(true)
1214 .write(true)
1215 .custom_flags(libc::O_CLOEXEC | libc::O_NONBLOCK)
1216 .open(path)
1217 .context("failed to open virtual socket device")?,
1218 };
1219
1220 let dev = virtio::vhost::Vsock::new(device_file, features, cid)
Daniel Verkamp6b298582021-08-16 15:37:11 -07001221 .context("failed to set up virtual socket device")?;
David Tolnay2b089fc2019-03-04 15:33:22 -08001222
1223 Ok(VirtioDeviceStub {
1224 dev: Box::new(dev),
Daniel Verkamp166d1dd2021-08-19 17:05:29 -07001225 jail: simple_jail(cfg, "vhost_vsock_device")?,
David Tolnay2b089fc2019-03-04 15:33:22 -08001226 })
1227}
1228
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +09001229fn create_fs_device(
1230 cfg: &Config,
1231 uid_map: &str,
1232 gid_map: &str,
1233 src: &Path,
1234 tag: &str,
1235 fs_cfg: virtio::fs::passthrough::Config,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001236 device_tube: Tube,
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +09001237) -> DeviceResult {
Daniel Verkamp6b298582021-08-16 15:37:11 -07001238 let max_open_files =
1239 base::get_max_open_files().context("failed to get max number of open files")?;
Matt Delcoc24ad782020-02-14 13:24:36 -08001240 let j = if cfg.sandbox {
1241 let seccomp_policy = cfg.seccomp_policy_dir.join("fs_device");
1242 let config = SandboxConfig {
1243 limit_caps: false,
1244 uid_map: Some(uid_map),
1245 gid_map: Some(gid_map),
1246 log_failures: cfg.seccomp_log_failures,
1247 seccomp_policy: &seccomp_policy,
1248 };
Chirantan Ekbote34d45e52020-04-20 18:15:02 +09001249 let mut jail = create_base_minijail(src, Some(max_open_files), Some(&config))?;
1250 // We want bind mounts from the parent namespaces to propagate into the fs device's
1251 // namespace.
1252 jail.set_remount_mode(libc::MS_SLAVE);
1253
1254 jail
Matt Delcoc24ad782020-02-14 13:24:36 -08001255 } else {
1256 create_base_minijail(src, Some(max_open_files), None)?
1257 };
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +09001258
Will Deacon7d2b8ac2020-10-06 18:51:12 +01001259 let features = virtio::base_features(cfg.protected_vm);
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +09001260 // TODO(chirantan): Use more than one worker once the kernel driver has been fixed to not panic
1261 // when num_queues > 1.
Daniel Verkamp6b298582021-08-16 15:37:11 -07001262 let dev = virtio::fs::Fs::new(features, tag, 1, fs_cfg, device_tube)
1263 .context("failed to create fs device")?;
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +09001264
1265 Ok(VirtioDeviceStub {
1266 dev: Box::new(dev),
1267 jail: Some(j),
1268 })
1269}
1270
Chirantan Ekbotec6b73e32020-02-20 15:53:06 +09001271fn create_9p_device(
1272 cfg: &Config,
1273 uid_map: &str,
1274 gid_map: &str,
1275 src: &Path,
1276 tag: &str,
Chirantan Ekbote75ba8752020-10-27 18:33:02 +09001277 mut p9_cfg: p9::Config,
Chirantan Ekbotec6b73e32020-02-20 15:53:06 +09001278) -> DeviceResult {
Daniel Verkamp6b298582021-08-16 15:37:11 -07001279 let max_open_files =
1280 base::get_max_open_files().context("failed to get max number of open files")?;
Chirantan Ekbotec6b73e32020-02-20 15:53:06 +09001281 let (jail, root) = if cfg.sandbox {
1282 let seccomp_policy = cfg.seccomp_policy_dir.join("9p_device");
1283 let config = SandboxConfig {
1284 limit_caps: false,
1285 uid_map: Some(uid_map),
1286 gid_map: Some(gid_map),
1287 log_failures: cfg.seccomp_log_failures,
1288 seccomp_policy: &seccomp_policy,
1289 };
David Tolnay2b089fc2019-03-04 15:33:22 -08001290
Chirantan Ekbotec6b73e32020-02-20 15:53:06 +09001291 let mut jail = create_base_minijail(src, Some(max_open_files), Some(&config))?;
1292 // We want bind mounts from the parent namespaces to propagate into the 9p server's
1293 // namespace.
1294 jail.set_remount_mode(libc::MS_SLAVE);
Chirantan Ekbote055de382020-01-24 12:16:58 +09001295
Chirantan Ekbotec6b73e32020-02-20 15:53:06 +09001296 // The shared directory becomes the root of the device's file system.
1297 let root = Path::new("/");
1298 (Some(jail), root)
1299 } else {
1300 // There's no mount namespace so we tell the server to treat the source directory as the
1301 // root.
1302 (None, src)
David Tolnay2b089fc2019-03-04 15:33:22 -08001303 };
1304
Will Deacon7d2b8ac2020-10-06 18:51:12 +01001305 let features = virtio::base_features(cfg.protected_vm);
Chirantan Ekbote75ba8752020-10-27 18:33:02 +09001306 p9_cfg.root = root.into();
Daniel Verkamp6b298582021-08-16 15:37:11 -07001307 let dev = virtio::P9::new(features, tag, p9_cfg).context("failed to create 9p device")?;
David Tolnay2b089fc2019-03-04 15:33:22 -08001308
1309 Ok(VirtioDeviceStub {
1310 dev: Box::new(dev),
1311 jail,
1312 })
1313}
1314
Jakub Starona3411ea2019-04-24 10:55:25 -07001315fn create_pmem_device(
1316 cfg: &Config,
Steven Richmanf32d0b42020-06-20 21:45:32 -07001317 vm: &mut impl Vm,
Jakub Starona3411ea2019-04-24 10:55:25 -07001318 resources: &mut SystemAllocator,
1319 disk: &DiskOption,
1320 index: usize,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001321 pmem_device_tube: Tube,
Jakub Starona3411ea2019-04-24 10:55:25 -07001322) -> DeviceResult {
Junichi Uekawa7bea39f2021-07-16 14:05:06 +09001323 let fd = open_file(&disk.path, disk.read_only, false /*O_DIRECT*/)
Daniel Verkamp6b298582021-08-16 15:37:11 -07001324 .with_context(|| format!("failed to load disk image {}", disk.path.display()))?;
Daniel Verkamp3eeaf6a2021-08-30 15:29:44 -07001325
1326 let (disk_size, arena_size) = {
Daniel Verkamp6b298582021-08-16 15:37:11 -07001327 let metadata = std::fs::metadata(&disk.path).with_context(|| {
1328 format!("failed to get disk image {} metadata", disk.path.display())
1329 })?;
Stephen Barberdc7c07b2019-12-20 12:43:35 -08001330 let disk_len = metadata.len();
1331 // Linux requires pmem region sizes to be 2 MiB aligned. Linux will fill any partial page
1332 // at the end of an mmap'd file and won't write back beyond the actual file length, but if
1333 // we just align the size of the file to 2 MiB then access beyond the last page of the
1334 // mapped file will generate SIGBUS. So use a memory mapping arena that will provide
1335 // padding up to 2 MiB.
1336 let alignment = 2 * 1024 * 1024;
1337 let align_adjust = if disk_len % alignment != 0 {
1338 alignment - (disk_len % alignment)
1339 } else {
1340 0
1341 };
Daniel Verkamp3eeaf6a2021-08-30 15:29:44 -07001342 (
1343 disk_len,
1344 disk_len
1345 .checked_add(align_adjust)
Daniel Verkamp6b298582021-08-16 15:37:11 -07001346 .ok_or_else(|| anyhow!("pmem device image too big"))?,
Daniel Verkamp3eeaf6a2021-08-30 15:29:44 -07001347 )
Jakub Starona3411ea2019-04-24 10:55:25 -07001348 };
1349
1350 let protection = {
1351 if disk.read_only {
1352 Protection::read()
1353 } else {
1354 Protection::read_write()
1355 }
1356 };
1357
Stephen Barberdc7c07b2019-12-20 12:43:35 -08001358 let arena = {
Jakub Starona3411ea2019-04-24 10:55:25 -07001359 // Conversion from u64 to usize may fail on 32bit system.
Daniel Verkamp6b298582021-08-16 15:37:11 -07001360 let arena_size = usize::try_from(arena_size).context("pmem device image too big")?;
1361 let disk_size = usize::try_from(disk_size).context("pmem device image too big")?;
Jakub Starona3411ea2019-04-24 10:55:25 -07001362
Daniel Verkamp6b298582021-08-16 15:37:11 -07001363 let mut arena =
1364 MemoryMappingArena::new(arena_size).context("failed to reserve pmem memory")?;
Stephen Barberdc7c07b2019-12-20 12:43:35 -08001365 arena
Daniel Verkamp3eeaf6a2021-08-30 15:29:44 -07001366 .add_fd_offset_protection(0, disk_size, &fd, 0, protection)
Daniel Verkamp6b298582021-08-16 15:37:11 -07001367 .context("failed to reserve pmem memory")?;
Daniel Verkamp3eeaf6a2021-08-30 15:29:44 -07001368
1369 // If the disk is not a multiple of the page size, the OS will fill the remaining part
1370 // of the page with zeroes. However, the anonymous mapping added below must start on a
1371 // page boundary, so round up the size before calculating the offset of the anon region.
1372 let disk_size = round_up_to_page_size(disk_size);
1373
1374 if arena_size > disk_size {
1375 // Add an anonymous region with the same protection as the disk mapping if the arena
1376 // size was aligned.
1377 arena
1378 .add_anon_protection(disk_size, arena_size - disk_size, protection)
Daniel Verkamp6b298582021-08-16 15:37:11 -07001379 .context("failed to reserve pmem padding")?;
Daniel Verkamp3eeaf6a2021-08-30 15:29:44 -07001380 }
Stephen Barberdc7c07b2019-12-20 12:43:35 -08001381 arena
Jakub Starona3411ea2019-04-24 10:55:25 -07001382 };
1383
1384 let mapping_address = resources
Xiong Zhang383b3b52019-10-30 14:59:26 +08001385 .mmio_allocator(MmioType::High)
Daniel Verkamp57e4f542021-10-28 09:56:40 -07001386 .reverse_allocate_with_align(
Stephen Barberdc7c07b2019-12-20 12:43:35 -08001387 arena_size,
Jakub Starona3411ea2019-04-24 10:55:25 -07001388 Alloc::PmemDevice(index),
1389 format!("pmem_disk_image_{}", index),
1390 // Linux kernel requires pmem namespaces to be 128 MiB aligned.
1391 128 * 1024 * 1024, /* 128 MiB */
1392 )
Daniel Verkamp6b298582021-08-16 15:37:11 -07001393 .context("failed to allocate memory for pmem device")?;
Jakub Starona3411ea2019-04-24 10:55:25 -07001394
Daniel Verkampe1980a92020-02-07 11:00:55 -08001395 let slot = vm
Gurchetan Singh173fe622020-05-21 18:05:06 -07001396 .add_memory_region(
Daniel Verkampe1980a92020-02-07 11:00:55 -08001397 GuestAddress(mapping_address),
Gurchetan Singh173fe622020-05-21 18:05:06 -07001398 Box::new(arena),
Daniel Verkampe1980a92020-02-07 11:00:55 -08001399 /* read_only = */ disk.read_only,
1400 /* log_dirty_pages = */ false,
1401 )
Daniel Verkamp6b298582021-08-16 15:37:11 -07001402 .context("failed to add pmem device memory")?;
Jakub Starona3411ea2019-04-24 10:55:25 -07001403
Daniel Verkampe1980a92020-02-07 11:00:55 -08001404 let dev = virtio::Pmem::new(
Will Deacon7d2b8ac2020-10-06 18:51:12 +01001405 virtio::base_features(cfg.protected_vm),
Daniel Verkampe1980a92020-02-07 11:00:55 -08001406 fd,
1407 GuestAddress(mapping_address),
1408 slot,
1409 arena_size,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001410 Some(pmem_device_tube),
Daniel Verkampe1980a92020-02-07 11:00:55 -08001411 )
Daniel Verkamp6b298582021-08-16 15:37:11 -07001412 .context("failed to create pmem device")?;
Jakub Starona3411ea2019-04-24 10:55:25 -07001413
1414 Ok(VirtioDeviceStub {
1415 dev: Box::new(dev) as Box<dyn VirtioDevice>,
Daniel Verkamp166d1dd2021-08-19 17:05:29 -07001416 jail: simple_jail(cfg, "pmem_device")?,
Jakub Starona3411ea2019-04-24 10:55:25 -07001417 })
1418}
1419
Zide Chendfc4b882021-03-10 16:35:37 -08001420fn create_iommu_device(
1421 cfg: &Config,
Zide Chen71435c12021-03-03 15:02:02 -08001422 phys_max_addr: u64,
Zide Chendfc4b882021-03-10 16:35:37 -08001423 endpoints: BTreeMap<u32, Arc<Mutex<VfioContainer>>>,
1424) -> DeviceResult {
Zide Chen71435c12021-03-03 15:02:02 -08001425 let dev = virtio::Iommu::new(
1426 virtio::base_features(cfg.protected_vm),
1427 endpoints,
1428 phys_max_addr,
1429 )
Daniel Verkamp6b298582021-08-16 15:37:11 -07001430 .context("failed to create IOMMU device")?;
Zide Chendfc4b882021-03-10 16:35:37 -08001431
1432 Ok(VirtioDeviceStub {
1433 dev: Box::new(dev),
Daniel Verkamp166d1dd2021-08-19 17:05:29 -07001434 jail: simple_jail(cfg, "iommu_device")?,
Zide Chendfc4b882021-03-10 16:35:37 -08001435 })
1436}
1437
Daniel Verkampa7b6a1c2020-03-09 13:16:46 -07001438fn create_console_device(cfg: &Config, param: &SerialParameters) -> DeviceResult {
Michael Hoylecd23bc22020-10-20 22:12:20 -07001439 let mut keep_rds = Vec::new();
Daniel Verkamp6b298582021-08-16 15:37:11 -07001440 let evt = Event::new().context("failed to create event")?;
Daniel Verkampa7b6a1c2020-03-09 13:16:46 -07001441 let dev = param
Michael Hoylecd23bc22020-10-20 22:12:20 -07001442 .create_serial_device::<Console>(cfg.protected_vm, &evt, &mut keep_rds)
Daniel Verkamp6b298582021-08-16 15:37:11 -07001443 .context("failed to create console device")?;
Daniel Verkampa7b6a1c2020-03-09 13:16:46 -07001444
Daniel Verkamp166d1dd2021-08-19 17:05:29 -07001445 let jail = match simple_jail(cfg, "serial")? {
Nicholas Verne71e73d82020-07-08 17:19:55 +10001446 Some(mut jail) => {
1447 // Create a tmpfs in the device's root directory so that we can bind mount the
1448 // log socket directory into it.
1449 // The size=67108864 is size=64*1024*1024 or size=64MB.
1450 jail.mount_with_data(
1451 Path::new("none"),
1452 Path::new("/"),
1453 "tmpfs",
1454 (libc::MS_NODEV | libc::MS_NOEXEC | libc::MS_NOSUID) as usize,
1455 "size=67108864",
1456 )?;
Fergus Dall51200512021-08-19 12:54:26 +10001457 add_current_user_to_jail(&mut jail)?;
Nicholas Verne71e73d82020-07-08 17:19:55 +10001458 let res = param.add_bind_mounts(&mut jail);
1459 if res.is_err() {
1460 error!("failed to add bind mounts for console device");
1461 }
1462 Some(jail)
1463 }
1464 None => None,
1465 };
1466
Daniel Verkampa7b6a1c2020-03-09 13:16:46 -07001467 Ok(VirtioDeviceStub {
1468 dev: Box::new(dev),
Nicholas Verne71e73d82020-07-08 17:19:55 +10001469 jail, // TODO(dverkamp): use a separate policy for console?
Daniel Verkampa7b6a1c2020-03-09 13:16:46 -07001470 })
1471}
1472
Jorge E. Moreirad4562d02021-06-28 16:21:12 -07001473#[cfg(feature = "audio")]
1474fn create_sound_device(path: &Path, cfg: &Config) -> DeviceResult {
1475 let dev = virtio::new_sound(path, virtio::base_features(cfg.protected_vm))
Daniel Verkamp6b298582021-08-16 15:37:11 -07001476 .context("failed to create sound device")?;
Jorge E. Moreirad4562d02021-06-28 16:21:12 -07001477
1478 Ok(VirtioDeviceStub {
1479 dev: Box::new(dev),
Daniel Verkamp166d1dd2021-08-19 17:05:29 -07001480 jail: simple_jail(cfg, "vios_audio_device")?,
Jorge E. Moreirad4562d02021-06-28 16:21:12 -07001481 })
1482}
1483
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001484// gpu_device_tube is not used when GPU support is disabled.
Dmitry Torokhovee42b8c2019-05-27 11:14:20 -07001485#[cfg_attr(not(feature = "gpu"), allow(unused_variables))]
David Tolnay2b089fc2019-03-04 15:33:22 -08001486fn create_virtio_devices(
1487 cfg: &Config,
Steven Richmanf32d0b42020-06-20 21:45:32 -07001488 vm: &mut impl Vm,
Jakub Starona3411ea2019-04-24 10:55:25 -07001489 resources: &mut SystemAllocator,
Michael Hoyle685316f2020-09-16 15:29:20 -07001490 _exit_evt: &Event,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001491 wayland_device_tube: Tube,
1492 gpu_device_tube: Tube,
Chirantan Ekbote44292f52021-06-25 18:31:41 +09001493 vhost_user_gpu_tubes: Vec<(Tube, Tube)>,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001494 balloon_device_tube: Tube,
1495 disk_device_tubes: &mut Vec<Tube>,
1496 pmem_device_tubes: &mut Vec<Tube>,
Lingfeng Yangd6ac1ab2020-01-31 13:55:35 -08001497 map_request: Arc<Mutex<Option<ExternalMapping>>>,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001498 fs_device_tubes: &mut Vec<Tube>,
David Tolnay2b089fc2019-03-04 15:33:22 -08001499) -> DeviceResult<Vec<VirtioDeviceStub>> {
Dylan Reid059a1882018-07-23 17:58:09 -07001500 let mut devs = Vec::new();
Zach Reizner39aa26b2017-12-12 18:03:23 -08001501
Daniel Verkampa7b6a1c2020-03-09 13:16:46 -07001502 for (_, param) in cfg
1503 .serial_parameters
1504 .iter()
1505 .filter(|(_k, v)| v.hardware == SerialHardware::VirtioConsole)
1506 {
1507 let dev = create_console_device(cfg, param)?;
1508 devs.push(dev);
1509 }
1510
Zach Reizner8fb52112017-12-13 16:04:39 -08001511 for disk in &cfg.disks {
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001512 let disk_device_tube = disk_device_tubes.remove(0);
1513 devs.push(create_block_device(cfg, disk, disk_device_tube)?);
Zach Reizner39aa26b2017-12-12 18:03:23 -08001514 }
1515
Keiichi Watanabef3a37f42021-01-21 15:41:11 +09001516 for blk in &cfg.vhost_user_blk {
1517 devs.push(create_vhost_user_block_device(cfg, blk)?);
1518 }
1519
Federico 'Morg' Pareschi70fc7de2021-04-08 15:43:13 +09001520 for console in &cfg.vhost_user_console {
1521 devs.push(create_vhost_user_console_device(cfg, console)?);
1522 }
1523
Jakub Starona3411ea2019-04-24 10:55:25 -07001524 for (index, pmem_disk) in cfg.pmem_devices.iter().enumerate() {
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001525 let pmem_device_tube = pmem_device_tubes.remove(0);
Daniel Verkampe1980a92020-02-07 11:00:55 -08001526 devs.push(create_pmem_device(
1527 cfg,
1528 vm,
1529 resources,
1530 pmem_disk,
1531 index,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001532 pmem_device_tube,
Daniel Verkampe1980a92020-02-07 11:00:55 -08001533 )?);
Jakub Starona3411ea2019-04-24 10:55:25 -07001534 }
1535
David Tolnay2b089fc2019-03-04 15:33:22 -08001536 devs.push(create_rng_device(cfg)?);
Zach Reizner39aa26b2017-12-12 18:03:23 -08001537
David Tolnayde6b29a2018-12-20 11:49:46 -08001538 #[cfg(feature = "tpm")]
1539 {
David Tolnay43f8e212019-02-13 17:28:16 -08001540 if cfg.software_tpm {
David Tolnay2b089fc2019-03-04 15:33:22 -08001541 devs.push(create_tpm_device(cfg)?);
David Tolnay43f8e212019-02-13 17:28:16 -08001542 }
David Tolnayde6b29a2018-12-20 11:49:46 -08001543 }
1544
Jorge E. Moreira6635ca42021-04-28 13:11:41 -07001545 for (idx, single_touch_spec) in cfg.virtio_single_touch.iter().enumerate() {
1546 devs.push(create_single_touch_device(
1547 cfg,
1548 single_touch_spec,
1549 idx as u32,
1550 )?);
Jorge E. Moreira99d3f082019-03-07 10:59:54 -08001551 }
1552
Jorge E. Moreira6635ca42021-04-28 13:11:41 -07001553 for (idx, multi_touch_spec) in cfg.virtio_multi_touch.iter().enumerate() {
1554 devs.push(create_multi_touch_device(
1555 cfg,
1556 multi_touch_spec,
1557 idx as u32,
1558 )?);
Tristan Muntsinger486cffc2020-09-29 22:05:41 +00001559 }
1560
Jorge E. Moreira6635ca42021-04-28 13:11:41 -07001561 for (idx, trackpad_spec) in cfg.virtio_trackpad.iter().enumerate() {
1562 devs.push(create_trackpad_device(cfg, trackpad_spec, idx as u32)?);
Jorge E. Moreiradffec502019-01-14 18:44:49 -08001563 }
1564
Jorge E. Moreira6635ca42021-04-28 13:11:41 -07001565 for (idx, mouse_socket) in cfg.virtio_mice.iter().enumerate() {
1566 devs.push(create_mouse_device(cfg, mouse_socket, idx as u32)?);
Jorge E. Moreiradffec502019-01-14 18:44:49 -08001567 }
1568
Jorge E. Moreira6635ca42021-04-28 13:11:41 -07001569 for (idx, keyboard_socket) in cfg.virtio_keyboard.iter().enumerate() {
1570 devs.push(create_keyboard_device(cfg, keyboard_socket, idx as u32)?);
Jorge E. Moreiradffec502019-01-14 18:44:49 -08001571 }
1572
Jorge E. Moreira6635ca42021-04-28 13:11:41 -07001573 for (idx, switches_socket) in cfg.virtio_switches.iter().enumerate() {
1574 devs.push(create_switches_device(cfg, switches_socket, idx as u32)?);
Daniel Norman5e23df72021-03-11 10:11:02 -08001575 }
1576
Jianxun Zhang8f4d7682019-02-21 12:55:31 -08001577 for dev_path in &cfg.virtio_input_evdevs {
Daniel Verkamp166d1dd2021-08-19 17:05:29 -07001578 devs.push(create_vinput_device(cfg, dev_path)?);
Jorge E. Moreiradffec502019-01-14 18:44:49 -08001579 }
1580
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001581 devs.push(create_balloon_device(cfg, balloon_device_tube)?);
Dylan Reid295ccac2017-11-06 14:06:24 -08001582
Zach Reizner39aa26b2017-12-12 18:03:23 -08001583 // We checked above that if the IP is defined, then the netmask is, too.
Jianxun Zhang8f4d7682019-02-21 12:55:31 -08001584 for tap_fd in &cfg.tap_fd {
Alexandre Courbot911773a2021-12-10 14:31:10 +09001585 devs.push(create_tap_net_device_from_fd(cfg, *tap_fd)?);
Jorge E. Moreirab7952802019-02-12 16:43:05 -08001586 }
1587
David Tolnay2b089fc2019-03-04 15:33:22 -08001588 if let (Some(host_ip), Some(netmask), Some(mac_address)) =
1589 (cfg.host_ip, cfg.netmask, cfg.mac_address)
1590 {
Keiichi Watanabe60686582021-03-12 04:53:51 +09001591 if !cfg.vhost_user_net.is_empty() {
Daniel Verkamp6b298582021-08-16 15:37:11 -07001592 bail!("vhost-user-net cannot be used with any of --host_ip, --netmask or --mac");
Keiichi Watanabe60686582021-03-12 04:53:51 +09001593 }
Alexandre Courbot911773a2021-12-10 14:31:10 +09001594 devs.push(create_net_device_from_config(
1595 cfg,
1596 host_ip,
1597 netmask,
1598 mac_address,
1599 )?);
Zach Reizner39aa26b2017-12-12 18:03:23 -08001600 }
1601
Alexandre Courbot993aa7f2021-12-09 14:51:29 +09001602 for tap_name in &cfg.tap_name {
1603 devs.push(create_tap_net_device_from_name(cfg, tap_name.as_bytes())?);
1604 }
1605
Keiichi Watanabe60686582021-03-12 04:53:51 +09001606 for net in &cfg.vhost_user_net {
1607 devs.push(create_vhost_user_net_device(cfg, net)?);
1608 }
1609
Chirantan Ekbote84091e52021-09-10 18:43:17 +09001610 for vsock in &cfg.vhost_user_vsock {
1611 devs.push(create_vhost_user_vsock_device(cfg, vsock)?);
1612 }
1613
Chirantan Ekbote2ee9dcd2021-05-26 18:21:44 +09001614 for opt in &cfg.vhost_user_wl {
1615 devs.push(create_vhost_user_wl_device(cfg, opt)?);
1616 }
1617
Chirantan Ekbote44292f52021-06-25 18:31:41 +09001618 #[cfg(feature = "gpu")]
1619 for (opt, (host_tube, device_tube)) in cfg.vhost_user_gpu.iter().zip(vhost_user_gpu_tubes) {
1620 devs.push(create_vhost_user_gpu_device(
1621 cfg,
1622 opt,
1623 host_tube,
1624 device_tube,
1625 )?);
1626 }
1627
Abhishek Bhardwaj103c1b72021-11-01 15:52:23 -07001628 for opt in &cfg.vvu_proxy {
1629 devs.push(create_vvu_proxy_device(cfg, opt)?);
1630 }
1631
David Tolnayfa701712019-02-13 16:42:54 -08001632 #[cfg_attr(not(feature = "gpu"), allow(unused_mut))]
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001633 let mut resource_bridges = Vec::<Tube>::new();
Chirantan Ekbotedd11d432019-06-11 21:50:46 +09001634
Ryo Hashimoto0b788de2019-12-10 17:14:13 +09001635 if !cfg.wayland_socket_paths.is_empty() {
Chirantan Ekbotedd11d432019-06-11 21:50:46 +09001636 #[cfg_attr(not(feature = "gpu"), allow(unused_mut))]
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001637 let mut wl_resource_bridge = None::<Tube>;
Chirantan Ekbotedd11d432019-06-11 21:50:46 +09001638
1639 #[cfg(feature = "gpu")]
1640 {
Jason Macnakcc7070b2019-11-06 14:48:12 -08001641 if cfg.gpu_parameters.is_some() {
Daniel Verkamp6b298582021-08-16 15:37:11 -07001642 let (wl_socket, gpu_socket) = Tube::pair().context("failed to create tube")?;
Chirantan Ekbotedd11d432019-06-11 21:50:46 +09001643 resource_bridges.push(gpu_socket);
1644 wl_resource_bridge = Some(wl_socket);
1645 }
1646 }
1647
1648 devs.push(create_wayland_device(
1649 cfg,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001650 wayland_device_tube,
Chirantan Ekbotedd11d432019-06-11 21:50:46 +09001651 wl_resource_bridge,
1652 )?);
1653 }
David Tolnayfa701712019-02-13 16:42:54 -08001654
Keiichi Watanabe57df6a02019-12-06 22:24:40 +09001655 #[cfg(feature = "video-decoder")]
Alexandre Courbotb42b3e52021-07-09 23:38:57 +09001656 let video_dec_cfg = if let Some(backend) = cfg.video_dec {
Daniel Verkamp6b298582021-08-16 15:37:11 -07001657 let (video_tube, gpu_tube) = Tube::pair().context("failed to create tube")?;
Daniel Verkampffb59122021-03-18 14:06:15 -07001658 resource_bridges.push(gpu_tube);
Alexandre Courbotb42b3e52021-07-09 23:38:57 +09001659 Some((video_tube, backend))
Daniel Verkampffb59122021-03-18 14:06:15 -07001660 } else {
1661 None
1662 };
Keiichi Watanabe57df6a02019-12-06 22:24:40 +09001663
1664 #[cfg(feature = "video-encoder")]
Alexandre Courbotb42b3e52021-07-09 23:38:57 +09001665 let video_enc_cfg = if let Some(backend) = cfg.video_enc {
Daniel Verkamp6b298582021-08-16 15:37:11 -07001666 let (video_tube, gpu_tube) = Tube::pair().context("failed to create tube")?;
Daniel Verkampffb59122021-03-18 14:06:15 -07001667 resource_bridges.push(gpu_tube);
Alexandre Courbotb42b3e52021-07-09 23:38:57 +09001668 Some((video_tube, backend))
Daniel Verkampffb59122021-03-18 14:06:15 -07001669 } else {
1670 None
1671 };
Keiichi Watanabe57df6a02019-12-06 22:24:40 +09001672
Zach Reizner3a8100a2017-09-13 19:15:43 -07001673 #[cfg(feature = "gpu")]
1674 {
Noah Golddc7f52b2020-02-01 13:01:58 -08001675 if let Some(gpu_parameters) = &cfg.gpu_parameters {
Jason Macnakd659a0d2021-03-15 15:33:01 -07001676 let mut gpu_display_w = DEFAULT_DISPLAY_WIDTH;
1677 let mut gpu_display_h = DEFAULT_DISPLAY_HEIGHT;
1678 if !gpu_parameters.displays.is_empty() {
1679 gpu_display_w = gpu_parameters.displays[0].width;
1680 gpu_display_h = gpu_parameters.displays[0].height;
1681 }
1682
Zach Reizner65b98f12019-11-22 17:34:58 -08001683 let mut event_devices = Vec::new();
1684 if cfg.display_window_mouse {
1685 let (event_device_socket, virtio_dev_socket) =
Daniel Verkamp6b298582021-08-16 15:37:11 -07001686 UnixStream::pair().context("failed to create socket")?;
Tristan Muntsinger486cffc2020-09-29 22:05:41 +00001687 let (multi_touch_width, multi_touch_height) = cfg
1688 .virtio_multi_touch
Jorge E. Moreira6635ca42021-04-28 13:11:41 -07001689 .first()
Kaiyi Libccb4eb2020-02-06 17:53:11 -08001690 .as_ref()
Tristan Muntsinger486cffc2020-09-29 22:05:41 +00001691 .map(|multi_touch_spec| multi_touch_spec.get_size())
Jason Macnakd659a0d2021-03-15 15:33:01 -07001692 .unwrap_or((gpu_display_w, gpu_display_h));
Tristan Muntsinger486cffc2020-09-29 22:05:41 +00001693 let dev = virtio::new_multi_touch(
Jorge E. Moreira6635ca42021-04-28 13:11:41 -07001694 // u32::MAX is the least likely to collide with the indices generated above for
1695 // the multi_touch options, which begin at 0.
1696 u32::MAX,
Kaiyi Libccb4eb2020-02-06 17:53:11 -08001697 virtio_dev_socket,
Tristan Muntsinger486cffc2020-09-29 22:05:41 +00001698 multi_touch_width,
1699 multi_touch_height,
Noah Goldd4ca29b2020-10-27 12:21:52 -07001700 virtio::base_features(cfg.protected_vm),
Kaiyi Libccb4eb2020-02-06 17:53:11 -08001701 )
Daniel Verkamp6b298582021-08-16 15:37:11 -07001702 .context("failed to set up mouse device")?;
Zach Reizner65b98f12019-11-22 17:34:58 -08001703 devs.push(VirtioDeviceStub {
1704 dev: Box::new(dev),
Daniel Verkamp166d1dd2021-08-19 17:05:29 -07001705 jail: simple_jail(cfg, "input_device")?,
Zach Reizner65b98f12019-11-22 17:34:58 -08001706 });
1707 event_devices.push(EventDevice::touchscreen(event_device_socket));
1708 }
1709 if cfg.display_window_keyboard {
1710 let (event_device_socket, virtio_dev_socket) =
Daniel Verkamp6b298582021-08-16 15:37:11 -07001711 UnixStream::pair().context("failed to create socket")?;
Noah Goldd4ca29b2020-10-27 12:21:52 -07001712 let dev = virtio::new_keyboard(
Jorge E. Moreira6635ca42021-04-28 13:11:41 -07001713 // u32::MAX is the least likely to collide with the indices generated above for
1714 // the multi_touch options, which begin at 0.
1715 u32::MAX,
Noah Goldd4ca29b2020-10-27 12:21:52 -07001716 virtio_dev_socket,
1717 virtio::base_features(cfg.protected_vm),
1718 )
Daniel Verkamp6b298582021-08-16 15:37:11 -07001719 .context("failed to set up keyboard device")?;
Zach Reizner65b98f12019-11-22 17:34:58 -08001720 devs.push(VirtioDeviceStub {
1721 dev: Box::new(dev),
Daniel Verkamp166d1dd2021-08-19 17:05:29 -07001722 jail: simple_jail(cfg, "input_device")?,
Zach Reizner65b98f12019-11-22 17:34:58 -08001723 });
1724 event_devices.push(EventDevice::keyboard(event_device_socket));
1725 }
Chia-I Wu16fb6592021-11-10 11:45:32 -08001726
1727 let mut render_server_fd = None;
1728 if let Some(ref render_server_parameters) = gpu_parameters.render_server {
1729 render_server_fd = Some(start_gpu_render_server(cfg, render_server_parameters)?);
1730 }
1731
Zach Reizner0f2cfb02019-06-19 17:46:03 -07001732 devs.push(create_gpu_device(
1733 cfg,
1734 _exit_evt,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001735 gpu_device_tube,
Zach Reizner0f2cfb02019-06-19 17:46:03 -07001736 resource_bridges,
Ryo Hashimoto0b788de2019-12-10 17:14:13 +09001737 // Use the unnamed socket for GPU display screens.
1738 cfg.wayland_socket_paths.get(""),
Zach Reizner0f2cfb02019-06-19 17:46:03 -07001739 cfg.x_display.clone(),
Chia-I Wu16fb6592021-11-10 11:45:32 -08001740 render_server_fd,
Zach Reizner65b98f12019-11-22 17:34:58 -08001741 event_devices,
Lingfeng Yangd6ac1ab2020-01-31 13:55:35 -08001742 map_request,
Zach Reizner0f2cfb02019-06-19 17:46:03 -07001743 )?);
Zach Reizner3a8100a2017-09-13 19:15:43 -07001744 }
1745 }
1746
Chih-Yang Hsiae31731c2022-01-05 17:30:28 +08001747 #[cfg(feature = "audio_cras")]
1748 {
1749 for cras_snd in &cfg.cras_snds {
1750 devs.push(create_cras_snd_device(cfg, cras_snd.clone())?);
1751 }
1752 }
1753
Daniel Verkampffb59122021-03-18 14:06:15 -07001754 #[cfg(feature = "video-decoder")]
1755 {
Alexandre Courbotb42b3e52021-07-09 23:38:57 +09001756 if let Some((video_dec_tube, video_dec_backend)) = video_dec_cfg {
Daniel Verkampffb59122021-03-18 14:06:15 -07001757 register_video_device(
Alexandre Courbotb42b3e52021-07-09 23:38:57 +09001758 video_dec_backend,
Daniel Verkampffb59122021-03-18 14:06:15 -07001759 &mut devs,
1760 video_dec_tube,
1761 cfg,
1762 devices::virtio::VideoDeviceType::Decoder,
1763 )?;
1764 }
1765 }
1766
1767 #[cfg(feature = "video-encoder")]
1768 {
Alexandre Courbotb42b3e52021-07-09 23:38:57 +09001769 if let Some((video_enc_tube, video_enc_backend)) = video_enc_cfg {
Daniel Verkampffb59122021-03-18 14:06:15 -07001770 register_video_device(
Alexandre Courbotb42b3e52021-07-09 23:38:57 +09001771 video_enc_backend,
Daniel Verkampffb59122021-03-18 14:06:15 -07001772 &mut devs,
1773 video_enc_tube,
1774 cfg,
1775 devices::virtio::VideoDeviceType::Encoder,
1776 )?;
1777 }
1778 }
1779
Zach Reizneraa575662018-08-15 10:46:32 -07001780 if let Some(cid) = cfg.cid {
Chirantan Ekbote3e8d52b2021-09-10 18:27:16 +09001781 devs.push(create_vhost_vsock_device(cfg, cid)?);
Zach Reizneraa575662018-08-15 10:46:32 -07001782 }
1783
Woody Chow5890b702021-02-12 14:57:02 +09001784 for vhost_user_fs in &cfg.vhost_user_fs {
Daniel Verkamp166d1dd2021-08-19 17:05:29 -07001785 devs.push(create_vhost_user_fs_device(cfg, vhost_user_fs)?);
Woody Chow5890b702021-02-12 14:57:02 +09001786 }
1787
Woody Chow1b16db12021-04-02 16:59:59 +09001788 #[cfg(feature = "audio")]
1789 for vhost_user_snd in &cfg.vhost_user_snd {
1790 devs.push(create_vhost_user_snd_device(cfg, vhost_user_snd)?);
1791 }
1792
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +09001793 for shared_dir in &cfg.shared_dirs {
1794 let SharedDir {
1795 src,
1796 tag,
1797 kind,
1798 uid_map,
1799 gid_map,
Chirantan Ekbote75ba8752020-10-27 18:33:02 +09001800 fs_cfg,
1801 p9_cfg,
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +09001802 } = shared_dir;
David Tolnay2b089fc2019-03-04 15:33:22 -08001803
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +09001804 let dev = match kind {
Keiichi Watanabeeefe7fb2020-11-17 17:58:35 +09001805 SharedDirKind::FS => {
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001806 let device_tube = fs_device_tubes.remove(0);
1807 create_fs_device(cfg, uid_map, gid_map, src, tag, fs_cfg.clone(), device_tube)?
Keiichi Watanabeeefe7fb2020-11-17 17:58:35 +09001808 }
Chirantan Ekbote75ba8752020-10-27 18:33:02 +09001809 SharedDirKind::P9 => create_9p_device(cfg, uid_map, gid_map, src, tag, p9_cfg.clone())?,
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +09001810 };
1811 devs.push(dev);
David Tolnay2b089fc2019-03-04 15:33:22 -08001812 }
1813
JaeMan Parkeb9cc532021-07-02 15:02:59 +09001814 if let Some(vhost_user_mac80211_hwsim) = &cfg.vhost_user_mac80211_hwsim {
1815 devs.push(create_vhost_user_mac80211_hwsim_device(
1816 cfg,
Daniel Verkamp166d1dd2021-08-19 17:05:29 -07001817 vhost_user_mac80211_hwsim,
JaeMan Parkeb9cc532021-07-02 15:02:59 +09001818 )?);
1819 }
1820
Jorge E. Moreirad4562d02021-06-28 16:21:12 -07001821 #[cfg(feature = "audio")]
1822 if let Some(path) = &cfg.sound {
Daniel Verkamp166d1dd2021-08-19 17:05:29 -07001823 devs.push(create_sound_device(path, cfg)?);
Jorge E. Moreirad4562d02021-06-28 16:21:12 -07001824 }
1825
David Tolnay2b089fc2019-03-04 15:33:22 -08001826 Ok(devs)
1827}
1828
Xiong Zhang10f15052021-04-08 17:23:33 +08001829fn create_vfio_device(
1830 cfg: &Config,
1831 vm: &impl Vm,
1832 resources: &mut SystemAllocator,
1833 control_tubes: &mut Vec<TaggedControlTube>,
1834 vfio_path: &Path,
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08001835 bus_num: Option<u8>,
Zide Chendfc4b882021-03-10 16:35:37 -08001836 endpoints: &mut BTreeMap<u32, Arc<Mutex<VfioContainer>>>,
1837 iommu_enabled: bool,
Xiong Zhang10f15052021-04-08 17:23:33 +08001838) -> DeviceResult<(Box<VfioPciDevice>, Option<Minijail>)> {
Zide Chendfc4b882021-03-10 16:35:37 -08001839 let vfio_container = VfioCommonSetup::vfio_get_container(vfio_path, iommu_enabled)
Daniel Verkamp6b298582021-08-16 15:37:11 -07001840 .context("failed to get vfio container")?;
Xiong Zhang10f15052021-04-08 17:23:33 +08001841
1842 // create MSI, MSI-X, and Mem request sockets for each vfio device
Daniel Verkamp6b298582021-08-16 15:37:11 -07001843 let (vfio_host_tube_msi, vfio_device_tube_msi) =
1844 Tube::pair().context("failed to create tube")?;
Xiong Zhang10f15052021-04-08 17:23:33 +08001845 control_tubes.push(TaggedControlTube::VmIrq(vfio_host_tube_msi));
1846
Daniel Verkamp6b298582021-08-16 15:37:11 -07001847 let (vfio_host_tube_msix, vfio_device_tube_msix) =
1848 Tube::pair().context("failed to create tube")?;
Xiong Zhang10f15052021-04-08 17:23:33 +08001849 control_tubes.push(TaggedControlTube::VmIrq(vfio_host_tube_msix));
1850
Daniel Verkamp6b298582021-08-16 15:37:11 -07001851 let (vfio_host_tube_mem, vfio_device_tube_mem) =
1852 Tube::pair().context("failed to create tube")?;
Xiong Zhang10f15052021-04-08 17:23:33 +08001853 control_tubes.push(TaggedControlTube::VmMemory(vfio_host_tube_mem));
1854
Xiong Zhange2ff2c42021-06-02 16:49:50 +08001855 let hotplug = bus_num.is_some();
1856
Keiichi Watanabe7b805542021-09-03 02:13:51 +09001857 let vfio_device =
1858 VfioDevice::new_passthrough(&vfio_path, vm, vfio_container.clone(), iommu_enabled)
1859 .context("failed to create vfio device")?;
Xiong Zhang10f15052021-04-08 17:23:33 +08001860 let mut vfio_pci_device = Box::new(VfioPciDevice::new(
1861 vfio_device,
Xiong Zhange19ab752021-05-20 18:18:46 +08001862 bus_num,
Xiong Zhang10f15052021-04-08 17:23:33 +08001863 vfio_device_tube_msi,
1864 vfio_device_tube_msix,
1865 vfio_device_tube_mem,
1866 ));
1867 // early reservation for pass-through PCI devices.
Zide Chendfc4b882021-03-10 16:35:37 -08001868 let endpoint_addr = vfio_pci_device.allocate_address(resources);
1869 if endpoint_addr.is_err() {
Xiong Zhang10f15052021-04-08 17:23:33 +08001870 warn!(
1871 "address reservation failed for vfio {}",
1872 vfio_pci_device.debug_label()
1873 );
1874 }
1875
Zide Chendfc4b882021-03-10 16:35:37 -08001876 if iommu_enabled {
1877 endpoints.insert(endpoint_addr.unwrap().to_u32(), vfio_container);
1878 }
1879
Xiong Zhange2ff2c42021-06-02 16:49:50 +08001880 if hotplug {
1881 Ok((vfio_pci_device, None))
1882 } else {
1883 Ok((vfio_pci_device, simple_jail(cfg, "vfio_device")?))
1884 }
Xiong Zhang10f15052021-04-08 17:23:33 +08001885}
1886
Tomasz Nowicki344eb142021-09-22 05:51:58 +00001887fn create_vfio_platform_device(
1888 cfg: &Config,
1889 vm: &impl Vm,
1890 _resources: &mut SystemAllocator,
1891 control_tubes: &mut Vec<TaggedControlTube>,
1892 vfio_path: &Path,
1893 _endpoints: &mut BTreeMap<u32, Arc<Mutex<VfioContainer>>>,
1894 iommu_enabled: bool,
1895) -> DeviceResult<(VfioPlatformDevice, Option<Minijail>)> {
1896 let vfio_container = VfioCommonSetup::vfio_get_container(vfio_path, iommu_enabled)
Daniel Verkamp6b298582021-08-16 15:37:11 -07001897 .context("Failed to create vfio device")?;
Tomasz Nowicki344eb142021-09-22 05:51:58 +00001898
Daniel Verkamp6b298582021-08-16 15:37:11 -07001899 let (vfio_host_tube_mem, vfio_device_tube_mem) =
1900 Tube::pair().context("failed to create tube")?;
Tomasz Nowicki344eb142021-09-22 05:51:58 +00001901 control_tubes.push(TaggedControlTube::VmMemory(vfio_host_tube_mem));
1902
Keiichi Watanabe7b805542021-09-03 02:13:51 +09001903 let vfio_device = VfioDevice::new_passthrough(&vfio_path, vm, vfio_container, iommu_enabled)
Daniel Verkamp6b298582021-08-16 15:37:11 -07001904 .context("Failed to create vfio device")?;
Tomasz Nowicki344eb142021-09-22 05:51:58 +00001905 let vfio_plat_dev = VfioPlatformDevice::new(vfio_device, vfio_device_tube_mem);
1906
1907 Ok((vfio_plat_dev, simple_jail(cfg, "vfio_platform_device")?))
1908}
1909
David Tolnay2b089fc2019-03-04 15:33:22 -08001910fn create_devices(
Trent Begin17ccaad2019-04-17 13:51:25 -06001911 cfg: &Config,
Steven Richmanf32d0b42020-06-20 21:45:32 -07001912 vm: &mut impl Vm,
Jakub Starona3411ea2019-04-24 10:55:25 -07001913 resources: &mut SystemAllocator,
Michael Hoyle685316f2020-09-16 15:29:20 -07001914 exit_evt: &Event,
Zide Chen71435c12021-03-03 15:02:02 -08001915 phys_max_addr: u64,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001916 control_tubes: &mut Vec<TaggedControlTube>,
1917 wayland_device_tube: Tube,
1918 gpu_device_tube: Tube,
Chirantan Ekbote44292f52021-06-25 18:31:41 +09001919 vhost_user_gpu_tubes: Vec<(Tube, Tube)>,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001920 balloon_device_tube: Tube,
1921 disk_device_tubes: &mut Vec<Tube>,
1922 pmem_device_tubes: &mut Vec<Tube>,
1923 fs_device_tubes: &mut Vec<Tube>,
Daniel Verkampf1439d42021-05-21 13:55:10 -07001924 #[cfg(feature = "usb")] usb_provider: HostBackendDeviceProvider,
Lingfeng Yangd6ac1ab2020-01-31 13:55:35 -08001925 map_request: Arc<Mutex<Option<ExternalMapping>>>,
Tomasz Nowickiab86d522021-09-22 05:50:46 +00001926) -> DeviceResult<Vec<(Box<dyn BusDeviceObj>, Option<Minijail>)>> {
David Tolnay2b089fc2019-03-04 15:33:22 -08001927 let stubs = create_virtio_devices(
Daniel Verkamp166d1dd2021-08-19 17:05:29 -07001928 cfg,
Jakub Starona3411ea2019-04-24 10:55:25 -07001929 vm,
1930 resources,
David Tolnay2b089fc2019-03-04 15:33:22 -08001931 exit_evt,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001932 wayland_device_tube,
1933 gpu_device_tube,
Chirantan Ekbote44292f52021-06-25 18:31:41 +09001934 vhost_user_gpu_tubes,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001935 balloon_device_tube,
1936 disk_device_tubes,
1937 pmem_device_tubes,
Lingfeng Yangd6ac1ab2020-01-31 13:55:35 -08001938 map_request,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001939 fs_device_tubes,
David Tolnay2b089fc2019-03-04 15:33:22 -08001940 )?;
1941
Tomasz Nowickiab86d522021-09-22 05:50:46 +00001942 let mut devices = Vec::new();
David Tolnay2b089fc2019-03-04 15:33:22 -08001943
1944 for stub in stubs {
Daniel Verkamp6b298582021-08-16 15:37:11 -07001945 let (msi_host_tube, msi_device_tube) = Tube::pair().context("failed to create tube")?;
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08001946 control_tubes.push(TaggedControlTube::VmIrq(msi_host_tube));
Zach Reiznerdc748482021-04-14 13:59:30 -07001947 let dev = VirtioPciDevice::new(vm.get_memory().clone(), stub.dev, msi_device_tube)
Daniel Verkamp6b298582021-08-16 15:37:11 -07001948 .context("failed to create virtio pci dev")?;
Tomasz Nowickiab86d522021-09-22 05:50:46 +00001949 let dev = Box::new(dev) as Box<dyn BusDeviceObj>;
1950 devices.push((dev, stub.jail));
David Tolnay2b089fc2019-03-04 15:33:22 -08001951 }
1952
Andrew Scull1590e6f2020-03-18 18:00:47 +00001953 #[cfg(feature = "audio")]
Judy Hsiaod5c1e962020-02-04 12:30:01 +08001954 for ac97_param in &cfg.ac97_parameters {
Zach Reiznerdc748482021-04-14 13:59:30 -07001955 let dev = Ac97Dev::try_new(vm.get_memory().clone(), ac97_param.clone())
Daniel Verkamp6b298582021-08-16 15:37:11 -07001956 .context("failed to create ac97 device")?;
Daniel Verkamp166d1dd2021-08-19 17:05:29 -07001957 let jail = simple_jail(cfg, dev.minijail_policy())?;
Tomasz Nowickiab86d522021-09-22 05:50:46 +00001958 devices.push((Box::new(dev), jail));
David Tolnay2b089fc2019-03-04 15:33:22 -08001959 }
Andrew Scull1590e6f2020-03-18 18:00:47 +00001960
Daniel Verkampf1439d42021-05-21 13:55:10 -07001961 #[cfg(feature = "usb")]
1962 {
1963 // Create xhci controller.
1964 let usb_controller = Box::new(XhciController::new(vm.get_memory().clone(), usb_provider));
Tomasz Nowickiab86d522021-09-22 05:50:46 +00001965 devices.push((usb_controller, simple_jail(cfg, "xhci")?));
Daniel Verkampf1439d42021-05-21 13:55:10 -07001966 }
David Tolnay2b089fc2019-03-04 15:33:22 -08001967
Zide Chen5deee482021-04-19 11:06:01 -07001968 if !cfg.vfio.is_empty() {
Zide Chendfc4b882021-03-10 16:35:37 -08001969 let mut iommu_attached_endpoints: BTreeMap<u32, Arc<Mutex<VfioContainer>>> =
1970 BTreeMap::new();
1971
Tomasz Nowicki71aca792021-06-09 18:53:49 +00001972 for vfio_dev in cfg
1973 .vfio
1974 .iter()
1975 .filter(|dev| dev.get_type() == VfioType::Pci)
1976 {
1977 let vfio_path = &vfio_dev.vfio_path;
Zide Chen5deee482021-04-19 11:06:01 -07001978 let (vfio_pci_device, jail) = create_vfio_device(
1979 cfg,
1980 vm,
1981 resources,
1982 control_tubes,
1983 vfio_path.as_path(),
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08001984 None,
Zide Chendfc4b882021-03-10 16:35:37 -08001985 &mut iommu_attached_endpoints,
Tomasz Nowicki71aca792021-06-09 18:53:49 +00001986 vfio_dev.iommu_enabled(),
Zide Chen5deee482021-04-19 11:06:01 -07001987 )?;
Zide Chendfc4b882021-03-10 16:35:37 -08001988
Tomasz Nowickiab86d522021-09-22 05:50:46 +00001989 devices.push((vfio_pci_device, jail));
Zide Chen5deee482021-04-19 11:06:01 -07001990 }
Zide Chendfc4b882021-03-10 16:35:37 -08001991
Tomasz Nowicki344eb142021-09-22 05:51:58 +00001992 for vfio_dev in cfg
1993 .vfio
1994 .iter()
1995 .filter(|dev| dev.get_type() == VfioType::Platform)
1996 {
1997 let vfio_path = &vfio_dev.vfio_path;
1998 let (vfio_plat_dev, jail) = create_vfio_platform_device(
1999 cfg,
2000 vm,
2001 resources,
2002 control_tubes,
2003 vfio_path.as_path(),
2004 &mut iommu_attached_endpoints,
2005 false, // Virtio IOMMU is not supported yet
2006 )?;
2007
2008 devices.push((Box::new(vfio_plat_dev), jail));
2009 }
2010
Zide Chendfc4b882021-03-10 16:35:37 -08002011 if !iommu_attached_endpoints.is_empty() {
Zide Chen71435c12021-03-03 15:02:02 -08002012 let iommu_dev = create_iommu_device(cfg, phys_max_addr, iommu_attached_endpoints)?;
Zide Chendfc4b882021-03-10 16:35:37 -08002013
Daniel Verkamp6b298582021-08-16 15:37:11 -07002014 let (msi_host_tube, msi_device_tube) = Tube::pair().context("failed to create tube")?;
Zide Chendfc4b882021-03-10 16:35:37 -08002015 control_tubes.push(TaggedControlTube::VmIrq(msi_host_tube));
Peter Fangad3b24e2021-06-21 00:43:29 -07002016 let mut dev =
2017 VirtioPciDevice::new(vm.get_memory().clone(), iommu_dev.dev, msi_device_tube)
Daniel Verkamp6b298582021-08-16 15:37:11 -07002018 .context("failed to create virtio pci dev")?;
Peter Fangad3b24e2021-06-21 00:43:29 -07002019 // early reservation for viommu.
2020 dev.allocate_address(resources)
Daniel Verkamp6b298582021-08-16 15:37:11 -07002021 .context("failed to allocate resources early for virtio pci dev")?;
Peter Fangad3b24e2021-06-21 00:43:29 -07002022 let dev = Box::new(dev);
Tomasz Nowickiab86d522021-09-22 05:50:46 +00002023 devices.push((dev, iommu_dev.jail));
Zide Chendfc4b882021-03-10 16:35:37 -08002024 }
Xiong Zhang17b0daf2019-04-23 17:14:50 +08002025 }
2026
Mattias Nisslerde2c6402021-10-21 12:05:29 +00002027 for params in &cfg.stub_pci_devices {
2028 // Stub devices don't need jailing since they don't do anything.
2029 devices.push((Box::new(StubPciDevice::new(params)), None));
2030 }
2031
Tomasz Nowickiab86d522021-09-22 05:50:46 +00002032 Ok(devices)
David Tolnay2b089fc2019-03-04 15:33:22 -08002033}
2034
2035#[derive(Copy, Clone)]
Chirantan Ekbote1a2683b2019-11-26 16:28:23 +09002036#[cfg_attr(not(feature = "tpm"), allow(dead_code))]
David Tolnay2b089fc2019-03-04 15:33:22 -08002037struct Ids {
2038 uid: uid_t,
2039 gid: gid_t,
2040}
2041
David Tolnay48c48292019-03-01 16:54:25 -08002042// Set the uid/gid for the jailed process and give a basic id map. This is
2043// required for bind mounts to work.
Fergus Dall51200512021-08-19 12:54:26 +10002044fn add_current_user_to_jail(jail: &mut Minijail) -> Result<Ids> {
2045 let crosvm_uid = geteuid();
2046 let crosvm_gid = getegid();
David Tolnay48c48292019-03-01 16:54:25 -08002047
David Tolnay48c48292019-03-01 16:54:25 -08002048 jail.uidmap(&format!("{0} {0} 1", crosvm_uid))
Daniel Verkamp6b298582021-08-16 15:37:11 -07002049 .context("error setting UID map")?;
David Tolnay48c48292019-03-01 16:54:25 -08002050 jail.gidmap(&format!("{0} {0} 1", crosvm_gid))
Daniel Verkamp6b298582021-08-16 15:37:11 -07002051 .context("error setting GID map")?;
David Tolnay48c48292019-03-01 16:54:25 -08002052
Chirantan Ekbotee1663ee2021-09-03 18:31:25 +09002053 if crosvm_uid != 0 {
2054 jail.change_uid(crosvm_uid);
2055 }
2056 if crosvm_gid != 0 {
2057 jail.change_gid(crosvm_gid);
2058 }
Fergus Dall51200512021-08-19 12:54:26 +10002059
David Tolnay41a6f842019-03-01 16:18:44 -08002060 Ok(Ids {
2061 uid: crosvm_uid,
2062 gid: crosvm_gid,
2063 })
David Tolnay48c48292019-03-01 16:54:25 -08002064}
2065
Chia-I Wu16fb6592021-11-10 11:45:32 -08002066fn add_current_user_as_root_to_jail(jail: &mut Minijail) -> Result<Ids> {
2067 let crosvm_uid = geteuid();
2068 let crosvm_gid = getegid();
2069 jail.uidmap(&format!("0 {0} 1", crosvm_uid))
2070 .context("error setting UID map")?;
2071 jail.gidmap(&format!("0 {0} 1", crosvm_gid))
2072 .context("error setting GID map")?;
2073
2074 Ok(Ids {
2075 uid: crosvm_uid,
2076 gid: crosvm_gid,
2077 })
2078}
2079
Zach Reizner65b98f12019-11-22 17:34:58 -08002080trait IntoUnixStream {
2081 fn into_unix_stream(self) -> Result<UnixStream>;
2082}
2083
2084impl<'a> IntoUnixStream for &'a Path {
2085 fn into_unix_stream(self) -> Result<UnixStream> {
Daniel Verkamp6b298582021-08-16 15:37:11 -07002086 if let Some(fd) = safe_descriptor_from_path(self).context("failed to open event device")? {
Andrew Walbranbc55e302021-07-13 17:35:10 +01002087 Ok(fd.into())
Zach Reizner65b98f12019-11-22 17:34:58 -08002088 } else {
Daniel Verkamp6b298582021-08-16 15:37:11 -07002089 UnixStream::connect(self).context("failed to open event device")
Zach Reizner65b98f12019-11-22 17:34:58 -08002090 }
2091 }
2092}
2093impl<'a> IntoUnixStream for &'a PathBuf {
2094 fn into_unix_stream(self) -> Result<UnixStream> {
2095 self.as_path().into_unix_stream()
2096 }
2097}
2098
2099impl IntoUnixStream for UnixStream {
2100 fn into_unix_stream(self) -> Result<UnixStream> {
2101 Ok(self)
Jorge E. Moreiradffec502019-01-14 18:44:49 -08002102 }
2103}
2104
Steven Richmanf32d0b42020-06-20 21:45:32 -07002105fn setup_vcpu_signal_handler<T: Vcpu>(use_hypervisor_signals: bool) -> Result<()> {
2106 if use_hypervisor_signals {
Matt Delco84cf9c02019-10-07 22:38:13 -07002107 unsafe {
Allen Webb44c728c2021-03-23 15:22:41 -05002108 extern "C" fn handle_signal(_: c_int) {}
Matt Delco84cf9c02019-10-07 22:38:13 -07002109 // Our signal handler does nothing and is trivially async signal safe.
2110 register_rt_signal_handler(SIGRTMIN() + 0, handle_signal)
Daniel Verkamp6b298582021-08-16 15:37:11 -07002111 .context("error registering signal handler")?;
Matt Delco84cf9c02019-10-07 22:38:13 -07002112 }
Daniel Verkamp6b298582021-08-16 15:37:11 -07002113 block_signal(SIGRTMIN() + 0).context("failed to block signal")?;
Matt Delco84cf9c02019-10-07 22:38:13 -07002114 } else {
2115 unsafe {
Allen Webb44c728c2021-03-23 15:22:41 -05002116 extern "C" fn handle_signal<T: Vcpu>(_: c_int) {
Steven Richmanf32d0b42020-06-20 21:45:32 -07002117 T::set_local_immediate_exit(true);
Matt Delco84cf9c02019-10-07 22:38:13 -07002118 }
Steven Richmanf32d0b42020-06-20 21:45:32 -07002119 register_rt_signal_handler(SIGRTMIN() + 0, handle_signal::<T>)
Daniel Verkamp6b298582021-08-16 15:37:11 -07002120 .context("error registering signal handler")?;
Matt Delco84cf9c02019-10-07 22:38:13 -07002121 }
Mark Ryan6ed5aea2018-04-20 13:52:35 +01002122 }
Mark Ryan6ed5aea2018-04-20 13:52:35 +01002123 Ok(())
2124}
2125
Steven Richmanf32d0b42020-06-20 21:45:32 -07002126// Sets up a vcpu and converts it into a runnable vcpu.
Zach Reizner2c770e62020-09-30 16:49:59 -07002127fn runnable_vcpu<V>(
Steven Richmanf32d0b42020-06-20 21:45:32 -07002128 cpu_id: usize,
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +08002129 kvm_vcpu_id: usize,
Steven Richmanf32d0b42020-06-20 21:45:32 -07002130 vcpu: Option<V>,
Zach Reizner304e7312020-09-29 16:00:24 -07002131 vm: impl VmArch,
Zach Reiznerdc748482021-04-14 13:59:30 -07002132 irq_chip: &mut dyn IrqChipArch,
Steven Richmanf32d0b42020-06-20 21:45:32 -07002133 vcpu_count: usize,
Kansho Nishidaab205af2020-08-13 18:17:50 +09002134 run_rt: bool,
Steven Richmanf32d0b42020-06-20 21:45:32 -07002135 vcpu_affinity: Vec<usize>,
Suleiman Souhlal015c3c12020-10-07 14:15:41 +09002136 no_smt: bool,
Steven Richmanf32d0b42020-06-20 21:45:32 -07002137 has_bios: bool,
2138 use_hypervisor_signals: bool,
Yusuke Sato31e136a2021-08-18 11:51:38 -07002139 enable_per_vm_core_scheduling: bool,
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +08002140 host_cpu_topology: bool,
Zach Reizner2c770e62020-09-30 16:49:59 -07002141) -> Result<(V, VcpuRunHandle)>
Steven Richmanf32d0b42020-06-20 21:45:32 -07002142where
Zach Reizner2c770e62020-09-30 16:49:59 -07002143 V: VcpuArch,
Steven Richmanf32d0b42020-06-20 21:45:32 -07002144{
Zach Reizner304e7312020-09-29 16:00:24 -07002145 let mut vcpu = match vcpu {
2146 Some(v) => v,
2147 None => {
2148 // If vcpu is None, it means this arch/hypervisor requires create_vcpu to be called from
2149 // the vcpu thread.
2150 match vm
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +08002151 .create_vcpu(kvm_vcpu_id)
Daniel Verkamp6b298582021-08-16 15:37:11 -07002152 .context("failed to create vcpu")?
Zach Reizner304e7312020-09-29 16:00:24 -07002153 .downcast::<V>()
2154 {
2155 Ok(v) => *v,
2156 Err(_) => panic!("VM created wrong type of VCPU"),
2157 }
2158 }
Steven Richmanf32d0b42020-06-20 21:45:32 -07002159 };
Dylan Reidbb30b2f2019-10-22 18:30:36 +03002160
Steven Richmanf32d0b42020-06-20 21:45:32 -07002161 irq_chip
Zach Reizner304e7312020-09-29 16:00:24 -07002162 .add_vcpu(cpu_id, &vcpu)
Daniel Verkamp6b298582021-08-16 15:37:11 -07002163 .context("failed to add vcpu to irq chip")?;
Steven Richmanf32d0b42020-06-20 21:45:32 -07002164
Daniel Verkampcaf9ced2020-09-29 15:35:02 -07002165 if !vcpu_affinity.is_empty() {
2166 if let Err(e) = set_cpu_affinity(vcpu_affinity) {
2167 error!("Failed to set CPU affinity: {}", e);
2168 }
2169 }
2170
Steven Richmanf32d0b42020-06-20 21:45:32 -07002171 Arch::configure_vcpu(
Daniel Verkamp6f4f8222022-01-05 14:09:09 -08002172 &vm,
Steven Richmanf32d0b42020-06-20 21:45:32 -07002173 vm.get_hypervisor(),
2174 irq_chip,
2175 &mut vcpu,
2176 cpu_id,
2177 vcpu_count,
2178 has_bios,
Suleiman Souhlal015c3c12020-10-07 14:15:41 +09002179 no_smt,
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +08002180 host_cpu_topology,
Steven Richmanf32d0b42020-06-20 21:45:32 -07002181 )
Daniel Verkamp6b298582021-08-16 15:37:11 -07002182 .context("failed to configure vcpu")?;
Steven Richmanf32d0b42020-06-20 21:45:32 -07002183
Yusuke Sato31e136a2021-08-18 11:51:38 -07002184 if !enable_per_vm_core_scheduling {
2185 // Do per-vCPU core scheduling by setting a unique cookie to each vCPU.
2186 if let Err(e) = enable_core_scheduling() {
2187 error!("Failed to enable core scheduling: {}", e);
2188 }
Steven Richmanf32d0b42020-06-20 21:45:32 -07002189 }
2190
Kansho Nishidaab205af2020-08-13 18:17:50 +09002191 if run_rt {
2192 const DEFAULT_VCPU_RT_LEVEL: u16 = 6;
2193 if let Err(e) = set_rt_prio_limit(u64::from(DEFAULT_VCPU_RT_LEVEL))
2194 .and_then(|_| set_rt_round_robin(i32::from(DEFAULT_VCPU_RT_LEVEL)))
2195 {
2196 warn!("Failed to set vcpu to real time: {}", e);
2197 }
2198 }
2199
Steven Richmanf32d0b42020-06-20 21:45:32 -07002200 if use_hypervisor_signals {
Daniel Verkamp6b298582021-08-16 15:37:11 -07002201 let mut v = get_blocked_signals().context("failed to retrieve signal mask for vcpu")?;
Steven Richmanf32d0b42020-06-20 21:45:32 -07002202 v.retain(|&x| x != SIGRTMIN() + 0);
Daniel Verkamp6b298582021-08-16 15:37:11 -07002203 vcpu.set_signal_mask(&v)
2204 .context("failed to set the signal mask for vcpu")?;
Steven Richmanf32d0b42020-06-20 21:45:32 -07002205 }
2206
Zach Reizner2c770e62020-09-30 16:49:59 -07002207 let vcpu_run_handle = vcpu
2208 .take_run_handle(Some(SIGRTMIN() + 0))
Daniel Verkamp6b298582021-08-16 15:37:11 -07002209 .context("failed to set thread id for vcpu")?;
Zach Reizner2c770e62020-09-30 16:49:59 -07002210
2211 Ok((vcpu, vcpu_run_handle))
Dylan Reidbb30b2f2019-10-22 18:30:36 +03002212}
2213
Keiichi Watanabec5262e92020-10-21 15:57:33 +09002214#[cfg(all(target_arch = "x86_64", feature = "gdb"))]
2215fn handle_debug_msg<V>(
2216 cpu_id: usize,
2217 vcpu: &V,
2218 guest_mem: &GuestMemory,
2219 d: VcpuDebug,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002220 reply_tube: &mpsc::Sender<VcpuDebugStatusMessage>,
Keiichi Watanabec5262e92020-10-21 15:57:33 +09002221) -> Result<()>
2222where
2223 V: VcpuArch + 'static,
2224{
2225 match d {
2226 VcpuDebug::ReadRegs => {
2227 let msg = VcpuDebugStatusMessage {
2228 cpu: cpu_id as usize,
2229 msg: VcpuDebugStatus::RegValues(
Daniel Verkamp6b298582021-08-16 15:37:11 -07002230 Arch::debug_read_registers(vcpu as &V)
2231 .context("failed to handle a gdb ReadRegs command")?,
Keiichi Watanabec5262e92020-10-21 15:57:33 +09002232 ),
2233 };
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002234 reply_tube
Keiichi Watanabec5262e92020-10-21 15:57:33 +09002235 .send(msg)
Daniel Verkamp6b298582021-08-16 15:37:11 -07002236 .context("failed to send a debug status to GDB thread")
Keiichi Watanabec5262e92020-10-21 15:57:33 +09002237 }
2238 VcpuDebug::WriteRegs(regs) => {
Daniel Verkamp6b298582021-08-16 15:37:11 -07002239 Arch::debug_write_registers(vcpu as &V, &regs)
2240 .context("failed to handle a gdb WriteRegs command")?;
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002241 reply_tube
Keiichi Watanabec5262e92020-10-21 15:57:33 +09002242 .send(VcpuDebugStatusMessage {
2243 cpu: cpu_id as usize,
2244 msg: VcpuDebugStatus::CommandComplete,
2245 })
Daniel Verkamp6b298582021-08-16 15:37:11 -07002246 .context("failed to send a debug status to GDB thread")
Keiichi Watanabec5262e92020-10-21 15:57:33 +09002247 }
2248 VcpuDebug::ReadMem(vaddr, len) => {
2249 let msg = VcpuDebugStatusMessage {
2250 cpu: cpu_id as usize,
2251 msg: VcpuDebugStatus::MemoryRegion(
2252 Arch::debug_read_memory(vcpu as &V, guest_mem, vaddr, len)
2253 .unwrap_or(Vec::new()),
2254 ),
2255 };
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002256 reply_tube
Keiichi Watanabec5262e92020-10-21 15:57:33 +09002257 .send(msg)
Daniel Verkamp6b298582021-08-16 15:37:11 -07002258 .context("failed to send a debug status to GDB thread")
Keiichi Watanabec5262e92020-10-21 15:57:33 +09002259 }
2260 VcpuDebug::WriteMem(vaddr, buf) => {
2261 Arch::debug_write_memory(vcpu as &V, guest_mem, vaddr, &buf)
Daniel Verkamp6b298582021-08-16 15:37:11 -07002262 .context("failed to handle a gdb WriteMem command")?;
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002263 reply_tube
Keiichi Watanabec5262e92020-10-21 15:57:33 +09002264 .send(VcpuDebugStatusMessage {
2265 cpu: cpu_id as usize,
2266 msg: VcpuDebugStatus::CommandComplete,
2267 })
Daniel Verkamp6b298582021-08-16 15:37:11 -07002268 .context("failed to send a debug status to GDB thread")
Keiichi Watanabec5262e92020-10-21 15:57:33 +09002269 }
Keiichi Watanabe23f94712020-10-22 17:43:06 +09002270 VcpuDebug::EnableSinglestep => {
Daniel Verkamp6b298582021-08-16 15:37:11 -07002271 Arch::debug_enable_singlestep(vcpu as &V)
2272 .context("failed to handle a gdb EnableSingleStep command")?;
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002273 reply_tube
Keiichi Watanabe23f94712020-10-22 17:43:06 +09002274 .send(VcpuDebugStatusMessage {
2275 cpu: cpu_id as usize,
2276 msg: VcpuDebugStatus::CommandComplete,
2277 })
Daniel Verkamp6b298582021-08-16 15:37:11 -07002278 .context("failed to send a debug status to GDB thread")
Keiichi Watanabe23f94712020-10-22 17:43:06 +09002279 }
2280 VcpuDebug::SetHwBreakPoint(addrs) => {
2281 Arch::debug_set_hw_breakpoints(vcpu as &V, &addrs)
Daniel Verkamp6b298582021-08-16 15:37:11 -07002282 .context("failed to handle a gdb SetHwBreakPoint command")?;
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002283 reply_tube
Keiichi Watanabe23f94712020-10-22 17:43:06 +09002284 .send(VcpuDebugStatusMessage {
2285 cpu: cpu_id as usize,
2286 msg: VcpuDebugStatus::CommandComplete,
2287 })
Daniel Verkamp6b298582021-08-16 15:37:11 -07002288 .context("failed to send a debug status to GDB thread")
Keiichi Watanabe23f94712020-10-22 17:43:06 +09002289 }
Keiichi Watanabec5262e92020-10-21 15:57:33 +09002290 }
2291}
2292
Zach Reizner2c770e62020-09-30 16:49:59 -07002293fn run_vcpu<V>(
Steven Richmanf32d0b42020-06-20 21:45:32 -07002294 cpu_id: usize,
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +08002295 kvm_vcpu_id: usize,
Steven Richmanf32d0b42020-06-20 21:45:32 -07002296 vcpu: Option<V>,
Zach Reizner304e7312020-09-29 16:00:24 -07002297 vm: impl VmArch + 'static,
Zach Reiznerdc748482021-04-14 13:59:30 -07002298 mut irq_chip: Box<dyn IrqChipArch + 'static>,
Steven Richmanf32d0b42020-06-20 21:45:32 -07002299 vcpu_count: usize,
Kansho Nishidaab205af2020-08-13 18:17:50 +09002300 run_rt: bool,
Daniel Verkamp107edb32019-04-05 09:58:48 -07002301 vcpu_affinity: Vec<usize>,
Suleiman Souhlal63630e82021-02-18 11:53:11 +09002302 delay_rt: bool,
Suleiman Souhlal015c3c12020-10-07 14:15:41 +09002303 no_smt: bool,
Zach Reizner55a9e502018-10-03 10:22:32 -07002304 start_barrier: Arc<Barrier>,
Steven Richmanf32d0b42020-06-20 21:45:32 -07002305 has_bios: bool,
Colin Downs-Razouk11bed5e2021-11-02 09:33:14 -07002306 mut io_bus: devices::Bus,
2307 mut mmio_bus: devices::Bus,
Michael Hoyle685316f2020-09-16 15:29:20 -07002308 exit_evt: Event,
Steven Richmanf32d0b42020-06-20 21:45:32 -07002309 requires_pvclock_ctrl: bool,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002310 from_main_tube: mpsc::Receiver<VcpuControl>,
Steven Richmanf32d0b42020-06-20 21:45:32 -07002311 use_hypervisor_signals: bool,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002312 #[cfg(all(target_arch = "x86_64", feature = "gdb"))] to_gdb_tube: Option<
Keiichi Watanabec5262e92020-10-21 15:57:33 +09002313 mpsc::Sender<VcpuDebugStatusMessage>,
2314 >,
Yusuke Sato31e136a2021-08-18 11:51:38 -07002315 enable_per_vm_core_scheduling: bool,
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +08002316 host_cpu_topology: bool,
Steven Richmanf32d0b42020-06-20 21:45:32 -07002317) -> Result<JoinHandle<()>>
2318where
Zach Reizner2c770e62020-09-30 16:49:59 -07002319 V: VcpuArch + 'static,
Steven Richmanf32d0b42020-06-20 21:45:32 -07002320{
Zach Reizner8fb52112017-12-13 16:04:39 -08002321 thread::Builder::new()
2322 .name(format!("crosvm_vcpu{}", cpu_id))
2323 .spawn(move || {
Zach Reizner95885312020-01-29 18:06:01 -08002324 // The VCPU thread must trigger the `exit_evt` in all paths, and a `ScopedEvent`'s Drop
2325 // implementation accomplishes that.
2326 let _scoped_exit_evt = ScopedEvent::from(exit_evt);
2327
Keiichi Watanabec5262e92020-10-21 15:57:33 +09002328 #[cfg(all(target_arch = "x86_64", feature = "gdb"))]
2329 let guest_mem = vm.get_memory().clone();
Zach Reizner2c770e62020-09-30 16:49:59 -07002330 let runnable_vcpu = runnable_vcpu(
Steven Richmanf32d0b42020-06-20 21:45:32 -07002331 cpu_id,
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +08002332 kvm_vcpu_id,
Steven Richmanf32d0b42020-06-20 21:45:32 -07002333 vcpu,
2334 vm,
Zach Reiznerdc748482021-04-14 13:59:30 -07002335 irq_chip.as_mut(),
Steven Richmanf32d0b42020-06-20 21:45:32 -07002336 vcpu_count,
Suleiman Souhlal63630e82021-02-18 11:53:11 +09002337 run_rt && !delay_rt,
Steven Richmanf32d0b42020-06-20 21:45:32 -07002338 vcpu_affinity,
Suleiman Souhlal015c3c12020-10-07 14:15:41 +09002339 no_smt,
Steven Richmanf32d0b42020-06-20 21:45:32 -07002340 has_bios,
2341 use_hypervisor_signals,
Yusuke Sato31e136a2021-08-18 11:51:38 -07002342 enable_per_vm_core_scheduling,
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +08002343 host_cpu_topology,
Steven Richmanf32d0b42020-06-20 21:45:32 -07002344 );
Zach Reizner39aa26b2017-12-12 18:03:23 -08002345
Zach Reizner8fb52112017-12-13 16:04:39 -08002346 start_barrier.wait();
Mark Ryan6ed5aea2018-04-20 13:52:35 +01002347
Zach Reizner2c770e62020-09-30 16:49:59 -07002348 let (vcpu, vcpu_run_handle) = match runnable_vcpu {
Steven Richmanf32d0b42020-06-20 21:45:32 -07002349 Ok(v) => v,
2350 Err(e) => {
Maciek Swiechc3011222021-11-24 21:01:04 +00002351 error!("failed to start vcpu {}: {:#}", cpu_id, e);
Steven Richmanf32d0b42020-06-20 21:45:32 -07002352 return;
2353 }
2354 };
Mark Ryan6ed5aea2018-04-20 13:52:35 +01002355
Dylan Reidb0492662019-05-17 14:50:13 -07002356 let mut run_mode = VmRunMode::Running;
Keiichi Watanabec5262e92020-10-21 15:57:33 +09002357 #[cfg(all(target_arch = "x86_64", feature = "gdb"))]
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002358 if to_gdb_tube.is_some() {
Keiichi Watanabec5262e92020-10-21 15:57:33 +09002359 // Wait until a GDB client attaches
2360 run_mode = VmRunMode::Breakpoint;
2361 }
2362
Dylan Reidb0492662019-05-17 14:50:13 -07002363 let mut interrupted_by_signal = false;
2364
Colin Downs-Razouk11bed5e2021-11-02 09:33:14 -07002365 mmio_bus.set_access_id(cpu_id);
2366 io_bus.set_access_id(cpu_id);
2367
Dylan Reidb0492662019-05-17 14:50:13 -07002368 'vcpu_loop: loop {
2369 // Start by checking for messages to process and the run state of the CPU.
2370 // An extra check here for Running so there isn't a need to call recv unless a
2371 // message is likely to be ready because a signal was sent.
2372 if interrupted_by_signal || run_mode != VmRunMode::Running {
2373 'state_loop: loop {
2374 // Tries to get a pending message without blocking first.
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002375 let msg = match from_main_tube.try_recv() {
Dylan Reidb0492662019-05-17 14:50:13 -07002376 Ok(m) => m,
2377 Err(mpsc::TryRecvError::Empty) if run_mode == VmRunMode::Running => {
2378 // If the VM is running and no message is pending, the state won't
Keiichi Watanabec5262e92020-10-21 15:57:33 +09002379 // change.
Dylan Reidb0492662019-05-17 14:50:13 -07002380 break 'state_loop;
2381 }
2382 Err(mpsc::TryRecvError::Empty) => {
2383 // If the VM is not running, wait until a message is ready.
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002384 match from_main_tube.recv() {
Dylan Reidb0492662019-05-17 14:50:13 -07002385 Ok(m) => m,
2386 Err(mpsc::RecvError) => {
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002387 error!("Failed to read from main tube in vcpu");
Dylan Reidb0492662019-05-17 14:50:13 -07002388 break 'vcpu_loop;
2389 }
2390 }
2391 }
2392 Err(mpsc::TryRecvError::Disconnected) => {
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002393 error!("Failed to read from main tube in vcpu");
Dylan Reidb0492662019-05-17 14:50:13 -07002394 break 'vcpu_loop;
2395 }
2396 };
2397
2398 // Collect all pending messages.
2399 let mut messages = vec![msg];
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002400 messages.append(&mut from_main_tube.try_iter().collect());
Dylan Reidb0492662019-05-17 14:50:13 -07002401
Keiichi Watanabec5262e92020-10-21 15:57:33 +09002402 for msg in messages {
2403 match msg {
2404 VcpuControl::RunState(new_mode) => {
2405 run_mode = new_mode;
2406 match run_mode {
2407 VmRunMode::Running => break 'state_loop,
2408 VmRunMode::Suspending => {
2409 // On KVM implementations that use a paravirtualized
2410 // clock (e.g. x86), a flag must be set to indicate to
2411 // the guest kernel that a vCPU was suspended. The guest
2412 // kernel will use this flag to prevent the soft lockup
2413 // detection from triggering when this vCPU resumes,
2414 // which could happen days later in realtime.
2415 if requires_pvclock_ctrl {
2416 if let Err(e) = vcpu.pvclock_ctrl() {
2417 error!(
2418 "failed to tell hypervisor vcpu {} is suspending: {}",
2419 cpu_id, e
2420 );
2421 }
2422 }
2423 }
2424 VmRunMode::Breakpoint => {}
2425 VmRunMode::Exiting => break 'vcpu_loop,
2426 }
2427 }
2428 #[cfg(all(target_arch = "x86_64", feature = "gdb"))]
2429 VcpuControl::Debug(d) => {
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002430 match &to_gdb_tube {
Keiichi Watanabec5262e92020-10-21 15:57:33 +09002431 Some(ref ch) => {
2432 if let Err(e) = handle_debug_msg(
Daniel Verkamp166d1dd2021-08-19 17:05:29 -07002433 cpu_id, &vcpu, &guest_mem, d, ch,
Keiichi Watanabec5262e92020-10-21 15:57:33 +09002434 ) {
2435 error!("Failed to handle gdb message: {}", e);
2436 }
2437 },
2438 None => {
2439 error!("VcpuControl::Debug received while GDB feature is disabled: {:?}", d);
Dylan Reidb0492662019-05-17 14:50:13 -07002440 }
2441 }
2442 }
Suleiman Souhlal2ac78b92021-02-01 12:33:26 +09002443 VcpuControl::MakeRT => {
2444 if run_rt && delay_rt {
2445 info!("Making vcpu {} RT\n", cpu_id);
2446 const DEFAULT_VCPU_RT_LEVEL: u16 = 6;
2447 if let Err(e) = set_rt_prio_limit(
2448 u64::from(DEFAULT_VCPU_RT_LEVEL))
2449 .and_then(|_|
2450 set_rt_round_robin(
2451 i32::from(DEFAULT_VCPU_RT_LEVEL)
2452 ))
2453 {
2454 warn!("Failed to set vcpu to real time: {}", e);
2455 }
2456 }
2457 }
Dylan Reidb0492662019-05-17 14:50:13 -07002458 }
2459 }
2460 }
2461 }
2462
2463 interrupted_by_signal = false;
2464
Steven Richman11dc6712020-09-02 15:39:14 -07002465 // Vcpus may have run a HLT instruction, which puts them into a state other than
2466 // VcpuRunState::Runnable. In that case, this call to wait_until_runnable blocks
2467 // until either the irqchip receives an interrupt for this vcpu, or until the main
2468 // thread kicks this vcpu as a result of some VmControl operation. In most IrqChip
2469 // implementations HLT instructions do not make it to crosvm, and thus this is a
2470 // no-op that always returns VcpuRunState::Runnable.
2471 match irq_chip.wait_until_runnable(&vcpu) {
2472 Ok(VcpuRunState::Runnable) => {}
2473 Ok(VcpuRunState::Interrupted) => interrupted_by_signal = true,
2474 Err(e) => error!(
2475 "error waiting for vcpu {} to become runnable: {}",
2476 cpu_id, e
2477 ),
2478 }
2479
2480 if !interrupted_by_signal {
2481 match vcpu.run(&vcpu_run_handle) {
2482 Ok(VcpuExit::IoIn { port, mut size }) => {
2483 let mut data = [0; 8];
2484 if size > data.len() {
Dmitry Torokhova0410682021-08-01 10:40:50 -07002485 error!("unsupported IoIn size of {} bytes at port {:#x}", size, port);
Steven Richman11dc6712020-09-02 15:39:14 -07002486 size = data.len();
Keiichi Watanabe23f94712020-10-22 17:43:06 +09002487 }
Steven Richman11dc6712020-09-02 15:39:14 -07002488 io_bus.read(port as u64, &mut data[..size]);
2489 if let Err(e) = vcpu.set_data(&data[..size]) {
Dmitry Torokhova0410682021-08-01 10:40:50 -07002490 error!("failed to set return data for IoIn at port {:#x}: {}", port, e);
Steven Richman11dc6712020-09-02 15:39:14 -07002491 }
Keiichi Watanabe23f94712020-10-22 17:43:06 +09002492 }
Steven Richman11dc6712020-09-02 15:39:14 -07002493 Ok(VcpuExit::IoOut {
2494 port,
2495 mut size,
2496 data,
2497 }) => {
2498 if size > data.len() {
Dmitry Torokhova0410682021-08-01 10:40:50 -07002499 error!("unsupported IoOut size of {} bytes at port {:#x}", size, port);
Steven Richman11dc6712020-09-02 15:39:14 -07002500 size = data.len();
2501 }
2502 io_bus.write(port as u64, &data[..size]);
2503 }
2504 Ok(VcpuExit::MmioRead { address, size }) => {
2505 let mut data = [0; 8];
2506 mmio_bus.read(address, &mut data[..size]);
2507 // Setting data for mmio can not fail.
2508 let _ = vcpu.set_data(&data[..size]);
2509 }
2510 Ok(VcpuExit::MmioWrite {
2511 address,
2512 size,
2513 data,
2514 }) => {
2515 mmio_bus.write(address, &data[..size]);
2516 }
2517 Ok(VcpuExit::IoapicEoi { vector }) => {
2518 if let Err(e) = irq_chip.broadcast_eoi(vector) {
2519 error!(
2520 "failed to broadcast eoi {} on vcpu {}: {}",
2521 vector, cpu_id, e
2522 );
2523 }
2524 }
2525 Ok(VcpuExit::IrqWindowOpen) => {}
Leo Lai558460f2021-07-23 05:32:27 +00002526 Ok(VcpuExit::Hlt) => irq_chip.halted(cpu_id),
Steven Richman11dc6712020-09-02 15:39:14 -07002527 Ok(VcpuExit::Shutdown) => break,
2528 Ok(VcpuExit::FailEntry {
2529 hardware_entry_failure_reason,
2530 }) => {
2531 error!("vcpu hw run failure: {:#x}", hardware_entry_failure_reason);
Steven Richmanf32d0b42020-06-20 21:45:32 -07002532 break;
2533 }
Steven Richman11dc6712020-09-02 15:39:14 -07002534 Ok(VcpuExit::SystemEvent(_, _)) => break,
2535 Ok(VcpuExit::Debug { .. }) => {
2536 #[cfg(all(target_arch = "x86_64", feature = "gdb"))]
2537 {
2538 let msg = VcpuDebugStatusMessage {
2539 cpu: cpu_id as usize,
2540 msg: VcpuDebugStatus::HitBreakPoint,
2541 };
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002542 if let Some(ref ch) = to_gdb_tube {
Steven Richman11dc6712020-09-02 15:39:14 -07002543 if let Err(e) = ch.send(msg) {
2544 error!("failed to notify breakpoint to GDB thread: {}", e);
2545 break;
2546 }
2547 }
2548 run_mode = VmRunMode::Breakpoint;
2549 }
2550 }
2551 Ok(r) => warn!("unexpected vcpu exit: {:?}", r),
2552 Err(e) => match e.errno() {
2553 libc::EINTR => interrupted_by_signal = true,
2554 libc::EAGAIN => {}
2555 _ => {
2556 error!("vcpu hit unknown error: {}", e);
2557 break;
2558 }
2559 },
2560 }
Steven Richmanf32d0b42020-06-20 21:45:32 -07002561 }
2562
2563 if interrupted_by_signal {
2564 if use_hypervisor_signals {
2565 // Try to clear the signal that we use to kick VCPU if it is pending before
2566 // attempting to handle pause requests.
2567 if let Err(e) = clear_signal(SIGRTMIN() + 0) {
2568 error!("failed to clear pending signal: {}", e);
2569 break;
2570 }
2571 } else {
2572 vcpu.set_immediate_exit(false);
2573 }
David Tolnay8f3a2322018-11-30 17:11:35 -08002574 }
Steven Richmanf32d0b42020-06-20 21:45:32 -07002575
Steven Richman11dc6712020-09-02 15:39:14 -07002576 if let Err(e) = irq_chip.inject_interrupts(&vcpu) {
2577 error!("failed to inject interrupts for vcpu {}: {}", cpu_id, e);
2578 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08002579 }
David Tolnay2bac1e72018-12-12 14:33:42 -08002580 })
Daniel Verkamp6b298582021-08-16 15:37:11 -07002581 .context("failed to spawn VCPU thread")
Zach Reizner39aa26b2017-12-12 18:03:23 -08002582}
2583
Zach Reiznera90649a2021-03-31 12:56:08 -07002584fn setup_vm_components(cfg: &Config) -> Result<VmComponents> {
David Tolnay2b089fc2019-03-04 15:33:22 -08002585 let initrd_image = if let Some(initrd_path) = &cfg.initrd_path {
Andrew Walbranbc55e302021-07-13 17:35:10 +01002586 Some(
Junichi Uekawa7bea39f2021-07-16 14:05:06 +09002587 open_file(
2588 initrd_path,
2589 true, /*read_only*/
2590 false, /*O_DIRECT*/
2591 )
Daniel Verkamp6b298582021-08-16 15:37:11 -07002592 .with_context(|| format!("failed to open initrd {}", initrd_path.display()))?,
Andrew Walbranbc55e302021-07-13 17:35:10 +01002593 )
Daniel Verkampe403f5c2018-12-11 16:29:26 -08002594 } else {
2595 None
2596 };
2597
Cody Schuffelen6d1ab502019-05-21 12:12:38 -07002598 let vm_image = match cfg.executable_path {
Andrew Walbranbc55e302021-07-13 17:35:10 +01002599 Some(Executable::Kernel(ref kernel_path)) => VmImage::Kernel(
Junichi Uekawa7bea39f2021-07-16 14:05:06 +09002600 open_file(
2601 kernel_path,
2602 true, /*read_only*/
2603 false, /*O_DIRECT*/
2604 )
Daniel Verkamp6b298582021-08-16 15:37:11 -07002605 .with_context(|| format!("failed to open kernel image {}", kernel_path.display()))?,
Andrew Walbranbc55e302021-07-13 17:35:10 +01002606 ),
2607 Some(Executable::Bios(ref bios_path)) => VmImage::Bios(
Junichi Uekawa7bea39f2021-07-16 14:05:06 +09002608 open_file(bios_path, true /*read_only*/, false /*O_DIRECT*/)
Daniel Verkamp6b298582021-08-16 15:37:11 -07002609 .with_context(|| format!("failed to open bios {}", bios_path.display()))?,
Andrew Walbranbc55e302021-07-13 17:35:10 +01002610 ),
Cody Schuffelen6d1ab502019-05-21 12:12:38 -07002611 _ => panic!("Did not receive a bios or kernel, should be impossible."),
2612 };
2613
Will Deaconc48e7832021-07-30 19:03:06 +01002614 let swiotlb = if let Some(size) = cfg.swiotlb {
2615 Some(
2616 size.checked_mul(1024 * 1024)
Daniel Verkamp6b298582021-08-16 15:37:11 -07002617 .ok_or_else(|| anyhow!("requested swiotlb size too large"))?,
Will Deaconc48e7832021-07-30 19:03:06 +01002618 )
2619 } else {
2620 match cfg.protected_vm {
Andrew Walbran0bbbb682021-12-13 13:42:07 +00002621 ProtectionType::Protected | ProtectionType::ProtectedWithoutFirmware => {
2622 Some(64 * 1024 * 1024)
2623 }
Will Deaconc48e7832021-07-30 19:03:06 +01002624 ProtectionType::Unprotected => None,
2625 }
2626 };
2627
Zach Reiznera90649a2021-03-31 12:56:08 -07002628 Ok(VmComponents {
Daniel Verkamp6a847062019-11-26 13:16:35 -08002629 memory_size: cfg
2630 .memory
2631 .unwrap_or(256)
2632 .checked_mul(1024 * 1024)
Daniel Verkamp6b298582021-08-16 15:37:11 -07002633 .ok_or_else(|| anyhow!("requested memory size too large"))?,
Will Deaconc48e7832021-07-30 19:03:06 +01002634 swiotlb,
Dylan Reid059a1882018-07-23 17:58:09 -07002635 vcpu_count: cfg.vcpu_count.unwrap_or(1),
Daniel Verkamp107edb32019-04-05 09:58:48 -07002636 vcpu_affinity: cfg.vcpu_affinity.clone(),
Daniel Verkamp8a72afc2021-03-15 17:55:52 -07002637 cpu_clusters: cfg.cpu_clusters.clone(),
2638 cpu_capacity: cfg.cpu_capacity.clone(),
Suleiman Souhlal015c3c12020-10-07 14:15:41 +09002639 no_smt: cfg.no_smt,
Sergey Senozhatsky1e369c52021-04-13 20:23:51 +09002640 hugepages: cfg.hugepages,
Cody Schuffelen6d1ab502019-05-21 12:12:38 -07002641 vm_image,
Tristan Muntsinger4133b012018-12-21 16:01:56 -08002642 android_fstab: cfg
2643 .android_fstab
2644 .as_ref()
Daniel Verkamp6b298582021-08-16 15:37:11 -07002645 .map(|x| {
2646 File::open(x)
2647 .with_context(|| format!("failed to open android fstab file {}", x.display()))
2648 })
Tristan Muntsinger4133b012018-12-21 16:01:56 -08002649 .map_or(Ok(None), |v| v.map(Some))?,
Kansho Nishida282115b2019-12-18 13:13:14 +09002650 pstore: cfg.pstore.clone(),
Daniel Verkampe403f5c2018-12-11 16:29:26 -08002651 initrd_image,
Daniel Verkampaac28132018-10-15 14:58:48 -07002652 extra_kernel_params: cfg.params.clone(),
Tomasz Jeznach42644642020-05-20 23:27:59 -07002653 acpi_sdts: cfg
2654 .acpi_tables
2655 .iter()
Daniel Verkamp6b298582021-08-16 15:37:11 -07002656 .map(|path| {
2657 SDT::from_file(path)
2658 .with_context(|| format!("failed to open ACPI file {}", path.display()))
2659 })
Tomasz Jeznach42644642020-05-20 23:27:59 -07002660 .collect::<Result<Vec<SDT>>>()?,
Kansho Nishidaab205af2020-08-13 18:17:50 +09002661 rt_cpus: cfg.rt_cpus.clone(),
Suleiman Souhlal63630e82021-02-18 11:53:11 +09002662 delay_rt: cfg.delay_rt,
Will Deacon7d2b8ac2020-10-06 18:51:12 +01002663 protected_vm: cfg.protected_vm,
Keiichi Watanabec5262e92020-10-21 15:57:33 +09002664 #[cfg(all(target_arch = "x86_64", feature = "gdb"))]
Zach Reiznera90649a2021-03-31 12:56:08 -07002665 gdb: None,
Tomasz Jeznachccb26942021-03-30 22:44:11 -07002666 dmi_path: cfg.dmi_path.clone(),
Tomasz Jeznachd93c29f2021-04-12 11:00:24 -07002667 no_legacy: cfg.no_legacy,
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +08002668 host_cpu_topology: cfg.host_cpu_topology,
Zach Reiznera90649a2021-03-31 12:56:08 -07002669 })
2670}
2671
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08002672pub enum ExitState {
2673 Reset,
2674 Stop,
2675}
2676
2677pub fn run_config(cfg: Config) -> Result<ExitState> {
Zach Reiznerdc748482021-04-14 13:59:30 -07002678 let components = setup_vm_components(&cfg)?;
2679
2680 let guest_mem_layout =
Daniel Verkamp6b298582021-08-16 15:37:11 -07002681 Arch::guest_memory_layout(&components).context("failed to create guest memory layout")?;
2682 let guest_mem = GuestMemory::new(&guest_mem_layout).context("failed to create guest memory")?;
Zach Reiznerdc748482021-04-14 13:59:30 -07002683 let mut mem_policy = MemoryPolicy::empty();
2684 if components.hugepages {
2685 mem_policy |= MemoryPolicy::USE_HUGEPAGES;
2686 }
Quentin Perret26203802021-12-02 09:48:43 +00002687 guest_mem.set_memory_policy(mem_policy);
Daniel Verkamp6b298582021-08-16 15:37:11 -07002688 let kvm = Kvm::new_with_path(&cfg.kvm_device_path).context("failed to create kvm")?;
Andrew Walbran00f1c9f2021-12-10 17:13:08 +00002689 let vm = KvmVm::new(&kvm, guest_mem, components.protected_vm).context("failed to create vm")?;
Daniel Verkamp6b298582021-08-16 15:37:11 -07002690 let vm_clone = vm.try_clone().context("failed to clone vm")?;
Zach Reiznerdc748482021-04-14 13:59:30 -07002691
2692 enum KvmIrqChip {
2693 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
2694 Split(KvmSplitIrqChip),
2695 Kernel(KvmKernelIrqChip),
2696 }
2697
2698 impl KvmIrqChip {
2699 fn as_mut(&mut self) -> &mut dyn IrqChipArch {
2700 match self {
2701 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
2702 KvmIrqChip::Split(i) => i,
2703 KvmIrqChip::Kernel(i) => i,
2704 }
2705 }
2706 }
2707
2708 let ioapic_host_tube;
2709 let mut irq_chip = if cfg.split_irqchip {
2710 #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
2711 unimplemented!("KVM split irqchip mode only supported on x86 processors");
2712 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
2713 {
Daniel Verkamp6b298582021-08-16 15:37:11 -07002714 let (host_tube, ioapic_device_tube) = Tube::pair().context("failed to create tube")?;
Zach Reiznerdc748482021-04-14 13:59:30 -07002715 ioapic_host_tube = Some(host_tube);
2716 KvmIrqChip::Split(
2717 KvmSplitIrqChip::new(
2718 vm_clone,
2719 components.vcpu_count,
2720 ioapic_device_tube,
2721 Some(120),
2722 )
Daniel Verkamp6b298582021-08-16 15:37:11 -07002723 .context("failed to create IRQ chip")?,
Zach Reiznerdc748482021-04-14 13:59:30 -07002724 )
2725 }
2726 } else {
2727 ioapic_host_tube = None;
2728 KvmIrqChip::Kernel(
Daniel Verkamp6b298582021-08-16 15:37:11 -07002729 KvmKernelIrqChip::new(vm_clone, components.vcpu_count)
2730 .context("failed to create IRQ chip")?,
Zach Reiznerdc748482021-04-14 13:59:30 -07002731 )
2732 };
2733
2734 run_vm::<KvmVcpu, KvmVm>(cfg, components, vm, irq_chip.as_mut(), ioapic_host_tube)
2735}
2736
2737fn run_vm<Vcpu, V>(
Zach Reiznera90649a2021-03-31 12:56:08 -07002738 cfg: Config,
2739 #[allow(unused_mut)] mut components: VmComponents,
Zach Reiznerdc748482021-04-14 13:59:30 -07002740 mut vm: V,
2741 irq_chip: &mut dyn IrqChipArch,
2742 ioapic_host_tube: Option<Tube>,
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08002743) -> Result<ExitState>
Zach Reiznera90649a2021-03-31 12:56:08 -07002744where
2745 Vcpu: VcpuArch + 'static,
2746 V: VmArch + 'static,
Zach Reiznera90649a2021-03-31 12:56:08 -07002747{
2748 if cfg.sandbox {
2749 // Printing something to the syslog before entering minijail so that libc's syslogger has a
2750 // chance to open files necessary for its operation, like `/etc/localtime`. After jailing,
2751 // access to those files will not be possible.
2752 info!("crosvm entering multiprocess mode");
2753 }
2754
Daniel Verkampf1439d42021-05-21 13:55:10 -07002755 #[cfg(feature = "usb")]
Zach Reiznera90649a2021-03-31 12:56:08 -07002756 let (usb_control_tube, usb_provider) =
Daniel Verkamp6b298582021-08-16 15:37:11 -07002757 HostBackendDeviceProvider::new().context("failed to create usb provider")?;
Daniel Verkampf1439d42021-05-21 13:55:10 -07002758
Zach Reiznera90649a2021-03-31 12:56:08 -07002759 // Masking signals is inherently dangerous, since this can persist across clones/execs. Do this
2760 // before any jailed devices have been spawned, so that we can catch any of them that fail very
2761 // quickly.
Daniel Verkamp6b298582021-08-16 15:37:11 -07002762 let sigchld_fd = SignalFd::new(libc::SIGCHLD).context("failed to create signalfd")?;
Dylan Reid059a1882018-07-23 17:58:09 -07002763
Zach Reiznera60744b2019-02-13 17:33:32 -08002764 let control_server_socket = match &cfg.socket_path {
2765 Some(path) => Some(UnlinkUnixSeqpacketListener(
Daniel Verkamp6b298582021-08-16 15:37:11 -07002766 UnixSeqpacketListener::bind(path).context("failed to create control server")?,
Zach Reiznera60744b2019-02-13 17:33:32 -08002767 )),
2768 None => None,
Dylan Reid059a1882018-07-23 17:58:09 -07002769 };
Zach Reiznera60744b2019-02-13 17:33:32 -08002770
Zach Reiznera90649a2021-03-31 12:56:08 -07002771 let mut control_tubes = Vec::new();
2772
2773 #[cfg(all(target_arch = "x86_64", feature = "gdb"))]
2774 if let Some(port) = cfg.gdb {
2775 // GDB needs a control socket to interrupt vcpus.
Daniel Verkamp6b298582021-08-16 15:37:11 -07002776 let (gdb_host_tube, gdb_control_tube) = Tube::pair().context("failed to create tube")?;
Zach Reiznera90649a2021-03-31 12:56:08 -07002777 control_tubes.push(TaggedControlTube::Vm(gdb_host_tube));
2778 components.gdb = Some((port, gdb_control_tube));
2779 }
2780
Chirantan Ekbote2ee9dcd2021-05-26 18:21:44 +09002781 for wl_cfg in &cfg.vhost_user_wl {
2782 let wayland_host_tube = UnixSeqpacket::connect(&wl_cfg.vm_tube)
2783 .map(Tube::new)
Daniel Verkamp6b298582021-08-16 15:37:11 -07002784 .context("failed to connect to wayland tube")?;
Chirantan Ekbote2ee9dcd2021-05-26 18:21:44 +09002785 control_tubes.push(TaggedControlTube::VmMemory(wayland_host_tube));
2786 }
2787
Chirantan Ekbote44292f52021-06-25 18:31:41 +09002788 let mut vhost_user_gpu_tubes = Vec::with_capacity(cfg.vhost_user_gpu.len());
2789 for _ in 0..cfg.vhost_user_gpu.len() {
Daniel Verkamp6b298582021-08-16 15:37:11 -07002790 let (host_tube, device_tube) = Tube::pair().context("failed to create tube")?;
Chirantan Ekbote44292f52021-06-25 18:31:41 +09002791 vhost_user_gpu_tubes.push((
Daniel Verkamp6b298582021-08-16 15:37:11 -07002792 host_tube.try_clone().context("failed to clone tube")?,
Chirantan Ekbote44292f52021-06-25 18:31:41 +09002793 device_tube,
2794 ));
2795 control_tubes.push(TaggedControlTube::VmMemory(host_tube));
2796 }
2797
Daniel Verkamp6b298582021-08-16 15:37:11 -07002798 let (wayland_host_tube, wayland_device_tube) = Tube::pair().context("failed to create tube")?;
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002799 control_tubes.push(TaggedControlTube::VmMemory(wayland_host_tube));
Dylan Reid059a1882018-07-23 17:58:09 -07002800 // Balloon gets a special socket so balloon requests can be forwarded from the main process.
Daniel Verkamp6b298582021-08-16 15:37:11 -07002801 let (balloon_host_tube, balloon_device_tube) = Tube::pair().context("failed to create tube")?;
Hikaru Nishidaaf3f3bb2021-05-21 12:03:54 +09002802 // Set recv timeout to avoid deadlock on sending BalloonControlCommand before guest is ready.
2803 balloon_host_tube
2804 .set_recv_timeout(Some(Duration::from_millis(100)))
Daniel Verkamp6b298582021-08-16 15:37:11 -07002805 .context("failed to create tube")?;
Dylan Reid059a1882018-07-23 17:58:09 -07002806
Daniel Verkamp92f73d72018-12-04 13:17:46 -08002807 // Create one control socket per disk.
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002808 let mut disk_device_tubes = Vec::new();
2809 let mut disk_host_tubes = Vec::new();
Daniel Verkamp92f73d72018-12-04 13:17:46 -08002810 let disk_count = cfg.disks.len();
2811 for _ in 0..disk_count {
Daniel Verkamp6b298582021-08-16 15:37:11 -07002812 let (disk_host_tub, disk_device_tube) = Tube::pair().context("failed to create tube")?;
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002813 disk_host_tubes.push(disk_host_tub);
2814 disk_device_tubes.push(disk_device_tube);
Daniel Verkamp92f73d72018-12-04 13:17:46 -08002815 }
2816
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002817 let mut pmem_device_tubes = Vec::new();
Daniel Verkampe1980a92020-02-07 11:00:55 -08002818 let pmem_count = cfg.pmem_devices.len();
2819 for _ in 0..pmem_count {
Daniel Verkamp6b298582021-08-16 15:37:11 -07002820 let (pmem_host_tube, pmem_device_tube) = Tube::pair().context("failed to create tube")?;
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002821 pmem_device_tubes.push(pmem_device_tube);
2822 control_tubes.push(TaggedControlTube::VmMsync(pmem_host_tube));
Daniel Verkampe1980a92020-02-07 11:00:55 -08002823 }
2824
Daniel Verkamp6b298582021-08-16 15:37:11 -07002825 let (gpu_host_tube, gpu_device_tube) = Tube::pair().context("failed to create tube")?;
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002826 control_tubes.push(TaggedControlTube::VmMemory(gpu_host_tube));
Gurchetan Singh96beafc2019-05-15 09:46:52 -07002827
Zach Reiznerdc748482021-04-14 13:59:30 -07002828 if let Some(ioapic_host_tube) = ioapic_host_tube {
2829 control_tubes.push(TaggedControlTube::VmIrq(ioapic_host_tube));
2830 }
Zhuocheng Dingf2e90bf2019-12-02 15:50:20 +08002831
Chuanxiao Dongbbb32af2020-04-27 16:37:10 +08002832 let battery = if cfg.battery_type.is_some() {
Daniel Verkampcfe49462021-08-19 17:11:05 -07002833 #[cfg_attr(not(feature = "power-monitor-powerd"), allow(clippy::manual_map))]
Alex Lauf408c732020-11-10 18:24:04 +09002834 let jail = match simple_jail(&cfg, "battery")? {
Daniel Verkampcfe49462021-08-19 17:11:05 -07002835 #[cfg_attr(not(feature = "power-monitor-powerd"), allow(unused_mut))]
Alex Lauf408c732020-11-10 18:24:04 +09002836 Some(mut jail) => {
2837 // Setup a bind mount to the system D-Bus socket if the powerd monitor is used.
2838 #[cfg(feature = "power-monitor-powerd")]
2839 {
Fergus Dall51200512021-08-19 12:54:26 +10002840 add_current_user_to_jail(&mut jail)?;
Alex Lauf408c732020-11-10 18:24:04 +09002841
2842 // Create a tmpfs in the device's root directory so that we can bind mount files.
2843 jail.mount_with_data(
2844 Path::new("none"),
2845 Path::new("/"),
2846 "tmpfs",
2847 (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as usize,
2848 "size=67108864",
2849 )?;
2850
2851 let system_bus_socket_path = Path::new("/run/dbus/system_bus_socket");
2852 jail.mount_bind(system_bus_socket_path, system_bus_socket_path, true)?;
2853 }
2854 Some(jail)
2855 }
2856 None => None,
2857 };
2858 (&cfg.battery_type, jail)
Chuanxiao Dongbbb32af2020-04-27 16:37:10 +08002859 } else {
2860 (&cfg.battery_type, None)
2861 };
2862
Lingfeng Yangd6ac1ab2020-01-31 13:55:35 -08002863 let map_request: Arc<Mutex<Option<ExternalMapping>>> = Arc::new(Mutex::new(None));
2864
Keiichi Watanabeeefe7fb2020-11-17 17:58:35 +09002865 let fs_count = cfg
2866 .shared_dirs
2867 .iter()
2868 .filter(|sd| sd.kind == SharedDirKind::FS)
2869 .count();
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002870 let mut fs_device_tubes = Vec::with_capacity(fs_count);
Keiichi Watanabeeefe7fb2020-11-17 17:58:35 +09002871 for _ in 0..fs_count {
Daniel Verkamp6b298582021-08-16 15:37:11 -07002872 let (fs_host_tube, fs_device_tube) = Tube::pair().context("failed to create tube")?;
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08002873 control_tubes.push(TaggedControlTube::Fs(fs_host_tube));
2874 fs_device_tubes.push(fs_device_tube);
Keiichi Watanabeeefe7fb2020-11-17 17:58:35 +09002875 }
2876
Daniel Verkamp6b298582021-08-16 15:37:11 -07002877 let exit_evt = Event::new().context("failed to create event")?;
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08002878 let reset_evt = Event::new().context("failed to create event")?;
Daniel Verkamp6f4f8222022-01-05 14:09:09 -08002879 let mut sys_allocator = Arch::create_system_allocator(&vm);
Ryo Hashimoto8f9dc1d2021-08-18 19:07:29 +09002880
2881 // Allocate the ramoops region first. AArch64::build_vm() assumes this.
2882 let ramoops_region = match &components.pstore {
2883 Some(pstore) => Some(
Dennis Kempin65740a62021-10-18 16:46:57 -07002884 arch::pstore::create_memory_region(&mut vm, &mut sys_allocator, pstore)
Daniel Verkamp6b298582021-08-16 15:37:11 -07002885 .context("failed to allocate pstore region")?,
Ryo Hashimoto8f9dc1d2021-08-18 19:07:29 +09002886 ),
2887 None => None,
2888 };
2889
Daniel Verkamp891ea3e2022-01-04 12:35:55 -08002890 let phys_max_addr = (1u64 << vm.get_guest_phys_addr_bits()) - 1;
Tomasz Nowickiab86d522021-09-22 05:50:46 +00002891 let mut devices = create_devices(
Zach Reiznerdc748482021-04-14 13:59:30 -07002892 &cfg,
2893 &mut vm,
2894 &mut sys_allocator,
2895 &exit_evt,
Zide Chen71435c12021-03-03 15:02:02 -08002896 phys_max_addr,
Zach Reiznerdc748482021-04-14 13:59:30 -07002897 &mut control_tubes,
2898 wayland_device_tube,
2899 gpu_device_tube,
Chirantan Ekbote44292f52021-06-25 18:31:41 +09002900 vhost_user_gpu_tubes,
Zach Reiznerdc748482021-04-14 13:59:30 -07002901 balloon_device_tube,
2902 &mut disk_device_tubes,
2903 &mut pmem_device_tubes,
2904 &mut fs_device_tubes,
Daniel Verkampf1439d42021-05-21 13:55:10 -07002905 #[cfg(feature = "usb")]
Zach Reiznerdc748482021-04-14 13:59:30 -07002906 usb_provider,
2907 Arc::clone(&map_request),
2908 )?;
2909
Peter Fangc2bba082021-04-19 18:40:24 -07002910 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
Tomasz Nowickiab86d522021-09-22 05:50:46 +00002911 for device in devices
2912 .iter_mut()
2913 .filter_map(|(dev, _)| dev.as_pci_device_mut())
2914 {
Peter Fangc2bba082021-04-19 18:40:24 -07002915 let sdts = device
2916 .generate_acpi(components.acpi_sdts)
2917 .or_else(|| {
2918 error!("ACPI table generation error");
2919 None
2920 })
Daniel Verkamp6b298582021-08-16 15:37:11 -07002921 .ok_or_else(|| anyhow!("failed to generate ACPI table"))?;
Peter Fangc2bba082021-04-19 18:40:24 -07002922 components.acpi_sdts = sdts;
2923 }
2924
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +08002925 // KVM_CREATE_VCPU uses apic id for x86 and uses cpu id for others.
2926 let mut kvm_vcpu_ids = Vec::new();
2927
Kuo-Hsin Yang6139da62021-04-14 16:55:24 +08002928 #[cfg_attr(not(feature = "direct"), allow(unused_mut))]
Zach Reiznerdc748482021-04-14 13:59:30 -07002929 let mut linux = Arch::build_vm::<V, Vcpu>(
Trent Begin17ccaad2019-04-17 13:51:25 -06002930 components,
Zach Reiznerdc748482021-04-14 13:59:30 -07002931 &exit_evt,
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08002932 &reset_evt,
Zach Reiznerdc748482021-04-14 13:59:30 -07002933 &mut sys_allocator,
Trent Begin17ccaad2019-04-17 13:51:25 -06002934 &cfg.serial_parameters,
Matt Delco45caf912019-11-13 08:11:09 -08002935 simple_jail(&cfg, "serial")?,
Chuanxiao Dongbbb32af2020-04-27 16:37:10 +08002936 battery,
Zach Reiznera90649a2021-03-31 12:56:08 -07002937 vm,
Ryo Hashimoto8f9dc1d2021-08-18 19:07:29 +09002938 ramoops_region,
Tomasz Nowickiab86d522021-09-22 05:50:46 +00002939 devices,
Zach Reiznerdc748482021-04-14 13:59:30 -07002940 irq_chip,
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +08002941 &mut kvm_vcpu_ids,
Trent Begin17ccaad2019-04-17 13:51:25 -06002942 )
Daniel Verkamp6b298582021-08-16 15:37:11 -07002943 .context("the architecture failed to build the vm")?;
Lepton Wu60893882018-11-21 11:06:18 -08002944
Daniel Verkamp1286b482021-11-30 15:14:16 -08002945 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
2946 {
2947 // Create Pcie Root Port
2948 let pcie_root_port = Arc::new(Mutex::new(PcieRootPort::new()));
2949 let (msi_host_tube, msi_device_tube) = Tube::pair().context("failed to create tube")?;
2950 control_tubes.push(TaggedControlTube::VmIrq(msi_host_tube));
2951 let sec_bus = (1..255)
2952 .find(|&bus_num| sys_allocator.pci_bus_empty(bus_num))
2953 .context("failed to find empty bus for Pci hotplug")?;
2954 let pci_bridge = Box::new(PciBridge::new(
2955 pcie_root_port.clone(),
2956 msi_device_tube,
2957 0,
2958 sec_bus,
2959 ));
2960 Arch::register_pci_device(&mut linux, pci_bridge, None, &mut sys_allocator)
2961 .context("Failed to configure pci bridge device")?;
2962 linux.hotplug_bus.push(pcie_root_port);
2963 }
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08002964
Tomasz Jeznach3ce74762021-02-26 01:01:53 -08002965 #[cfg(feature = "direct")]
2966 if let Some(pmio) = &cfg.direct_pmio {
Daniel Verkamp6b298582021-08-16 15:37:11 -07002967 let direct_io = Arc::new(
2968 devices::DirectIo::new(&pmio.path, false).context("failed to open direct io device")?,
2969 );
Tomasz Jeznach3ce74762021-02-26 01:01:53 -08002970 for range in pmio.ranges.iter() {
2971 linux
2972 .io_bus
Junichi Uekawab180f9c2021-12-07 09:21:36 +09002973 .insert_sync(direct_io.clone(), range.base, range.len)
Tomasz Jeznach3ce74762021-02-26 01:01:53 -08002974 .unwrap();
2975 }
2976 };
2977
Tomasz Jeznach7271f752021-03-04 01:44:06 -08002978 #[cfg(feature = "direct")]
Tomasz Jeznach9e6c6332021-05-27 21:49:14 -07002979 if let Some(mmio) = &cfg.direct_mmio {
Xiong Zhang46471a02021-11-12 00:34:42 +08002980 let direct_mmio = Arc::new(
Junichi Uekawab180f9c2021-12-07 09:21:36 +09002981 devices::DirectMmio::new(&mmio.path, false, &mmio.ranges)
Xiong Zhang46471a02021-11-12 00:34:42 +08002982 .context("failed to open direct mmio device")?,
Daniel Verkamp6b298582021-08-16 15:37:11 -07002983 );
Xiong Zhang46471a02021-11-12 00:34:42 +08002984
Tomasz Jeznach9e6c6332021-05-27 21:49:14 -07002985 for range in mmio.ranges.iter() {
2986 linux
2987 .mmio_bus
Junichi Uekawab180f9c2021-12-07 09:21:36 +09002988 .insert_sync(direct_mmio.clone(), range.base, range.len)
Tomasz Jeznach9e6c6332021-05-27 21:49:14 -07002989 .unwrap();
2990 }
2991 };
2992
2993 #[cfg(feature = "direct")]
Tomasz Jeznach7271f752021-03-04 01:44:06 -08002994 let mut irqs = Vec::new();
2995
2996 #[cfg(feature = "direct")]
2997 for irq in &cfg.direct_level_irq {
Zach Reiznerdc748482021-04-14 13:59:30 -07002998 if !sys_allocator.reserve_irq(*irq) {
Tomasz Jeznach7271f752021-03-04 01:44:06 -08002999 warn!("irq {} already reserved.", irq);
3000 }
Daniel Verkamp6b298582021-08-16 15:37:11 -07003001 let trigger = Event::new().context("failed to create event")?;
3002 let resample = Event::new().context("failed to create event")?;
Tomasz Jeznach7271f752021-03-04 01:44:06 -08003003 linux
3004 .irq_chip
3005 .register_irq_event(*irq, &trigger, Some(&resample))
3006 .unwrap();
Daniel Verkamp6b298582021-08-16 15:37:11 -07003007 let direct_irq = devices::DirectIrq::new(trigger, Some(resample))
3008 .context("failed to enable interrupt forwarding")?;
3009 direct_irq
3010 .irq_enable(*irq)
3011 .context("failed to enable interrupt forwarding")?;
Tomasz Jeznach7271f752021-03-04 01:44:06 -08003012 irqs.push(direct_irq);
3013 }
3014
3015 #[cfg(feature = "direct")]
3016 for irq in &cfg.direct_edge_irq {
Zach Reiznerdc748482021-04-14 13:59:30 -07003017 if !sys_allocator.reserve_irq(*irq) {
Tomasz Jeznach7271f752021-03-04 01:44:06 -08003018 warn!("irq {} already reserved.", irq);
3019 }
Daniel Verkamp6b298582021-08-16 15:37:11 -07003020 let trigger = Event::new().context("failed to create event")?;
Tomasz Jeznach7271f752021-03-04 01:44:06 -08003021 linux
3022 .irq_chip
3023 .register_irq_event(*irq, &trigger, None)
3024 .unwrap();
Daniel Verkamp6b298582021-08-16 15:37:11 -07003025 let direct_irq = devices::DirectIrq::new(trigger, None)
3026 .context("failed to enable interrupt forwarding")?;
3027 direct_irq
3028 .irq_enable(*irq)
3029 .context("failed to enable interrupt forwarding")?;
Tomasz Jeznach7271f752021-03-04 01:44:06 -08003030 irqs.push(direct_irq);
3031 }
3032
Daniel Verkamp6b298582021-08-16 15:37:11 -07003033 let gralloc = RutabagaGralloc::new().context("failed to create gralloc")?;
Daniel Verkamp92f73d72018-12-04 13:17:46 -08003034 run_control(
3035 linux,
Zach Reiznerdc748482021-04-14 13:59:30 -07003036 sys_allocator,
Zach Reiznera60744b2019-02-13 17:33:32 -08003037 control_server_socket,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003038 control_tubes,
3039 balloon_host_tube,
3040 &disk_host_tubes,
Daniel Verkampf1439d42021-05-21 13:55:10 -07003041 #[cfg(feature = "usb")]
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003042 usb_control_tube,
Zach Reiznerdc748482021-04-14 13:59:30 -07003043 exit_evt,
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08003044 reset_evt,
Daniel Verkamp92f73d72018-12-04 13:17:46 -08003045 sigchld_fd,
Steven Richmanf32d0b42020-06-20 21:45:32 -07003046 cfg.sandbox,
Lingfeng Yangd6ac1ab2020-01-31 13:55:35 -08003047 Arc::clone(&map_request),
Gurchetan Singh293913c2020-12-09 10:44:13 -08003048 gralloc,
Yusuke Sato31e136a2021-08-18 11:51:38 -07003049 cfg.per_vm_core_scheduling,
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +08003050 cfg.host_cpu_topology,
3051 kvm_vcpu_ids,
Daniel Verkamp92f73d72018-12-04 13:17:46 -08003052 )
Dylan Reid0ed91ab2018-05-31 15:42:18 -07003053}
3054
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08003055fn get_hp_bus<V: VmArch, Vcpu: VcpuArch>(
3056 linux: &RunnableLinuxVm<V, Vcpu>,
3057 host_addr: PciAddress,
3058) -> Result<(Arc<Mutex<dyn HotPlugBus>>, u8)> {
3059 for hp_bus in linux.hotplug_bus.iter() {
3060 if let Some(number) = hp_bus.lock().is_match(host_addr) {
3061 return Ok((hp_bus.clone(), number));
3062 }
3063 }
3064 Err(anyhow!("Failed to find a suitable hotplug bus"))
3065}
3066
Xiong Zhang8c9fe3e2021-04-12 15:07:17 +08003067#[allow(dead_code)]
3068fn add_vfio_device<V: VmArch, Vcpu: VcpuArch>(
3069 linux: &mut RunnableLinuxVm<V, Vcpu>,
3070 sys_allocator: &mut SystemAllocator,
3071 cfg: &Config,
3072 control_tubes: &mut Vec<TaggedControlTube>,
3073 vfio_path: &Path,
3074) -> Result<()> {
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08003075 let host_os_str = vfio_path
3076 .file_name()
3077 .ok_or_else(|| anyhow!("failed to parse or find vfio path"))?;
3078 let host_str = host_os_str
3079 .to_str()
3080 .ok_or_else(|| anyhow!("failed to parse or find vfio path"))?;
3081 let host_addr = PciAddress::from_string(host_str);
3082
3083 let (hp_bus, bus_num) = get_hp_bus(linux, host_addr)?;
3084
Xiong Zhang8c9fe3e2021-04-12 15:07:17 +08003085 let mut endpoints: BTreeMap<u32, Arc<Mutex<VfioContainer>>> = BTreeMap::new();
3086 let (vfio_pci_device, jail) = create_vfio_device(
3087 cfg,
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08003088 &linux.vm,
Xiong Zhang8c9fe3e2021-04-12 15:07:17 +08003089 sys_allocator,
3090 control_tubes,
3091 vfio_path,
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08003092 Some(bus_num),
Xiong Zhang8c9fe3e2021-04-12 15:07:17 +08003093 &mut endpoints,
3094 false,
3095 )?;
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08003096
3097 let pci_address = Arch::register_pci_device(linux, vfio_pci_device, jail, sys_allocator)
Daniel Verkamp6b298582021-08-16 15:37:11 -07003098 .context("Failed to configure pci hotplug device")?;
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08003099
Daniel Verkamp6b298582021-08-16 15:37:11 -07003100 let host_os_str = vfio_path
3101 .file_name()
3102 .ok_or_else(|| anyhow!("failed to parse or find vfio path"))?;
3103 let host_str = host_os_str
3104 .to_str()
3105 .ok_or_else(|| anyhow!("failed to parse or find vfio path"))?;
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08003106 let host_addr = PciAddress::from_string(host_str);
3107 let host_key = HostHotPlugKey::Vfio { host_addr };
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08003108 let mut hp_bus = hp_bus.lock();
3109 hp_bus.add_hotplug_device(host_key, pci_address);
3110 hp_bus.hot_plug(pci_address);
3111 Ok(())
Xiong Zhang8c9fe3e2021-04-12 15:07:17 +08003112}
3113
3114#[allow(dead_code)]
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08003115fn remove_vfio_device<V: VmArch, Vcpu: VcpuArch>(
3116 linux: &RunnableLinuxVm<V, Vcpu>,
Xiong Zhang2d45b912021-05-13 16:22:25 +08003117 sys_allocator: &mut SystemAllocator,
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08003118 vfio_path: &Path,
3119) -> Result<()> {
Daniel Verkamp6b298582021-08-16 15:37:11 -07003120 let host_os_str = vfio_path
3121 .file_name()
3122 .ok_or_else(|| anyhow!("failed to parse or find vfio path"))?;
3123 let host_str = host_os_str
3124 .to_str()
3125 .ok_or_else(|| anyhow!("failed to parse or find vfio path"))?;
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08003126 let host_addr = PciAddress::from_string(host_str);
3127 let host_key = HostHotPlugKey::Vfio { host_addr };
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08003128 for hp_bus in linux.hotplug_bus.iter() {
3129 let mut hp_bus_lock = hp_bus.lock();
3130 if let Some(pci_addr) = hp_bus_lock.get_hotplug_device(host_key) {
3131 hp_bus_lock.hot_unplug(pci_addr);
Xiong Zhang2d45b912021-05-13 16:22:25 +08003132 sys_allocator.release_pci(pci_addr.bus, pci_addr.dev, pci_addr.func);
Xiong Zhangf82f2dc2021-05-21 16:54:12 +08003133 return Ok(());
3134 }
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08003135 }
3136
Daniel Verkamp6b298582021-08-16 15:37:11 -07003137 Err(anyhow!("HotPlugBus hasn't been implemented"))
Xiong Zhang9fadc3f2021-06-07 14:16:45 +08003138}
Xiong Zhang8c9fe3e2021-04-12 15:07:17 +08003139
Daniel Verkamp29409802021-02-24 14:46:19 -08003140/// Signals all running VCPUs to vmexit, sends VcpuControl message to each VCPU tube, and tells
3141/// `irq_chip` to stop blocking halted VCPUs. The channel message is set first because both the
Steven Richman11dc6712020-09-02 15:39:14 -07003142/// signal and the irq_chip kick could cause the VCPU thread to continue through the VCPU run
3143/// loop.
3144fn kick_all_vcpus(
3145 vcpu_handles: &[(JoinHandle<()>, mpsc::Sender<vm_control::VcpuControl>)],
Zach Reiznerdc748482021-04-14 13:59:30 -07003146 irq_chip: &dyn IrqChip,
Daniel Verkamp29409802021-02-24 14:46:19 -08003147 message: VcpuControl,
Steven Richman11dc6712020-09-02 15:39:14 -07003148) {
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003149 for (handle, tube) in vcpu_handles {
Daniel Verkamp29409802021-02-24 14:46:19 -08003150 if let Err(e) = tube.send(message.clone()) {
3151 error!("failed to send VcpuControl: {}", e);
Steven Richman11dc6712020-09-02 15:39:14 -07003152 }
3153 let _ = handle.kill(SIGRTMIN() + 0);
3154 }
3155 irq_chip.kick_halted_vcpus();
3156}
3157
Zach Reiznerdc748482021-04-14 13:59:30 -07003158fn run_control<V: VmArch + 'static, Vcpu: VcpuArch + 'static>(
3159 mut linux: RunnableLinuxVm<V, Vcpu>,
3160 mut sys_allocator: SystemAllocator,
Zach Reiznera60744b2019-02-13 17:33:32 -08003161 control_server_socket: Option<UnlinkUnixSeqpacketListener>,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003162 mut control_tubes: Vec<TaggedControlTube>,
3163 balloon_host_tube: Tube,
3164 disk_host_tubes: &[Tube],
Daniel Verkampf1439d42021-05-21 13:55:10 -07003165 #[cfg(feature = "usb")] usb_control_tube: Tube,
Zach Reiznerdc748482021-04-14 13:59:30 -07003166 exit_evt: Event,
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08003167 reset_evt: Event,
Zach Reizner55a9e502018-10-03 10:22:32 -07003168 sigchld_fd: SignalFd,
Lepton Wu20333e42019-03-14 10:48:03 -07003169 sandbox: bool,
Lingfeng Yangd6ac1ab2020-01-31 13:55:35 -08003170 map_request: Arc<Mutex<Option<ExternalMapping>>>,
Gurchetan Singh293913c2020-12-09 10:44:13 -08003171 mut gralloc: RutabagaGralloc,
Yusuke Sato31e136a2021-08-18 11:51:38 -07003172 enable_per_vm_core_scheduling: bool,
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +08003173 host_cpu_topology: bool,
3174 kvm_vcpu_ids: Vec<usize>,
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08003175) -> Result<ExitState> {
Zach Reizner5bed0d22018-03-28 02:31:11 -07003176 #[derive(PollToken)]
3177 enum Token {
3178 Exit,
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08003179 Reset,
Chuanxiao Dong546f01c2020-02-12 21:58:47 +08003180 Suspend,
Zach Reizner5bed0d22018-03-28 02:31:11 -07003181 ChildSignal,
Colin Downs-Razoukbd532762020-09-08 15:49:35 -07003182 IrqFd { index: IrqEventIndex },
Zach Reiznera60744b2019-02-13 17:33:32 -08003183 VmControlServer,
Zach Reizner5bed0d22018-03-28 02:31:11 -07003184 VmControl { index: usize },
3185 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08003186
Zach Reizner19ad1f32019-12-12 18:58:50 -08003187 stdin()
Zach Reizner39aa26b2017-12-12 18:03:23 -08003188 .set_raw_mode()
3189 .expect("failed to set terminal raw mode");
3190
Michael Hoylee392c462020-10-07 03:29:24 -07003191 let wait_ctx = WaitContext::build_with(&[
Zach Reiznerdc748482021-04-14 13:59:30 -07003192 (&exit_evt, Token::Exit),
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08003193 (&reset_evt, Token::Reset),
Chuanxiao Dong546f01c2020-02-12 21:58:47 +08003194 (&linux.suspend_evt, Token::Suspend),
Zach Reiznerb2110be2019-07-23 15:55:03 -07003195 (&sigchld_fd, Token::ChildSignal),
3196 ])
Daniel Verkamp6b298582021-08-16 15:37:11 -07003197 .context("failed to add descriptor to wait context")?;
Zach Reiznerb2110be2019-07-23 15:55:03 -07003198
Zach Reiznera60744b2019-02-13 17:33:32 -08003199 if let Some(socket_server) = &control_server_socket {
Michael Hoylee392c462020-10-07 03:29:24 -07003200 wait_ctx
Zach Reiznera60744b2019-02-13 17:33:32 -08003201 .add(socket_server, Token::VmControlServer)
Daniel Verkamp6b298582021-08-16 15:37:11 -07003202 .context("failed to add descriptor to wait context")?;
Zach Reiznera60744b2019-02-13 17:33:32 -08003203 }
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003204 for (index, socket) in control_tubes.iter().enumerate() {
Michael Hoylee392c462020-10-07 03:29:24 -07003205 wait_ctx
Zach Reizner55a9e502018-10-03 10:22:32 -07003206 .add(socket.as_ref(), Token::VmControl { index })
Daniel Verkamp6b298582021-08-16 15:37:11 -07003207 .context("failed to add descriptor to wait context")?;
Zach Reizner39aa26b2017-12-12 18:03:23 -08003208 }
3209
Steven Richmanf32d0b42020-06-20 21:45:32 -07003210 let events = linux
3211 .irq_chip
3212 .irq_event_tokens()
Daniel Verkamp6b298582021-08-16 15:37:11 -07003213 .context("failed to add descriptor to wait context")?;
Steven Richmanf32d0b42020-06-20 21:45:32 -07003214
Colin Downs-Razoukbd532762020-09-08 15:49:35 -07003215 for (index, _gsi, evt) in events {
Michael Hoylee392c462020-10-07 03:29:24 -07003216 wait_ctx
Colin Downs-Razoukbd532762020-09-08 15:49:35 -07003217 .add(&evt, Token::IrqFd { index })
Daniel Verkamp6b298582021-08-16 15:37:11 -07003218 .context("failed to add descriptor to wait context")?;
Zhuocheng Dingb9f4c9b2019-12-02 15:50:28 +08003219 }
3220
Lepton Wu20333e42019-03-14 10:48:03 -07003221 if sandbox {
3222 // Before starting VCPUs, in case we started with some capabilities, drop them all.
Daniel Verkamp6b298582021-08-16 15:37:11 -07003223 drop_capabilities().context("failed to drop process capabilities")?;
Lepton Wu20333e42019-03-14 10:48:03 -07003224 }
Dmitry Torokhov71006072019-03-06 10:56:51 -08003225
Keiichi Watanabec5262e92020-10-21 15:57:33 +09003226 #[cfg(all(target_arch = "x86_64", feature = "gdb"))]
3227 // Create a channel for GDB thread.
3228 let (to_gdb_channel, from_vcpu_channel) = if linux.gdb.is_some() {
3229 let (s, r) = mpsc::channel();
3230 (Some(s), Some(r))
3231 } else {
3232 (None, None)
3233 };
3234
Steven Richmanf32d0b42020-06-20 21:45:32 -07003235 let mut vcpu_handles = Vec::with_capacity(linux.vcpu_count);
3236 let vcpu_thread_barrier = Arc::new(Barrier::new(linux.vcpu_count + 1));
Steven Richmanf32d0b42020-06-20 21:45:32 -07003237 let use_hypervisor_signals = !linux
3238 .vm
3239 .get_hypervisor()
3240 .check_capability(&HypervisorCap::ImmediateExit);
Zach Reizner304e7312020-09-29 16:00:24 -07003241 setup_vcpu_signal_handler::<Vcpu>(use_hypervisor_signals)?;
Steven Richmanf32d0b42020-06-20 21:45:32 -07003242
Zach Reizner304e7312020-09-29 16:00:24 -07003243 let vcpus: Vec<Option<_>> = match linux.vcpus.take() {
Andrew Walbran9cfdbd92021-01-11 17:40:34 +00003244 Some(vec) => vec.into_iter().map(Some).collect(),
Steven Richmanf32d0b42020-06-20 21:45:32 -07003245 None => iter::repeat_with(|| None).take(linux.vcpu_count).collect(),
3246 };
Yusuke Sato31e136a2021-08-18 11:51:38 -07003247 // Enable core scheduling before creating vCPUs so that the cookie will be
3248 // shared by all vCPU threads.
3249 // TODO(b/199312402): Avoid enabling core scheduling for the crosvm process
3250 // itself for even better performance. Only vCPUs need the feature.
3251 if enable_per_vm_core_scheduling {
3252 if let Err(e) = enable_core_scheduling() {
3253 error!("Failed to enable core scheduling: {}", e);
3254 }
3255 }
Daniel Verkamp94c35272019-09-12 13:31:30 -07003256 for (cpu_id, vcpu) in vcpus.into_iter().enumerate() {
Dylan Reidb0492662019-05-17 14:50:13 -07003257 let (to_vcpu_channel, from_main_channel) = mpsc::channel();
Daniel Verkampc677fb42020-09-08 13:47:49 -07003258 let vcpu_affinity = match linux.vcpu_affinity.clone() {
3259 Some(VcpuAffinity::Global(v)) => v,
3260 Some(VcpuAffinity::PerVcpu(mut m)) => m.remove(&cpu_id).unwrap_or_default(),
3261 None => Default::default(),
3262 };
Zach Reizner55a9e502018-10-03 10:22:32 -07003263 let handle = run_vcpu(
Steven Richmanf32d0b42020-06-20 21:45:32 -07003264 cpu_id,
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +08003265 kvm_vcpu_ids[cpu_id],
Zach Reizner55a9e502018-10-03 10:22:32 -07003266 vcpu,
Daniel Verkamp6b298582021-08-16 15:37:11 -07003267 linux.vm.try_clone().context("failed to clone vm")?,
3268 linux
3269 .irq_chip
3270 .try_box_clone()
3271 .context("failed to clone irqchip")?,
Steven Richmanf32d0b42020-06-20 21:45:32 -07003272 linux.vcpu_count,
Kansho Nishidaab205af2020-08-13 18:17:50 +09003273 linux.rt_cpus.contains(&cpu_id),
Daniel Verkampc677fb42020-09-08 13:47:49 -07003274 vcpu_affinity,
Suleiman Souhlal63630e82021-02-18 11:53:11 +09003275 linux.delay_rt,
Suleiman Souhlal015c3c12020-10-07 14:15:41 +09003276 linux.no_smt,
Zach Reizner55a9e502018-10-03 10:22:32 -07003277 vcpu_thread_barrier.clone(),
Steven Richmanf32d0b42020-06-20 21:45:32 -07003278 linux.has_bios,
Colin Downs-Razouk11bed5e2021-11-02 09:33:14 -07003279 (*linux.io_bus).clone(),
3280 (*linux.mmio_bus).clone(),
Daniel Verkamp6b298582021-08-16 15:37:11 -07003281 exit_evt.try_clone().context("failed to clone event")?,
Steven Richmanf32d0b42020-06-20 21:45:32 -07003282 linux.vm.check_capability(VmCap::PvClockSuspend),
Dylan Reidb0492662019-05-17 14:50:13 -07003283 from_main_channel,
Steven Richmanf32d0b42020-06-20 21:45:32 -07003284 use_hypervisor_signals,
Keiichi Watanabec5262e92020-10-21 15:57:33 +09003285 #[cfg(all(target_arch = "x86_64", feature = "gdb"))]
3286 to_gdb_channel.clone(),
Yusuke Sato31e136a2021-08-18 11:51:38 -07003287 enable_per_vm_core_scheduling,
ZhaoLiu2aaf7ad2021-10-10 18:22:29 +08003288 host_cpu_topology,
Zach Reizner55a9e502018-10-03 10:22:32 -07003289 )?;
Dylan Reidb0492662019-05-17 14:50:13 -07003290 vcpu_handles.push((handle, to_vcpu_channel));
Dylan Reid059a1882018-07-23 17:58:09 -07003291 }
Steven Richmanf32d0b42020-06-20 21:45:32 -07003292
Keiichi Watanabec5262e92020-10-21 15:57:33 +09003293 #[cfg(all(target_arch = "x86_64", feature = "gdb"))]
3294 // Spawn GDB thread.
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003295 if let Some((gdb_port_num, gdb_control_tube)) = linux.gdb.take() {
Keiichi Watanabec5262e92020-10-21 15:57:33 +09003296 let to_vcpu_channels = vcpu_handles
3297 .iter()
3298 .map(|(_handle, channel)| channel.clone())
3299 .collect();
3300 let target = GdbStub::new(
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003301 gdb_control_tube,
Keiichi Watanabec5262e92020-10-21 15:57:33 +09003302 to_vcpu_channels,
3303 from_vcpu_channel.unwrap(), // Must succeed to unwrap()
3304 );
3305 thread::Builder::new()
3306 .name("gdb".to_owned())
3307 .spawn(move || gdb_thread(target, gdb_port_num))
Daniel Verkamp6b298582021-08-16 15:37:11 -07003308 .context("failed to spawn GDB thread")?;
Keiichi Watanabec5262e92020-10-21 15:57:33 +09003309 };
3310
Dylan Reid059a1882018-07-23 17:58:09 -07003311 vcpu_thread_barrier.wait();
3312
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08003313 let mut exit_state = ExitState::Stop;
Charles William Dick54045012021-07-27 19:11:53 +09003314 let mut balloon_stats_id: u64 = 0;
3315
Michael Hoylee392c462020-10-07 03:29:24 -07003316 'wait: loop {
Zach Reizner5bed0d22018-03-28 02:31:11 -07003317 let events = {
Michael Hoylee392c462020-10-07 03:29:24 -07003318 match wait_ctx.wait() {
Zach Reizner39aa26b2017-12-12 18:03:23 -08003319 Ok(v) => v,
3320 Err(e) => {
David Tolnayb4bd00f2019-02-12 17:51:26 -08003321 error!("failed to poll: {}", e);
Zach Reizner39aa26b2017-12-12 18:03:23 -08003322 break;
3323 }
3324 }
3325 };
Zach Reiznera60744b2019-02-13 17:33:32 -08003326
Steven Richmanf32d0b42020-06-20 21:45:32 -07003327 if let Err(e) = linux.irq_chip.process_delayed_irq_events() {
3328 warn!("can't deliver delayed irqs: {}", e);
3329 }
Zhuocheng Dingb9f4c9b2019-12-02 15:50:28 +08003330
Zach Reiznera60744b2019-02-13 17:33:32 -08003331 let mut vm_control_indices_to_remove = Vec::new();
Michael Hoylee392c462020-10-07 03:29:24 -07003332 for event in events.iter().filter(|e| e.is_readable) {
3333 match event.token {
Zach Reizner5bed0d22018-03-28 02:31:11 -07003334 Token::Exit => {
Zach Reizner39aa26b2017-12-12 18:03:23 -08003335 info!("vcpu requested shutdown");
Michael Hoylee392c462020-10-07 03:29:24 -07003336 break 'wait;
Zach Reizner39aa26b2017-12-12 18:03:23 -08003337 }
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08003338 Token::Reset => {
3339 info!("vcpu requested reset");
3340 exit_state = ExitState::Reset;
3341 break 'wait;
3342 }
Chuanxiao Dong546f01c2020-02-12 21:58:47 +08003343 Token::Suspend => {
3344 info!("VM requested suspend");
3345 linux.suspend_evt.read().unwrap();
Zach Reiznerdc748482021-04-14 13:59:30 -07003346 kick_all_vcpus(
3347 &vcpu_handles,
3348 linux.irq_chip.as_irq_chip(),
Daniel Verkamp29409802021-02-24 14:46:19 -08003349 VcpuControl::RunState(VmRunMode::Suspending),
Zach Reiznerdc748482021-04-14 13:59:30 -07003350 );
Chuanxiao Dong546f01c2020-02-12 21:58:47 +08003351 }
Zach Reizner5bed0d22018-03-28 02:31:11 -07003352 Token::ChildSignal => {
Zach Reizner39aa26b2017-12-12 18:03:23 -08003353 // Print all available siginfo structs, then exit the loop.
Daniel Verkamp6b298582021-08-16 15:37:11 -07003354 while let Some(siginfo) =
3355 sigchld_fd.read().context("failed to create signalfd")?
3356 {
Zach Reizner3ba00982019-01-23 19:04:43 -08003357 let pid = siginfo.ssi_pid;
3358 let pid_label = match linux.pid_debug_label_map.get(&pid) {
3359 Some(label) => format!("{} (pid {})", label, pid),
3360 None => format!("pid {}", pid),
3361 };
David Tolnayf5032762018-12-03 10:46:45 -08003362 error!(
3363 "child {} died: signo {}, status {}, code {}",
Zach Reizner3ba00982019-01-23 19:04:43 -08003364 pid_label, siginfo.ssi_signo, siginfo.ssi_status, siginfo.ssi_code
David Tolnayf5032762018-12-03 10:46:45 -08003365 );
Zach Reizner39aa26b2017-12-12 18:03:23 -08003366 }
Michael Hoylee392c462020-10-07 03:29:24 -07003367 break 'wait;
Zach Reizner39aa26b2017-12-12 18:03:23 -08003368 }
Colin Downs-Razoukbd532762020-09-08 15:49:35 -07003369 Token::IrqFd { index } => {
3370 if let Err(e) = linux.irq_chip.service_irq_event(index) {
3371 error!("failed to signal irq {}: {}", index, e);
Zhuocheng Dingb9f4c9b2019-12-02 15:50:28 +08003372 }
3373 }
Zach Reiznera60744b2019-02-13 17:33:32 -08003374 Token::VmControlServer => {
3375 if let Some(socket_server) = &control_server_socket {
3376 match socket_server.accept() {
3377 Ok(socket) => {
Michael Hoylee392c462020-10-07 03:29:24 -07003378 wait_ctx
Zach Reiznera60744b2019-02-13 17:33:32 -08003379 .add(
3380 &socket,
3381 Token::VmControl {
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003382 index: control_tubes.len(),
Zach Reiznera60744b2019-02-13 17:33:32 -08003383 },
3384 )
Daniel Verkamp6b298582021-08-16 15:37:11 -07003385 .context("failed to add descriptor to wait context")?;
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003386 control_tubes.push(TaggedControlTube::Vm(Tube::new(socket)));
Zach Reiznera60744b2019-02-13 17:33:32 -08003387 }
3388 Err(e) => error!("failed to accept socket: {}", e),
3389 }
3390 }
3391 }
Zach Reizner5bed0d22018-03-28 02:31:11 -07003392 Token::VmControl { index } => {
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003393 if let Some(socket) = control_tubes.get(index) {
Jakub Starond99cd0a2019-04-11 14:09:39 -07003394 match socket {
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003395 TaggedControlTube::Vm(tube) => match tube.recv::<VmRequest>() {
Jakub Starond99cd0a2019-04-11 14:09:39 -07003396 Ok(request) => {
3397 let mut run_mode_opt = None;
3398 let response = request.execute(
3399 &mut run_mode_opt,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003400 &balloon_host_tube,
Charles William Dick54045012021-07-27 19:11:53 +09003401 &mut balloon_stats_id,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003402 disk_host_tubes,
Daniel Verkampf1439d42021-05-21 13:55:10 -07003403 #[cfg(feature = "usb")]
3404 Some(&usb_control_tube),
3405 #[cfg(not(feature = "usb"))]
3406 None,
Chuanxiao Dong256be3a2020-04-27 16:39:33 +08003407 &mut linux.bat_control,
Suleiman Souhlal2ac78b92021-02-01 12:33:26 +09003408 &vcpu_handles,
Jakub Starond99cd0a2019-04-11 14:09:39 -07003409 );
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003410 if let Err(e) = tube.send(&response) {
Jakub Starond99cd0a2019-04-11 14:09:39 -07003411 error!("failed to send VmResponse: {}", e);
3412 }
3413 if let Some(run_mode) = run_mode_opt {
3414 info!("control socket changed run mode to {}", run_mode);
3415 match run_mode {
3416 VmRunMode::Exiting => {
Michael Hoylee392c462020-10-07 03:29:24 -07003417 break 'wait;
Jakub Starond99cd0a2019-04-11 14:09:39 -07003418 }
Keiichi Watanabec5262e92020-10-21 15:57:33 +09003419 other => {
Chuanxiao Dong2bbe85c2020-11-12 17:18:07 +08003420 if other == VmRunMode::Running {
Daniel Verkampda4e8a92021-07-21 13:49:02 -07003421 for dev in &linux.resume_notify_devices {
3422 dev.lock().resume_imminent();
3423 }
Chuanxiao Dong546f01c2020-02-12 21:58:47 +08003424 }
Steven Richman11dc6712020-09-02 15:39:14 -07003425 kick_all_vcpus(
3426 &vcpu_handles,
Zach Reiznerdc748482021-04-14 13:59:30 -07003427 linux.irq_chip.as_irq_chip(),
Daniel Verkamp29409802021-02-24 14:46:19 -08003428 VcpuControl::RunState(other),
Steven Richman11dc6712020-09-02 15:39:14 -07003429 );
Zach Reizner6a8fdd92019-01-16 14:38:41 -08003430 }
3431 }
3432 }
Zach Reizner5bed0d22018-03-28 02:31:11 -07003433 }
Jakub Starond99cd0a2019-04-11 14:09:39 -07003434 Err(e) => {
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003435 if let TubeError::Disconnected = e {
Jakub Starond99cd0a2019-04-11 14:09:39 -07003436 vm_control_indices_to_remove.push(index);
3437 } else {
3438 error!("failed to recv VmRequest: {}", e);
3439 }
Zach Reiznera60744b2019-02-13 17:33:32 -08003440 }
Jakub Starond99cd0a2019-04-11 14:09:39 -07003441 },
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003442 TaggedControlTube::VmMemory(tube) => {
3443 match tube.recv::<VmMemoryRequest>() {
3444 Ok(request) => {
3445 let response = request.execute(
3446 &mut linux.vm,
Zach Reiznerdc748482021-04-14 13:59:30 -07003447 &mut sys_allocator,
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003448 Arc::clone(&map_request),
3449 &mut gralloc,
3450 );
3451 if let Err(e) = tube.send(&response) {
3452 error!("failed to send VmMemoryControlResponse: {}", e);
3453 }
3454 }
3455 Err(e) => {
3456 if let TubeError::Disconnected = e {
3457 vm_control_indices_to_remove.push(index);
3458 } else {
3459 error!("failed to recv VmMemoryControlRequest: {}", e);
3460 }
Jakub Starond99cd0a2019-04-11 14:09:39 -07003461 }
3462 }
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003463 }
3464 TaggedControlTube::VmIrq(tube) => match tube.recv::<VmIrqRequest>() {
Xiong Zhang2515b752019-09-19 10:29:02 +08003465 Ok(request) => {
Steven Richmanf32d0b42020-06-20 21:45:32 -07003466 let response = {
3467 let irq_chip = &mut linux.irq_chip;
3468 request.execute(
3469 |setup| match setup {
3470 IrqSetup::Event(irq, ev) => {
Colin Downs-Razoukbd532762020-09-08 15:49:35 -07003471 if let Some(event_index) = irq_chip
3472 .register_irq_event(irq, ev, None)?
3473 {
3474 match wait_ctx.add(
3475 ev,
3476 Token::IrqFd {
3477 index: event_index
3478 },
3479 ) {
3480 Err(e) => {
3481 warn!("failed to add IrqFd to poll context: {}", e);
3482 Err(e)
3483 },
3484 Ok(_) => {
3485 Ok(())
3486 }
3487 }
3488 } else {
3489 Ok(())
3490 }
Steven Richmanf32d0b42020-06-20 21:45:32 -07003491 }
3492 IrqSetup::Route(route) => irq_chip.route_irq(route),
Xiong Zhang4fbc5542021-06-01 11:29:14 +08003493 IrqSetup::UnRegister(irq, ev) => irq_chip.unregister_irq_event(irq, ev),
Steven Richmanf32d0b42020-06-20 21:45:32 -07003494 },
Zach Reiznerdc748482021-04-14 13:59:30 -07003495 &mut sys_allocator,
Steven Richmanf32d0b42020-06-20 21:45:32 -07003496 )
3497 };
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003498 if let Err(e) = tube.send(&response) {
Xiong Zhang2515b752019-09-19 10:29:02 +08003499 error!("failed to send VmIrqResponse: {}", e);
3500 }
3501 }
3502 Err(e) => {
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003503 if let TubeError::Disconnected = e {
Xiong Zhang2515b752019-09-19 10:29:02 +08003504 vm_control_indices_to_remove.push(index);
3505 } else {
3506 error!("failed to recv VmIrqRequest: {}", e);
3507 }
3508 }
3509 },
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003510 TaggedControlTube::VmMsync(tube) => {
3511 match tube.recv::<VmMsyncRequest>() {
3512 Ok(request) => {
3513 let response = request.execute(&mut linux.vm);
3514 if let Err(e) = tube.send(&response) {
3515 error!("failed to send VmMsyncResponse: {}", e);
3516 }
3517 }
3518 Err(e) => {
3519 if let TubeError::Disconnected = e {
3520 vm_control_indices_to_remove.push(index);
3521 } else {
3522 error!("failed to recv VmMsyncRequest: {}", e);
3523 }
Daniel Verkampe1980a92020-02-07 11:00:55 -08003524 }
3525 }
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003526 }
3527 TaggedControlTube::Fs(tube) => match tube.recv::<FsMappingRequest>() {
Keiichi Watanabeeefe7fb2020-11-17 17:58:35 +09003528 Ok(request) => {
3529 let response =
Zach Reiznerdc748482021-04-14 13:59:30 -07003530 request.execute(&mut linux.vm, &mut sys_allocator);
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003531 if let Err(e) = tube.send(&response) {
Keiichi Watanabeeefe7fb2020-11-17 17:58:35 +09003532 error!("failed to send VmResponse: {}", e);
3533 }
3534 }
3535 Err(e) => {
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003536 if let TubeError::Disconnected = e {
Keiichi Watanabeeefe7fb2020-11-17 17:58:35 +09003537 vm_control_indices_to_remove.push(index);
3538 } else {
3539 error!("failed to recv VmResponse: {}", e);
3540 }
3541 }
3542 },
Zach Reizner39aa26b2017-12-12 18:03:23 -08003543 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08003544 }
3545 }
Zach Reizner5bed0d22018-03-28 02:31:11 -07003546 }
3547 }
Zach Reiznera60744b2019-02-13 17:33:32 -08003548
Vikram Auradkarede68c72021-07-01 14:33:54 -07003549 // It's possible more data is readable and buffered while the socket is hungup,
3550 // so don't delete the tube from the poll context until we're sure all the
3551 // data is read.
3552 // Below case covers a condition where we have received a hungup event and the tube is not
3553 // readable.
3554 // In case of readable tube, once all data is read, any attempt to read more data on hungup
3555 // tube should fail. On such failure, we get Disconnected error and index gets added to
3556 // vm_control_indices_to_remove by the time we reach here.
3557 for event in events.iter().filter(|e| e.is_hungup && !e.is_readable) {
3558 if let Token::VmControl { index } = event.token {
3559 vm_control_indices_to_remove.push(index);
Zach Reizner39aa26b2017-12-12 18:03:23 -08003560 }
3561 }
Zach Reiznera60744b2019-02-13 17:33:32 -08003562
3563 // Sort in reverse so the highest indexes are removed first. This removal algorithm
Zide Chen89584072019-11-14 10:33:51 -08003564 // preserves correct indexes as each element is removed.
Daniel Verkamp8c2f0002020-08-31 15:13:35 -07003565 vm_control_indices_to_remove.sort_unstable_by_key(|&k| Reverse(k));
Zach Reiznera60744b2019-02-13 17:33:32 -08003566 vm_control_indices_to_remove.dedup();
3567 for index in vm_control_indices_to_remove {
Michael Hoylee392c462020-10-07 03:29:24 -07003568 // Delete the socket from the `wait_ctx` synchronously. Otherwise, the kernel will do
3569 // this automatically when the FD inserted into the `wait_ctx` is closed after this
Zide Chen89584072019-11-14 10:33:51 -08003570 // if-block, but this removal can be deferred unpredictably. In some instances where the
Michael Hoylee392c462020-10-07 03:29:24 -07003571 // system is under heavy load, we can even get events returned by `wait_ctx` for an FD
Zide Chen89584072019-11-14 10:33:51 -08003572 // that has already been closed. Because the token associated with that spurious event
3573 // now belongs to a different socket, the control loop will start to interact with
3574 // sockets that might not be ready to use. This can cause incorrect hangup detection or
3575 // blocking on a socket that will never be ready. See also: crbug.com/1019986
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003576 if let Some(socket) = control_tubes.get(index) {
Daniel Verkamp6b298582021-08-16 15:37:11 -07003577 wait_ctx
3578 .delete(socket)
3579 .context("failed to remove descriptor from wait context")?;
Zide Chen89584072019-11-14 10:33:51 -08003580 }
3581
3582 // This line implicitly drops the socket at `index` when it gets returned by
3583 // `swap_remove`. After this line, the socket at `index` is not the one from
3584 // `vm_control_indices_to_remove`. Because of this socket's change in index, we need to
Michael Hoylee392c462020-10-07 03:29:24 -07003585 // use `wait_ctx.modify` to change the associated index in its `Token::VmControl`.
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003586 control_tubes.swap_remove(index);
3587 if let Some(tube) = control_tubes.get(index) {
Michael Hoylee392c462020-10-07 03:29:24 -07003588 wait_ctx
Zach Reiznerd49bcdb2021-01-07 08:30:28 -08003589 .modify(tube, EventType::Read, Token::VmControl { index })
Daniel Verkamp6b298582021-08-16 15:37:11 -07003590 .context("failed to add descriptor to wait context")?;
Zach Reiznera60744b2019-02-13 17:33:32 -08003591 }
3592 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08003593 }
3594
Zach Reiznerdc748482021-04-14 13:59:30 -07003595 kick_all_vcpus(
3596 &vcpu_handles,
3597 linux.irq_chip.as_irq_chip(),
Daniel Verkamp29409802021-02-24 14:46:19 -08003598 VcpuControl::RunState(VmRunMode::Exiting),
Zach Reiznerdc748482021-04-14 13:59:30 -07003599 );
Steven Richman11dc6712020-09-02 15:39:14 -07003600 for (handle, _) in vcpu_handles {
3601 if let Err(e) = handle.join() {
3602 error!("failed to join vcpu thread: {:?}", e);
Zach Reizner39aa26b2017-12-12 18:03:23 -08003603 }
3604 }
3605
Daniel Verkamp94c35272019-09-12 13:31:30 -07003606 // Explicitly drop the VM structure here to allow the devices to clean up before the
3607 // control sockets are closed when this function exits.
3608 mem::drop(linux);
3609
Zach Reizner19ad1f32019-12-12 18:58:50 -08003610 stdin()
Zach Reizner39aa26b2017-12-12 18:03:23 -08003611 .set_canon_mode()
3612 .expect("failed to restore canonical mode for terminal");
3613
Dmitry Torokhovf75699f2021-12-03 11:19:13 -08003614 Ok(exit_state)
Zach Reizner39aa26b2017-12-12 18:03:23 -08003615}