Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1 | // 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 | |
| 5 | use std; |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 6 | use std::cmp::min; |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 7 | use std::error; |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 8 | use std::ffi::CStr; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 9 | use std::fmt; |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 10 | use std::fs::{File, OpenOptions}; |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 11 | use std::io::{self, stdin, Read}; |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 12 | use std::mem; |
Chirantan Ekbote | 2d29233 | 2018-11-16 11:35:24 -0800 | [diff] [blame^] | 13 | use std::os::unix::io::FromRawFd; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 14 | use std::os::unix::net::UnixDatagram; |
| 15 | use std::path::{Path, PathBuf}; |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 16 | use std::str; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 17 | use std::sync::atomic::{AtomicBool, Ordering}; |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 18 | use std::sync::{Arc, Barrier}; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 19 | use std::thread; |
| 20 | use std::thread::JoinHandle; |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 21 | use std::time::Duration; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 22 | |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 23 | use libc::{self, c_int}; |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 24 | use rand::distributions::{IndependentSample, Range}; |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 25 | use rand::thread_rng; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 26 | |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 27 | use byteorder::{ByteOrder, LittleEndian}; |
Daniel Verkamp | 56f283b | 2018-10-05 11:40:59 -0700 | [diff] [blame] | 28 | use devices::{self, PciDevice, VirtioPciDevice}; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 29 | use io_jail::{self, Minijail}; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 30 | use kvm::*; |
Jingkui Wang | e13b180 | 2018-10-03 13:04:47 -0700 | [diff] [blame] | 31 | use msg_socket::{MsgReceiver, MsgSender, UnlinkMsgSocket}; |
Jason D. Clinton | 865323d | 2017-09-27 22:04:03 -0600 | [diff] [blame] | 32 | use net_util::Tap; |
Daniel Verkamp | f02fdd1 | 2018-10-10 17:25:14 -0700 | [diff] [blame] | 33 | use qcow::{self, ImageType, QcowFile}; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 34 | use sys_util; |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 35 | use sys_util::*; |
Jason D. Clinton | 865323d | 2017-09-27 22:04:03 -0600 | [diff] [blame] | 36 | use vhost; |
Jingkui Wang | e13b180 | 2018-10-03 13:04:47 -0700 | [diff] [blame] | 37 | use vm_control::{VmRequest, VmResponse}; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 38 | |
| 39 | use Config; |
| 40 | |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 41 | use arch::{self, LinuxArch, RunnableLinuxVm, VirtioDeviceStub, VmComponents}; |
Sonny Rao | ed517d1 | 2018-02-13 22:09:43 -0800 | [diff] [blame] | 42 | |
Sonny Rao | 2ffa0cb | 2018-02-26 17:27:40 -0800 | [diff] [blame] | 43 | #[cfg(any(target_arch = "arm", target_arch = "aarch64"))] |
| 44 | use aarch64::AArch64 as Arch; |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 45 | #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] |
| 46 | use x86_64::X8664arch as Arch; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 47 | |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 48 | #[derive(Debug)] |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 49 | pub enum Error { |
Dylan Reid | 295ccac | 2017-11-06 14:06:24 -0800 | [diff] [blame] | 50 | BalloonDeviceNew(devices::virtio::BalloonError), |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 51 | BlockDeviceNew(sys_util::Error), |
Mark Ryan | 6ed5aea | 2018-04-20 13:52:35 +0100 | [diff] [blame] | 52 | BlockSignal(sys_util::signal::Error), |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 53 | BuildingVm(Box<error::Error>), |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 54 | CloneEventFd(sys_util::Error), |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 55 | CreateEventFd(sys_util::Error), |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 56 | CreatePollContext(sys_util::Error), |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 57 | CreateSignalFd(sys_util::SignalFdError), |
| 58 | CreateSocket(io::Error), |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 59 | CreateTimerFd(sys_util::Error), |
Daniel Verkamp | f02fdd1 | 2018-10-10 17:25:14 -0700 | [diff] [blame] | 60 | DetectImageType(qcow::Error), |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 61 | DeviceJail(io_jail::Error), |
| 62 | DevicePivotRoot(io_jail::Error), |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 63 | Disk(io::Error), |
Stephen Barber | c79de2d | 2018-02-21 14:17:27 -0800 | [diff] [blame] | 64 | DiskImageLock(sys_util::Error), |
Dylan Reid | 2056644 | 2018-04-02 15:06:15 -0700 | [diff] [blame] | 65 | InvalidFdPath, |
Zach Reizner | 579bd2c | 2018-09-14 15:43:33 -0700 | [diff] [blame] | 66 | InvalidWaylandPath, |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 67 | NetDeviceNew(devices::virtio::NetError), |
| 68 | NoVarEmpty, |
| 69 | OpenKernel(PathBuf, io::Error), |
Chirantan Ekbote | ebd5681 | 2018-04-16 19:32:04 -0700 | [diff] [blame] | 70 | P9DeviceNew(devices::virtio::P9Error), |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 71 | PollContextAdd(sys_util::Error), |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 72 | PollContextDelete(sys_util::Error), |
Dylan Reid | 88624f8 | 2018-01-11 09:20:16 -0800 | [diff] [blame] | 73 | QcowDeviceCreate(qcow::Error), |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 74 | ReadLowmemAvailable(io::Error), |
| 75 | ReadLowmemMargin(io::Error), |
Dylan Reid | 0f579cb | 2018-07-09 15:39:34 -0700 | [diff] [blame] | 76 | RegisterBalloon(arch::DeviceRegistrationError), |
| 77 | RegisterBlock(arch::DeviceRegistrationError), |
| 78 | RegisterGpu(arch::DeviceRegistrationError), |
| 79 | RegisterNet(arch::DeviceRegistrationError), |
| 80 | RegisterP9(arch::DeviceRegistrationError), |
| 81 | RegisterRng(arch::DeviceRegistrationError), |
Mark Ryan | 6ed5aea | 2018-04-20 13:52:35 +0100 | [diff] [blame] | 82 | RegisterSignalHandler(sys_util::Error), |
Dylan Reid | 0f579cb | 2018-07-09 15:39:34 -0700 | [diff] [blame] | 83 | RegisterWayland(arch::DeviceRegistrationError), |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 84 | ResetTimerFd(sys_util::Error), |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 85 | RngDeviceNew(devices::virtio::RngError), |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 86 | SettingGidMap(io_jail::Error), |
| 87 | SettingUidMap(io_jail::Error), |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 88 | SignalFd(sys_util::SignalFdError), |
| 89 | SpawnVcpu(io::Error), |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 90 | TimerFd(sys_util::Error), |
Chirantan Ekbote | 2d29233 | 2018-11-16 11:35:24 -0800 | [diff] [blame^] | 91 | ValidateRawFd(sys_util::Error), |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 92 | VhostNetDeviceNew(devices::virtio::vhost::Error), |
| 93 | VhostVsockDeviceNew(devices::virtio::vhost::Error), |
Daniel Verkamp | 56f283b | 2018-10-05 11:40:59 -0700 | [diff] [blame] | 94 | VirtioPciDev(sys_util::Error), |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 95 | WaylandDeviceNew(sys_util::Error), |
Sonny Rao | ed517d1 | 2018-02-13 22:09:43 -0800 | [diff] [blame] | 96 | LoadKernel(Box<error::Error>), |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 97 | } |
| 98 | |
| 99 | impl fmt::Display for Error { |
| 100 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 101 | match self { |
David Tolnay | 5bbbf61 | 2018-12-01 17:49:30 -0800 | [diff] [blame] | 102 | Error::BalloonDeviceNew(e) => write!(f, "failed to create balloon: {:?}", e), |
| 103 | Error::BlockDeviceNew(e) => write!(f, "failed to create block device: {:?}", e), |
| 104 | Error::BlockSignal(e) => write!(f, "failed to block signal: {:?}", e), |
| 105 | Error::BuildingVm(e) => write!(f, "The architecture failed to build the vm: {:?}", e), |
| 106 | Error::CloneEventFd(e) => write!(f, "failed to clone eventfd: {:?}", e), |
| 107 | Error::CreateEventFd(e) => write!(f, "failed to create eventfd: {:?}", e), |
| 108 | Error::CreatePollContext(e) => write!(f, "failed to create poll context: {:?}", e), |
| 109 | Error::CreateSignalFd(e) => write!(f, "failed to create signalfd: {:?}", e), |
| 110 | Error::CreateSocket(e) => write!(f, "failed to create socket: {}", e), |
| 111 | Error::CreateTimerFd(e) => write!(f, "failed to create timerfd: {}", e), |
| 112 | Error::DetectImageType(e) => write!(f, "failed to detect disk image type: {:?}", e), |
| 113 | Error::DeviceJail(e) => write!(f, "failed to jail device: {}", e), |
| 114 | Error::DevicePivotRoot(e) => write!(f, "failed to pivot root device: {}", e), |
| 115 | Error::Disk(e) => write!(f, "failed to load disk image: {}", e), |
| 116 | Error::DiskImageLock(e) => write!(f, "failed to lock disk image: {:?}", e), |
David Tolnay | 5bbbf61 | 2018-12-01 17:49:30 -0800 | [diff] [blame] | 117 | Error::InvalidFdPath => write!(f, "failed parsing a /proc/self/fd/*"), |
| 118 | Error::InvalidWaylandPath => { |
Zach Reizner | 579bd2c | 2018-09-14 15:43:33 -0700 | [diff] [blame] | 119 | write!(f, "wayland socket path has no parent or file name") |
| 120 | } |
David Tolnay | 5bbbf61 | 2018-12-01 17:49:30 -0800 | [diff] [blame] | 121 | Error::NetDeviceNew(e) => write!(f, "failed to set up virtio networking: {:?}", e), |
| 122 | Error::NoVarEmpty => write!(f, "/var/empty doesn't exist, can't jail devices."), |
| 123 | Error::OpenKernel(p, e) => write!(f, "failed to open kernel image {:?}: {}", p, e), |
| 124 | Error::P9DeviceNew(e) => write!(f, "failed to create 9p device: {}", e), |
| 125 | Error::PollContextAdd(e) => write!(f, "failed to add fd to poll context: {:?}", e), |
| 126 | Error::PollContextDelete(e) => { |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 127 | write!(f, "failed to remove fd from poll context: {:?}", e) |
| 128 | } |
David Tolnay | 5bbbf61 | 2018-12-01 17:49:30 -0800 | [diff] [blame] | 129 | Error::QcowDeviceCreate(e) => write!(f, "failed to read qcow formatted file {:?}", e), |
| 130 | Error::ReadLowmemAvailable(e) => write!( |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 131 | f, |
| 132 | "failed to read /sys/kernel/mm/chromeos-low_mem/available: {}", |
| 133 | e |
| 134 | ), |
David Tolnay | 5bbbf61 | 2018-12-01 17:49:30 -0800 | [diff] [blame] | 135 | Error::ReadLowmemMargin(e) => write!( |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 136 | f, |
| 137 | "failed to read /sys/kernel/mm/chromeos-low_mem/margin: {}", |
| 138 | e |
| 139 | ), |
David Tolnay | 5bbbf61 | 2018-12-01 17:49:30 -0800 | [diff] [blame] | 140 | Error::RegisterBalloon(e) => write!(f, "error registering balloon device: {:?}", e), |
| 141 | Error::RegisterBlock(e) => write!(f, "error registering block device: {:?}", e), |
| 142 | Error::RegisterGpu(e) => write!(f, "error registering gpu device: {:?}", e), |
| 143 | Error::RegisterNet(e) => write!(f, "error registering net device: {:?}", e), |
| 144 | Error::RegisterP9(e) => write!(f, "error registering 9p device: {:?}", e), |
| 145 | Error::RegisterRng(e) => write!(f, "error registering rng device: {:?}", e), |
| 146 | Error::RegisterSignalHandler(e) => { |
Mark Ryan | 6ed5aea | 2018-04-20 13:52:35 +0100 | [diff] [blame] | 147 | write!(f, "error registering signal handler: {:?}", e) |
| 148 | } |
David Tolnay | 5bbbf61 | 2018-12-01 17:49:30 -0800 | [diff] [blame] | 149 | Error::RegisterWayland(e) => write!(f, "error registering wayland device: {}", e), |
| 150 | Error::ResetTimerFd(e) => write!(f, "failed to reset timerfd: {}", e), |
| 151 | Error::RngDeviceNew(e) => write!(f, "failed to set up rng: {:?}", e), |
| 152 | Error::SettingGidMap(e) => write!(f, "error setting GID map: {}", e), |
| 153 | Error::SettingUidMap(e) => write!(f, "error setting UID map: {}", e), |
| 154 | Error::SignalFd(e) => write!(f, "failed to read signal fd: {:?}", e), |
| 155 | Error::SpawnVcpu(e) => write!(f, "failed to spawn VCPU thread: {:?}", e), |
| 156 | Error::TimerFd(e) => write!(f, "failed to read timer fd: {:?}", e), |
Chirantan Ekbote | 2d29233 | 2018-11-16 11:35:24 -0800 | [diff] [blame^] | 157 | Error::ValidateRawFd(e) => write!(f, "failed to validate raw fd: {:?}", e), |
David Tolnay | 5bbbf61 | 2018-12-01 17:49:30 -0800 | [diff] [blame] | 158 | Error::VhostNetDeviceNew(e) => write!(f, "failed to set up vhost networking: {:?}", e), |
| 159 | Error::VhostVsockDeviceNew(e) => { |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 160 | write!(f, "failed to set up virtual socket device: {:?}", e) |
| 161 | } |
David Tolnay | 5bbbf61 | 2018-12-01 17:49:30 -0800 | [diff] [blame] | 162 | Error::VirtioPciDev(e) => write!(f, "failed to create virtio pci dev: {}", e), |
| 163 | Error::WaylandDeviceNew(e) => write!(f, "failed to create wayland device: {:?}", e), |
| 164 | Error::LoadKernel(e) => write!(f, "failed to load kernel: {}", e), |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 165 | } |
| 166 | } |
| 167 | } |
| 168 | |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 169 | impl std::error::Error for Error { |
| 170 | fn description(&self) -> &str { |
| 171 | "Some device failure" |
| 172 | } |
| 173 | } |
| 174 | |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 175 | type Result<T> = std::result::Result<T, Error>; |
| 176 | |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 177 | fn create_base_minijail(root: &Path, seccomp_policy: &Path) -> Result<Minijail> { |
| 178 | // All child jails run in a new user namespace without any users mapped, |
| 179 | // they run as nobody unless otherwise configured. |
David Tolnay | 5bbbf61 | 2018-12-01 17:49:30 -0800 | [diff] [blame] | 180 | let mut j = Minijail::new().map_err(Error::DeviceJail)?; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 181 | j.namespace_pids(); |
| 182 | j.namespace_user(); |
| 183 | j.namespace_user_disable_setgroups(); |
| 184 | // Don't need any capabilities. |
| 185 | j.use_caps(0); |
| 186 | // Create a new mount namespace with an empty root FS. |
| 187 | j.namespace_vfs(); |
David Tolnay | 5bbbf61 | 2018-12-01 17:49:30 -0800 | [diff] [blame] | 188 | j.enter_pivot_root(root).map_err(Error::DevicePivotRoot)?; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 189 | // Run in an empty network namespace. |
| 190 | j.namespace_net(); |
| 191 | // Apply the block device seccomp policy. |
| 192 | j.no_new_privs(); |
Stephen Barber | 3b1d8a5 | 2018-01-06 17:34:51 -0800 | [diff] [blame] | 193 | // Use TSYNC only for the side effect of it using SECCOMP_RET_TRAP, which will correctly kill |
| 194 | // the entire device process if a worker thread commits a seccomp violation. |
| 195 | j.set_seccomp_filter_tsync(); |
Zach Reizner | 043ddc5 | 2018-04-03 20:47:21 -0700 | [diff] [blame] | 196 | #[cfg(debug_assertions)] |
| 197 | j.log_seccomp_filter_failures(); |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 198 | j.parse_seccomp_filters(seccomp_policy) |
David Tolnay | 5bbbf61 | 2018-12-01 17:49:30 -0800 | [diff] [blame] | 199 | .map_err(Error::DeviceJail)?; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 200 | j.use_seccomp_filter(); |
| 201 | // Don't do init setup. |
| 202 | j.run_as_init(); |
| 203 | Ok(j) |
| 204 | } |
| 205 | |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 206 | fn create_virtio_devs( |
Daniel Verkamp | aac2813 | 2018-10-15 14:58:48 -0700 | [diff] [blame] | 207 | cfg: Config, |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 208 | mem: &GuestMemory, |
| 209 | _exit_evt: &EventFd, |
| 210 | wayland_device_socket: UnixDatagram, |
| 211 | balloon_device_socket: UnixDatagram, |
Daniel Verkamp | 8eceba3 | 2018-10-18 16:45:13 -0700 | [diff] [blame] | 212 | ) -> std::result::Result<Vec<(Box<PciDevice + 'static>, Option<Minijail>)>, Box<error::Error>> { |
David Tolnay | 5bbbf61 | 2018-12-01 17:49:30 -0800 | [diff] [blame] | 213 | static DEFAULT_PIVOT_ROOT: &str = "/var/empty"; |
Dylan Reid | ef7352f | 2018-05-17 18:47:11 -0700 | [diff] [blame] | 214 | |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 215 | let mut devs = Vec::new(); |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 216 | |
| 217 | // An empty directory for jailed device's pivot root. |
| 218 | let empty_root_path = Path::new(DEFAULT_PIVOT_ROOT); |
| 219 | if cfg.multiprocess && !empty_root_path.exists() { |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 220 | return Err(Box::new(Error::NoVarEmpty)); |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 221 | } |
| 222 | |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 223 | for disk in &cfg.disks { |
Dylan Reid | 2056644 | 2018-04-02 15:06:15 -0700 | [diff] [blame] | 224 | // Special case '/proc/self/fd/*' paths. The FD is already open, just use it. |
| 225 | let mut raw_image: File = if disk.path.parent() == Some(Path::new("/proc/self/fd")) { |
| 226 | if !disk.path.is_file() { |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 227 | return Err(Box::new(Error::InvalidFdPath)); |
Dylan Reid | 2056644 | 2018-04-02 15:06:15 -0700 | [diff] [blame] | 228 | } |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 229 | let raw_fd = disk |
| 230 | .path |
| 231 | .file_name() |
Dylan Reid | 2056644 | 2018-04-02 15:06:15 -0700 | [diff] [blame] | 232 | .and_then(|fd_osstr| fd_osstr.to_str()) |
| 233 | .and_then(|fd_str| fd_str.parse::<c_int>().ok()) |
| 234 | .ok_or(Error::InvalidFdPath)?; |
Chirantan Ekbote | 5f78721 | 2018-05-31 15:31:31 -0700 | [diff] [blame] | 235 | // Safe because we will validate |raw_fd|. |
Chirantan Ekbote | 2d29233 | 2018-11-16 11:35:24 -0800 | [diff] [blame^] | 236 | unsafe { File::from_raw_fd(validate_raw_fd(raw_fd).map_err(Error::ValidateRawFd)?) } |
Dylan Reid | 2056644 | 2018-04-02 15:06:15 -0700 | [diff] [blame] | 237 | } else { |
| 238 | OpenOptions::new() |
| 239 | .read(true) |
Daniel Verkamp | de9ae03 | 2018-08-09 16:26:59 -0700 | [diff] [blame] | 240 | .write(!disk.read_only) |
Dylan Reid | 2056644 | 2018-04-02 15:06:15 -0700 | [diff] [blame] | 241 | .open(&disk.path) |
David Tolnay | 5bbbf61 | 2018-12-01 17:49:30 -0800 | [diff] [blame] | 242 | .map_err(Error::Disk)? |
Dylan Reid | 2056644 | 2018-04-02 15:06:15 -0700 | [diff] [blame] | 243 | }; |
Stephen Barber | c79de2d | 2018-02-21 14:17:27 -0800 | [diff] [blame] | 244 | // Lock the disk image to prevent other crosvm instances from using it. |
Daniel Verkamp | de9ae03 | 2018-08-09 16:26:59 -0700 | [diff] [blame] | 245 | let lock_op = if disk.read_only { |
Stephen Barber | c79de2d | 2018-02-21 14:17:27 -0800 | [diff] [blame] | 246 | FlockOperation::LockShared |
Daniel Verkamp | de9ae03 | 2018-08-09 16:26:59 -0700 | [diff] [blame] | 247 | } else { |
| 248 | FlockOperation::LockExclusive |
Stephen Barber | c79de2d | 2018-02-21 14:17:27 -0800 | [diff] [blame] | 249 | }; |
| 250 | flock(&raw_image, lock_op, true).map_err(Error::DiskImageLock)?; |
| 251 | |
Daniel Verkamp | f02fdd1 | 2018-10-10 17:25:14 -0700 | [diff] [blame] | 252 | let image_type = qcow::detect_image_type(&raw_image).map_err(Error::DetectImageType)?; |
| 253 | let block_box: Box<devices::virtio::VirtioDevice> = match image_type { |
| 254 | ImageType::Raw => { |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 255 | // Access as a raw block device. |
| 256 | Box::new( |
| 257 | devices::virtio::Block::new(raw_image, disk.read_only) |
David Tolnay | 5bbbf61 | 2018-12-01 17:49:30 -0800 | [diff] [blame] | 258 | .map_err(Error::BlockDeviceNew)?, |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 259 | ) |
Dylan Reid | 88624f8 | 2018-01-11 09:20:16 -0800 | [diff] [blame] | 260 | } |
Daniel Verkamp | f02fdd1 | 2018-10-10 17:25:14 -0700 | [diff] [blame] | 261 | ImageType::Qcow2 => { |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 262 | // Valid qcow header present |
David Tolnay | 5bbbf61 | 2018-12-01 17:49:30 -0800 | [diff] [blame] | 263 | let qcow_image = QcowFile::from(raw_image).map_err(Error::QcowDeviceCreate)?; |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 264 | Box::new( |
| 265 | devices::virtio::Block::new(qcow_image, disk.read_only) |
David Tolnay | 5bbbf61 | 2018-12-01 17:49:30 -0800 | [diff] [blame] | 266 | .map_err(Error::BlockDeviceNew)?, |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 267 | ) |
Dylan Reid | 88624f8 | 2018-01-11 09:20:16 -0800 | [diff] [blame] | 268 | } |
| 269 | }; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 270 | let jail = if cfg.multiprocess { |
| 271 | let policy_path: PathBuf = cfg.seccomp_policy_dir.join("block_device.policy"); |
| 272 | Some(create_base_minijail(empty_root_path, &policy_path)?) |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 273 | } else { |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 274 | None |
| 275 | }; |
| 276 | |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 277 | devs.push(VirtioDeviceStub { |
| 278 | dev: block_box, |
| 279 | jail, |
| 280 | }); |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 281 | } |
| 282 | |
| 283 | let rng_box = Box::new(devices::virtio::Rng::new().map_err(Error::RngDeviceNew)?); |
| 284 | let rng_jail = if cfg.multiprocess { |
| 285 | let policy_path: PathBuf = cfg.seccomp_policy_dir.join("rng_device.policy"); |
| 286 | Some(create_base_minijail(empty_root_path, &policy_path)?) |
| 287 | } else { |
| 288 | None |
| 289 | }; |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 290 | devs.push(VirtioDeviceStub { |
| 291 | dev: rng_box, |
| 292 | jail: rng_jail, |
| 293 | }); |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 294 | |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 295 | let balloon_box = Box::new( |
| 296 | devices::virtio::Balloon::new(balloon_device_socket).map_err(Error::BalloonDeviceNew)?, |
| 297 | ); |
Dylan Reid | 295ccac | 2017-11-06 14:06:24 -0800 | [diff] [blame] | 298 | let balloon_jail = if cfg.multiprocess { |
| 299 | let policy_path: PathBuf = cfg.seccomp_policy_dir.join("balloon_device.policy"); |
| 300 | Some(create_base_minijail(empty_root_path, &policy_path)?) |
| 301 | } else { |
| 302 | None |
| 303 | }; |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 304 | devs.push(VirtioDeviceStub { |
| 305 | dev: balloon_box, |
| 306 | jail: balloon_jail, |
| 307 | }); |
Dylan Reid | 295ccac | 2017-11-06 14:06:24 -0800 | [diff] [blame] | 308 | |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 309 | // We checked above that if the IP is defined, then the netmask is, too. |
Chirantan Ekbote | 5f78721 | 2018-05-31 15:31:31 -0700 | [diff] [blame] | 310 | if let Some(tap_fd) = cfg.tap_fd { |
| 311 | // Safe because we ensure that we get a unique handle to the fd. |
| 312 | let tap = unsafe { Tap::from_raw_fd(validate_raw_fd(tap_fd)?) }; |
David Tolnay | 5bbbf61 | 2018-12-01 17:49:30 -0800 | [diff] [blame] | 313 | let net_box = Box::new(devices::virtio::Net::from(tap).map_err(Error::NetDeviceNew)?); |
Chirantan Ekbote | 5f78721 | 2018-05-31 15:31:31 -0700 | [diff] [blame] | 314 | |
| 315 | let jail = if cfg.multiprocess { |
| 316 | let policy_path: PathBuf = cfg.seccomp_policy_dir.join("net_device.policy"); |
| 317 | |
| 318 | Some(create_base_minijail(empty_root_path, &policy_path)?) |
| 319 | } else { |
| 320 | None |
| 321 | }; |
| 322 | |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 323 | devs.push(VirtioDeviceStub { dev: net_box, jail }); |
Chirantan Ekbote | 5f78721 | 2018-05-31 15:31:31 -0700 | [diff] [blame] | 324 | } else if let Some(host_ip) = cfg.host_ip { |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 325 | if let Some(netmask) = cfg.netmask { |
Stephen Barber | 308ff60 | 2018-02-13 22:47:07 -0800 | [diff] [blame] | 326 | if let Some(mac_address) = cfg.mac_address { |
| 327 | let net_box: Box<devices::virtio::VirtioDevice> = if cfg.vhost_net { |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 328 | Box::new( |
| 329 | devices::virtio::vhost::Net::<Tap, vhost::Net<Tap>>::new( |
| 330 | host_ip, |
| 331 | netmask, |
| 332 | mac_address, |
| 333 | &mem, |
David Tolnay | 2bac1e7 | 2018-12-12 14:33:42 -0800 | [diff] [blame] | 334 | ) |
| 335 | .map_err(Error::VhostNetDeviceNew)?, |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 336 | ) |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 337 | } else { |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 338 | Box::new( |
| 339 | devices::virtio::Net::<Tap>::new(host_ip, netmask, mac_address) |
David Tolnay | 5bbbf61 | 2018-12-01 17:49:30 -0800 | [diff] [blame] | 340 | .map_err(Error::NetDeviceNew)?, |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 341 | ) |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 342 | }; |
| 343 | |
Stephen Barber | 308ff60 | 2018-02-13 22:47:07 -0800 | [diff] [blame] | 344 | let jail = if cfg.multiprocess { |
| 345 | let policy_path: PathBuf = if cfg.vhost_net { |
| 346 | cfg.seccomp_policy_dir.join("vhost_net_device.policy") |
| 347 | } else { |
| 348 | cfg.seccomp_policy_dir.join("net_device.policy") |
| 349 | }; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 350 | |
Stephen Barber | 308ff60 | 2018-02-13 22:47:07 -0800 | [diff] [blame] | 351 | Some(create_base_minijail(empty_root_path, &policy_path)?) |
| 352 | } else { |
| 353 | None |
| 354 | }; |
| 355 | |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 356 | devs.push(VirtioDeviceStub { dev: net_box, jail }); |
Stephen Barber | 308ff60 | 2018-02-13 22:47:07 -0800 | [diff] [blame] | 357 | } |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 358 | } |
| 359 | } |
| 360 | |
Zach Reizner | aa57566 | 2018-08-15 10:46:32 -0700 | [diff] [blame] | 361 | #[cfg(feature = "gpu")] |
| 362 | let mut resource_bridge_wl_socket: Option< |
| 363 | devices::virtio::resource_bridge::ResourceRequestSocket, |
| 364 | > = None; |
Zach Reizner | 3a8100a | 2017-09-13 19:15:43 -0700 | [diff] [blame] | 365 | #[cfg(feature = "gpu")] |
| 366 | { |
| 367 | if cfg.gpu { |
David Riley | b22b613 | 2018-08-20 08:11:42 -0700 | [diff] [blame] | 368 | if let Some(wayland_socket_path) = cfg.wayland_socket_path.as_ref() { |
Zach Reizner | aa57566 | 2018-08-15 10:46:32 -0700 | [diff] [blame] | 369 | let (wl_socket, gpu_socket) = |
| 370 | devices::virtio::resource_bridge::pair().map_err(Error::CreateSocket)?; |
| 371 | resource_bridge_wl_socket = Some(wl_socket); |
| 372 | |
David Riley | b22b613 | 2018-08-20 08:11:42 -0700 | [diff] [blame] | 373 | let jailed_wayland_path = Path::new("/wayland-0"); |
| 374 | |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 375 | let gpu_box = Box::new(devices::virtio::Gpu::new( |
| 376 | _exit_evt.try_clone().map_err(Error::CloneEventFd)?, |
Zach Reizner | aa57566 | 2018-08-15 10:46:32 -0700 | [diff] [blame] | 377 | Some(gpu_socket), |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 378 | if cfg.multiprocess { |
| 379 | &jailed_wayland_path |
| 380 | } else { |
| 381 | wayland_socket_path.as_path() |
| 382 | }, |
| 383 | )); |
David Riley | b22b613 | 2018-08-20 08:11:42 -0700 | [diff] [blame] | 384 | |
| 385 | let jail = if cfg.multiprocess { |
| 386 | let policy_path: PathBuf = cfg.seccomp_policy_dir.join("gpu_device.policy"); |
| 387 | let mut jail = create_base_minijail(empty_root_path, &policy_path)?; |
| 388 | |
| 389 | // Create a tmpfs in the device's root directory so that we can bind mount the |
| 390 | // dri directory into it. The size=67108864 is size=64*1024*1024 or size=64MB. |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 391 | jail.mount_with_data( |
| 392 | Path::new("none"), |
| 393 | Path::new("/"), |
| 394 | "tmpfs", |
| 395 | (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as usize, |
| 396 | "size=67108864", |
David Tolnay | 2bac1e7 | 2018-12-12 14:33:42 -0800 | [diff] [blame] | 397 | ) |
| 398 | .unwrap(); |
David Riley | b22b613 | 2018-08-20 08:11:42 -0700 | [diff] [blame] | 399 | |
| 400 | // Device nodes required for DRM. |
| 401 | let sys_dev_char_path = Path::new("/sys/dev/char"); |
| 402 | jail.mount_bind(sys_dev_char_path, sys_dev_char_path, false) |
| 403 | .unwrap(); |
| 404 | let sys_devices_path = Path::new("/sys/devices"); |
| 405 | jail.mount_bind(sys_devices_path, sys_devices_path, false) |
| 406 | .unwrap(); |
| 407 | let drm_dri_path = Path::new("/dev/dri"); |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 408 | jail.mount_bind(drm_dri_path, drm_dri_path, false).unwrap(); |
David Riley | b22b613 | 2018-08-20 08:11:42 -0700 | [diff] [blame] | 409 | |
| 410 | // Libraries that are required when mesa drivers are dynamically loaded. |
| 411 | let lib_path = Path::new("/lib64"); |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 412 | jail.mount_bind(lib_path, lib_path, false).unwrap(); |
David Riley | b22b613 | 2018-08-20 08:11:42 -0700 | [diff] [blame] | 413 | let usr_lib_path = Path::new("/usr/lib64"); |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 414 | jail.mount_bind(usr_lib_path, usr_lib_path, false).unwrap(); |
David Riley | b22b613 | 2018-08-20 08:11:42 -0700 | [diff] [blame] | 415 | |
| 416 | // Bind mount the wayland socket into jail's root. This is necessary since each |
| 417 | // new wayland context must open() the socket. |
| 418 | jail.mount_bind(wayland_socket_path.as_path(), jailed_wayland_path, true) |
| 419 | .unwrap(); |
| 420 | |
| 421 | // Set the uid/gid for the jailed process, and give a basic id map. This |
| 422 | // is required for the above bind mount to work. |
| 423 | let crosvm_user_group = CStr::from_bytes_with_nul(b"crosvm\0").unwrap(); |
| 424 | let crosvm_uid = match get_user_id(&crosvm_user_group) { |
| 425 | Ok(u) => u, |
| 426 | Err(e) => { |
| 427 | warn!("falling back to current user id for gpu: {:?}", e); |
| 428 | geteuid() |
| 429 | } |
| 430 | }; |
| 431 | let crosvm_gid = match get_group_id(&crosvm_user_group) { |
| 432 | Ok(u) => u, |
| 433 | Err(e) => { |
| 434 | warn!("falling back to current group id for gpu: {:?}", e); |
| 435 | getegid() |
| 436 | } |
| 437 | }; |
| 438 | jail.change_uid(crosvm_uid); |
| 439 | jail.change_gid(crosvm_gid); |
| 440 | jail.uidmap(&format!("{0} {0} 1", crosvm_uid)) |
| 441 | .map_err(Error::SettingUidMap)?; |
| 442 | jail.gidmap(&format!("{0} {0} 1", crosvm_gid)) |
| 443 | .map_err(Error::SettingGidMap)?; |
| 444 | |
| 445 | Some(jail) |
| 446 | } else { |
| 447 | None |
| 448 | }; |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 449 | devs.push(VirtioDeviceStub { dev: gpu_box, jail }); |
David Riley | b22b613 | 2018-08-20 08:11:42 -0700 | [diff] [blame] | 450 | } |
Zach Reizner | 3a8100a | 2017-09-13 19:15:43 -0700 | [diff] [blame] | 451 | } |
| 452 | } |
| 453 | |
Zach Reizner | aa57566 | 2018-08-15 10:46:32 -0700 | [diff] [blame] | 454 | if let Some(wayland_socket_path) = cfg.wayland_socket_path.as_ref() { |
| 455 | let wayland_socket_dir = wayland_socket_path |
| 456 | .parent() |
| 457 | .ok_or(Error::InvalidWaylandPath)?; |
| 458 | let wayland_socket_name = wayland_socket_path |
| 459 | .file_name() |
| 460 | .ok_or(Error::InvalidWaylandPath)?; |
| 461 | let jailed_wayland_dir = Path::new("/wayland"); |
| 462 | let jailed_wayland_path = jailed_wayland_dir.join(wayland_socket_name); |
| 463 | |
| 464 | #[cfg(not(feature = "gpu"))] |
| 465 | let resource_bridge_wl_socket = None; |
| 466 | |
| 467 | let wl_box = Box::new( |
| 468 | devices::virtio::Wl::new( |
| 469 | if cfg.multiprocess { |
| 470 | &jailed_wayland_path |
| 471 | } else { |
| 472 | wayland_socket_path.as_path() |
| 473 | }, |
| 474 | wayland_device_socket, |
| 475 | resource_bridge_wl_socket, |
David Tolnay | 2bac1e7 | 2018-12-12 14:33:42 -0800 | [diff] [blame] | 476 | ) |
| 477 | .map_err(Error::WaylandDeviceNew)?, |
Zach Reizner | aa57566 | 2018-08-15 10:46:32 -0700 | [diff] [blame] | 478 | ); |
| 479 | |
| 480 | let jail = if cfg.multiprocess { |
| 481 | let policy_path: PathBuf = cfg.seccomp_policy_dir.join("wl_device.policy"); |
| 482 | let mut jail = create_base_minijail(empty_root_path, &policy_path)?; |
| 483 | |
| 484 | // Create a tmpfs in the device's root directory so that we can bind mount the wayland |
| 485 | // socket directory into it. The size=67108864 is size=64*1024*1024 or size=64MB. |
| 486 | jail.mount_with_data( |
| 487 | Path::new("none"), |
| 488 | Path::new("/"), |
| 489 | "tmpfs", |
| 490 | (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as usize, |
| 491 | "size=67108864", |
David Tolnay | 2bac1e7 | 2018-12-12 14:33:42 -0800 | [diff] [blame] | 492 | ) |
| 493 | .unwrap(); |
Zach Reizner | aa57566 | 2018-08-15 10:46:32 -0700 | [diff] [blame] | 494 | |
| 495 | // Bind mount the wayland socket's directory into jail's root. This is necessary since |
| 496 | // each new wayland context must open() the socket. If the wayland socket is ever |
| 497 | // destroyed and remade in the same host directory, new connections will be possible |
| 498 | // without restarting the wayland device. |
| 499 | jail.mount_bind(wayland_socket_dir, jailed_wayland_dir, true) |
| 500 | .unwrap(); |
| 501 | |
| 502 | // Set the uid/gid for the jailed process, and give a basic id map. This |
| 503 | // is required for the above bind mount to work. |
| 504 | let crosvm_user_group = CStr::from_bytes_with_nul(b"crosvm\0").unwrap(); |
| 505 | let crosvm_uid = match get_user_id(&crosvm_user_group) { |
| 506 | Ok(u) => u, |
| 507 | Err(e) => { |
| 508 | warn!("falling back to current user id for Wayland: {:?}", e); |
| 509 | geteuid() |
| 510 | } |
| 511 | }; |
| 512 | let crosvm_gid = match get_group_id(&crosvm_user_group) { |
| 513 | Ok(u) => u, |
| 514 | Err(e) => { |
| 515 | warn!("falling back to current group id for Wayland: {:?}", e); |
| 516 | getegid() |
| 517 | } |
| 518 | }; |
| 519 | jail.change_uid(crosvm_uid); |
| 520 | jail.change_gid(crosvm_gid); |
| 521 | jail.uidmap(&format!("{0} {0} 1", crosvm_uid)) |
| 522 | .map_err(Error::SettingUidMap)?; |
| 523 | jail.gidmap(&format!("{0} {0} 1", crosvm_gid)) |
| 524 | .map_err(Error::SettingGidMap)?; |
| 525 | |
| 526 | Some(jail) |
| 527 | } else { |
| 528 | None |
| 529 | }; |
| 530 | devs.push(VirtioDeviceStub { dev: wl_box, jail }); |
| 531 | } |
| 532 | |
| 533 | if let Some(cid) = cfg.cid { |
| 534 | let vsock_box = Box::new( |
| 535 | devices::virtio::vhost::Vsock::new(cid, &mem).map_err(Error::VhostVsockDeviceNew)?, |
| 536 | ); |
| 537 | |
| 538 | let jail = if cfg.multiprocess { |
| 539 | let policy_path: PathBuf = cfg.seccomp_policy_dir.join("vhost_vsock_device.policy"); |
| 540 | |
| 541 | Some(create_base_minijail(empty_root_path, &policy_path)?) |
| 542 | } else { |
| 543 | None |
| 544 | }; |
| 545 | |
| 546 | devs.push(VirtioDeviceStub { |
| 547 | dev: vsock_box, |
| 548 | jail, |
| 549 | }); |
| 550 | } |
| 551 | |
Chirantan Ekbote | ebd5681 | 2018-04-16 19:32:04 -0700 | [diff] [blame] | 552 | let chronos_user_group = CStr::from_bytes_with_nul(b"chronos\0").unwrap(); |
| 553 | let chronos_uid = match get_user_id(&chronos_user_group) { |
| 554 | Ok(u) => u, |
| 555 | Err(e) => { |
| 556 | warn!("falling back to current user id for 9p: {:?}", e); |
| 557 | geteuid() |
| 558 | } |
| 559 | }; |
| 560 | let chronos_gid = match get_group_id(&chronos_user_group) { |
| 561 | Ok(u) => u, |
| 562 | Err(e) => { |
| 563 | warn!("falling back to current group id for 9p: {:?}", e); |
| 564 | getegid() |
| 565 | } |
| 566 | }; |
| 567 | |
| 568 | for &(ref src, ref tag) in &cfg.shared_dirs { |
| 569 | let (jail, root) = if cfg.multiprocess { |
| 570 | let policy_path: PathBuf = cfg.seccomp_policy_dir.join("9p_device.policy"); |
| 571 | let mut jail = create_base_minijail(empty_root_path, &policy_path)?; |
| 572 | |
| 573 | // The shared directory becomes the root of the device's file system. |
| 574 | let root = Path::new("/"); |
| 575 | jail.mount_bind(&src, root, true).unwrap(); |
| 576 | |
| 577 | // Set the uid/gid for the jailed process, and give a basic id map. This |
| 578 | // is required for the above bind mount to work. |
| 579 | jail.change_uid(chronos_uid); |
| 580 | jail.change_gid(chronos_gid); |
| 581 | jail.uidmap(&format!("{0} {0} 1", chronos_uid)) |
| 582 | .map_err(Error::SettingUidMap)?; |
| 583 | jail.gidmap(&format!("{0} {0} 1", chronos_gid)) |
| 584 | .map_err(Error::SettingGidMap)?; |
| 585 | |
| 586 | (Some(jail), root) |
| 587 | } else { |
| 588 | // There's no bind mount so we tell the server to treat the source directory as the |
| 589 | // root. The double deref here converts |src| from a &PathBuf into a &Path. |
| 590 | (None, &**src) |
| 591 | }; |
| 592 | |
| 593 | let p9_box = Box::new(devices::virtio::P9::new(root, tag).map_err(Error::P9DeviceNew)?); |
| 594 | |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 595 | devs.push(VirtioDeviceStub { dev: p9_box, jail }); |
Chirantan Ekbote | ebd5681 | 2018-04-16 19:32:04 -0700 | [diff] [blame] | 596 | } |
| 597 | |
Daniel Verkamp | 8eceba3 | 2018-10-18 16:45:13 -0700 | [diff] [blame] | 598 | let mut pci_devices: Vec<(Box<PciDevice + 'static>, Option<Minijail>)> = Vec::new(); |
Daniel Verkamp | 56f283b | 2018-10-05 11:40:59 -0700 | [diff] [blame] | 599 | for stub in devs { |
| 600 | let pci_dev = |
| 601 | Box::new(VirtioPciDevice::new((*mem).clone(), stub.dev).map_err(Error::VirtioPciDev)?); |
Daniel Verkamp | 8eceba3 | 2018-10-18 16:45:13 -0700 | [diff] [blame] | 602 | pci_devices.push((pci_dev, stub.jail)); |
Daniel Verkamp | 56f283b | 2018-10-05 11:40:59 -0700 | [diff] [blame] | 603 | } |
| 604 | |
| 605 | Ok(pci_devices) |
Sonny Rao | bb7da42 | 2018-02-13 20:37:48 -0800 | [diff] [blame] | 606 | } |
| 607 | |
Mark Ryan | 6ed5aea | 2018-04-20 13:52:35 +0100 | [diff] [blame] | 608 | fn setup_vcpu_signal_handler() -> Result<()> { |
| 609 | unsafe { |
| 610 | extern "C" fn handle_signal() {} |
| 611 | // Our signal handler does nothing and is trivially async signal safe. |
| 612 | register_signal_handler(SIGRTMIN() + 0, handle_signal) |
| 613 | .map_err(Error::RegisterSignalHandler)?; |
| 614 | } |
| 615 | block_signal(SIGRTMIN() + 0).map_err(Error::BlockSignal)?; |
| 616 | Ok(()) |
| 617 | } |
| 618 | |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 619 | fn run_vcpu( |
| 620 | vcpu: Vcpu, |
| 621 | cpu_id: u32, |
| 622 | start_barrier: Arc<Barrier>, |
| 623 | io_bus: devices::Bus, |
| 624 | mmio_bus: devices::Bus, |
| 625 | exit_evt: EventFd, |
| 626 | kill_signaled: Arc<AtomicBool>, |
| 627 | ) -> Result<JoinHandle<()>> { |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 628 | thread::Builder::new() |
| 629 | .name(format!("crosvm_vcpu{}", cpu_id)) |
| 630 | .spawn(move || { |
Mark Ryan | 6ed5aea | 2018-04-20 13:52:35 +0100 | [diff] [blame] | 631 | let mut sig_ok = true; |
| 632 | match get_blocked_signals() { |
| 633 | Ok(mut v) => { |
| 634 | v.retain(|&x| x != SIGRTMIN() + 0); |
| 635 | if let Err(e) = vcpu.set_signal_mask(&v) { |
| 636 | error!( |
| 637 | "Failed to set the KVM_SIGNAL_MASK for vcpu {} : {:?}", |
| 638 | cpu_id, e |
| 639 | ); |
| 640 | sig_ok = false; |
| 641 | } |
| 642 | } |
| 643 | Err(e) => { |
| 644 | error!( |
| 645 | "Failed to retrieve signal mask for vcpu {} : {:?}", |
| 646 | cpu_id, e |
| 647 | ); |
| 648 | sig_ok = false; |
| 649 | } |
| 650 | }; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 651 | |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 652 | start_barrier.wait(); |
Mark Ryan | 6ed5aea | 2018-04-20 13:52:35 +0100 | [diff] [blame] | 653 | |
David Tolnay | 8f3a232 | 2018-11-30 17:11:35 -0800 | [diff] [blame] | 654 | if sig_ok { |
| 655 | loop { |
| 656 | match vcpu.run() { |
| 657 | Ok(VcpuExit::IoIn { port, mut size }) => { |
| 658 | let mut data = [0; 8]; |
| 659 | if size > data.len() { |
| 660 | error!("unsupported IoIn size of {} bytes", size); |
| 661 | size = data.len(); |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 662 | } |
David Tolnay | 8f3a232 | 2018-11-30 17:11:35 -0800 | [diff] [blame] | 663 | io_bus.read(port as u64, &mut data[..size]); |
| 664 | if let Err(e) = vcpu.set_data(&data[..size]) { |
| 665 | error!("failed to set return data for IoIn: {:?}", e); |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 666 | } |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 667 | } |
David Tolnay | 8f3a232 | 2018-11-30 17:11:35 -0800 | [diff] [blame] | 668 | Ok(VcpuExit::IoOut { |
| 669 | port, |
| 670 | mut size, |
| 671 | data, |
| 672 | }) => { |
| 673 | if size > data.len() { |
| 674 | error!("unsupported IoOut size of {} bytes", size); |
| 675 | size = data.len(); |
| 676 | } |
| 677 | io_bus.write(port as u64, &data[..size]); |
| 678 | } |
| 679 | Ok(VcpuExit::MmioRead { address, size }) => { |
| 680 | let mut data = [0; 8]; |
| 681 | mmio_bus.read(address, &mut data[..size]); |
| 682 | // Setting data for mmio can not fail. |
| 683 | let _ = vcpu.set_data(&data[..size]); |
| 684 | } |
| 685 | Ok(VcpuExit::MmioWrite { |
| 686 | address, |
| 687 | size, |
| 688 | data, |
| 689 | }) => { |
| 690 | mmio_bus.write(address, &data[..size]); |
| 691 | } |
| 692 | Ok(VcpuExit::Hlt) => break, |
| 693 | Ok(VcpuExit::Shutdown) => break, |
| 694 | Ok(VcpuExit::SystemEvent(_, _)) => |
| 695 | //TODO handle reboot and crash events |
| 696 | { |
| 697 | kill_signaled.store(true, Ordering::SeqCst) |
| 698 | } |
| 699 | Ok(r) => warn!("unexpected vcpu exit: {:?}", r), |
| 700 | Err(e) => match e.errno() { |
| 701 | libc::EAGAIN | libc::EINTR => {} |
| 702 | _ => { |
| 703 | error!("vcpu hit unknown error: {:?}", e); |
| 704 | break; |
| 705 | } |
| 706 | }, |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 707 | } |
David Tolnay | 8f3a232 | 2018-11-30 17:11:35 -0800 | [diff] [blame] | 708 | if kill_signaled.load(Ordering::SeqCst) { |
| 709 | break; |
| 710 | } |
Mark Ryan | 6ed5aea | 2018-04-20 13:52:35 +0100 | [diff] [blame] | 711 | |
David Tolnay | 8f3a232 | 2018-11-30 17:11:35 -0800 | [diff] [blame] | 712 | // Try to clear the signal that we use to kick VCPU if it is |
| 713 | // pending before attempting to handle pause requests. |
| 714 | clear_signal(SIGRTMIN() + 0).expect("failed to clear pending signal"); |
| 715 | } |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 716 | } |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 717 | exit_evt |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 718 | .write(1) |
| 719 | .expect("failed to signal vcpu exit eventfd"); |
David Tolnay | 2bac1e7 | 2018-12-12 14:33:42 -0800 | [diff] [blame] | 720 | }) |
| 721 | .map_err(Error::SpawnVcpu) |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 722 | } |
| 723 | |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 724 | // Reads the contents of a file and converts them into a u64. |
| 725 | fn file_to_u64<P: AsRef<Path>>(path: P) -> io::Result<u64> { |
| 726 | let mut file = File::open(path)?; |
| 727 | |
| 728 | let mut buf = [0u8; 32]; |
| 729 | let count = file.read(&mut buf)?; |
| 730 | |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 731 | let content = |
| 732 | str::from_utf8(&buf[..count]).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; |
| 733 | content |
| 734 | .trim() |
| 735 | .parse() |
| 736 | .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 737 | } |
| 738 | |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 739 | pub fn run_config(cfg: Config) -> Result<()> { |
Daniel Verkamp | aac2813 | 2018-10-15 14:58:48 -0700 | [diff] [blame] | 740 | if cfg.multiprocess { |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 741 | // Printing something to the syslog before entering minijail so that libc's syslogger has a |
| 742 | // chance to open files necessary for its operation, like `/etc/localtime`. After jailing, |
| 743 | // access to those files will not be possible. |
| 744 | info!("crosvm entering multiprocess mode"); |
| 745 | } |
| 746 | |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 747 | // Masking signals is inherently dangerous, since this can persist across clones/execs. Do this |
| 748 | // before any jailed devices have been spawned, so that we can catch any of them that fail very |
| 749 | // quickly. |
| 750 | let sigchld_fd = SignalFd::new(libc::SIGCHLD).map_err(Error::CreateSignalFd)?; |
| 751 | |
| 752 | let components = VmComponents { |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 753 | memory_mb: (cfg.memory.unwrap_or(256) << 20) as u64, |
| 754 | vcpu_count: cfg.vcpu_count.unwrap_or(1), |
| 755 | kernel_image: File::open(cfg.kernel_path.as_path()) |
| 756 | .map_err(|e| Error::OpenKernel(cfg.kernel_path.clone(), e))?, |
Daniel Verkamp | aac2813 | 2018-10-15 14:58:48 -0700 | [diff] [blame] | 757 | extra_kernel_params: cfg.params.clone(), |
| 758 | wayland_dmabuf: cfg.wayland_dmabuf, |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 759 | }; |
| 760 | |
| 761 | let mut control_sockets = Vec::new(); |
| 762 | if let Some(ref path_string) = cfg.socket_path { |
| 763 | let path = Path::new(path_string); |
| 764 | let dgram = UnixDatagram::bind(path).map_err(Error::CreateSocket)?; |
Jingkui Wang | e13b180 | 2018-10-03 13:04:47 -0700 | [diff] [blame] | 765 | control_sockets.push(UnlinkMsgSocket::<VmResponse, VmRequest>::new( |
| 766 | UnlinkUnixDatagram(dgram), |
| 767 | )); |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 768 | }; |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 769 | let (wayland_host_socket, wayland_device_socket) = |
| 770 | UnixDatagram::pair().map_err(Error::CreateSocket)?; |
Jingkui Wang | e13b180 | 2018-10-03 13:04:47 -0700 | [diff] [blame] | 771 | control_sockets.push(UnlinkMsgSocket::<VmResponse, VmRequest>::new( |
| 772 | UnlinkUnixDatagram(wayland_host_socket), |
| 773 | )); |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 774 | // Balloon gets a special socket so balloon requests can be forwarded from the main process. |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 775 | let (balloon_host_socket, balloon_device_socket) = |
| 776 | UnixDatagram::pair().map_err(Error::CreateSocket)?; |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 777 | |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 778 | let linux = Arch::build_vm(components, |m, e| { |
Daniel Verkamp | aac2813 | 2018-10-15 14:58:48 -0700 | [diff] [blame] | 779 | create_virtio_devs(cfg, m, e, wayland_device_socket, balloon_device_socket) |
David Tolnay | 2bac1e7 | 2018-12-12 14:33:42 -0800 | [diff] [blame] | 780 | }) |
| 781 | .map_err(Error::BuildingVm)?; |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 782 | run_control(linux, control_sockets, balloon_host_socket, sigchld_fd) |
Dylan Reid | 0ed91ab | 2018-05-31 15:42:18 -0700 | [diff] [blame] | 783 | } |
| 784 | |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 785 | fn run_control( |
| 786 | mut linux: RunnableLinuxVm, |
Jingkui Wang | e13b180 | 2018-10-03 13:04:47 -0700 | [diff] [blame] | 787 | control_sockets: Vec<UnlinkMsgSocket<VmResponse, VmRequest>>, |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 788 | balloon_host_socket: UnixDatagram, |
| 789 | sigchld_fd: SignalFd, |
| 790 | ) -> Result<()> { |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 791 | // Paths to get the currently available memory and the low memory threshold. |
David Tolnay | 5bbbf61 | 2018-12-01 17:49:30 -0800 | [diff] [blame] | 792 | const LOWMEM_MARGIN: &str = "/sys/kernel/mm/chromeos-low_mem/margin"; |
| 793 | const LOWMEM_AVAILABLE: &str = "/sys/kernel/mm/chromeos-low_mem/available"; |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 794 | |
| 795 | // The amount of additional memory to claim back from the VM whenever the system is |
| 796 | // low on memory. |
| 797 | const ONE_GB: u64 = (1 << 30); |
| 798 | |
Dylan Reid | 0ed91ab | 2018-05-31 15:42:18 -0700 | [diff] [blame] | 799 | let max_balloon_memory = match linux.vm.get_memory().memory_size() { |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 800 | // If the VM has at least 1.5 GB, the balloon driver can consume all but the last 1 GB. |
| 801 | n if n >= (ONE_GB / 2) * 3 => n - ONE_GB, |
| 802 | // Otherwise, if the VM has at least 500MB the balloon driver will consume at most |
| 803 | // half of it. |
| 804 | n if n >= (ONE_GB / 2) => n / 2, |
| 805 | // Otherwise, the VM is too small for us to take memory away from it. |
| 806 | _ => 0, |
| 807 | }; |
| 808 | let mut current_balloon_memory: u64 = 0; |
| 809 | let balloon_memory_increment: u64 = max_balloon_memory / 16; |
| 810 | |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 811 | #[derive(PollToken)] |
| 812 | enum Token { |
| 813 | Exit, |
| 814 | Stdin, |
| 815 | ChildSignal, |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 816 | CheckAvailableMemory, |
| 817 | LowMemory, |
| 818 | LowmemTimer, |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 819 | VmControl { index: usize }, |
| 820 | } |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 821 | |
| 822 | let stdin_handle = stdin(); |
| 823 | let stdin_lock = stdin_handle.lock(); |
| 824 | stdin_lock |
| 825 | .set_raw_mode() |
| 826 | .expect("failed to set terminal raw mode"); |
| 827 | |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 828 | let poll_ctx = PollContext::new().map_err(Error::CreatePollContext)?; |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 829 | poll_ctx |
| 830 | .add(&linux.exit_evt, Token::Exit) |
| 831 | .map_err(Error::PollContextAdd)?; |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 832 | if let Err(e) = poll_ctx.add(&stdin_handle, Token::Stdin) { |
| 833 | warn!("failed to add stdin to poll context: {:?}", e); |
| 834 | } |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 835 | poll_ctx |
| 836 | .add(&sigchld_fd, Token::ChildSignal) |
| 837 | .map_err(Error::PollContextAdd)?; |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 838 | for (index, socket) in control_sockets.iter().enumerate() { |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 839 | poll_ctx |
| 840 | .add(socket.as_ref(), Token::VmControl { index }) |
| 841 | .map_err(Error::PollContextAdd)?; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 842 | } |
| 843 | |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 844 | // Watch for low memory notifications and take memory back from the VM. |
Dylan Reid | f11e6ed | 2018-07-31 10:24:06 -0700 | [diff] [blame] | 845 | let low_mem = File::open("/dev/chromeos-low-mem").ok(); |
| 846 | if let Some(ref low_mem) = low_mem { |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 847 | poll_ctx |
| 848 | .add(low_mem, Token::LowMemory) |
| 849 | .map_err(Error::PollContextAdd)?; |
Dylan Reid | f11e6ed | 2018-07-31 10:24:06 -0700 | [diff] [blame] | 850 | } else { |
| 851 | warn!("Unable to open low mem indicator, maybe not a chrome os kernel"); |
| 852 | } |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 853 | |
| 854 | // Used to rate limit balloon requests. |
| 855 | let mut lowmem_timer = TimerFd::new().map_err(Error::CreateTimerFd)?; |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 856 | poll_ctx |
| 857 | .add(&lowmem_timer, Token::LowmemTimer) |
| 858 | .map_err(Error::PollContextAdd)?; |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 859 | |
| 860 | // Used to check whether it's ok to start giving memory back to the VM. |
| 861 | let mut freemem_timer = TimerFd::new().map_err(Error::CreateTimerFd)?; |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 862 | poll_ctx |
| 863 | .add(&freemem_timer, Token::CheckAvailableMemory) |
| 864 | .map_err(Error::PollContextAdd)?; |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 865 | |
| 866 | // Used to add jitter to timer values so that we don't have a thundering herd problem when |
| 867 | // multiple VMs are running. |
| 868 | let mut rng = thread_rng(); |
| 869 | let lowmem_jitter_ms = Range::new(0, 200); |
| 870 | let freemem_jitter_secs = Range::new(0, 12); |
| 871 | let interval_jitter_secs = Range::new(0, 6); |
| 872 | |
Daniel Verkamp | 37c4a78 | 2019-01-04 10:44:17 -0800 | [diff] [blame] | 873 | let mut vcpu_handles = Vec::with_capacity(linux.vcpus.len()); |
| 874 | let vcpu_thread_barrier = Arc::new(Barrier::new(linux.vcpus.len() + 1)); |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 875 | let kill_signaled = Arc::new(AtomicBool::new(false)); |
| 876 | setup_vcpu_signal_handler()?; |
| 877 | for (cpu_id, vcpu) in linux.vcpus.into_iter().enumerate() { |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 878 | let handle = run_vcpu( |
| 879 | vcpu, |
| 880 | cpu_id as u32, |
| 881 | vcpu_thread_barrier.clone(), |
| 882 | linux.io_bus.clone(), |
| 883 | linux.mmio_bus.clone(), |
| 884 | linux.exit_evt.try_clone().map_err(Error::CloneEventFd)?, |
| 885 | kill_signaled.clone(), |
| 886 | )?; |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 887 | vcpu_handles.push(handle); |
| 888 | } |
| 889 | vcpu_thread_barrier.wait(); |
| 890 | |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 891 | 'poll: loop { |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 892 | let events = { |
| 893 | match poll_ctx.wait() { |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 894 | Ok(v) => v, |
| 895 | Err(e) => { |
| 896 | error!("failed to poll: {:?}", e); |
| 897 | break; |
| 898 | } |
| 899 | } |
| 900 | }; |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 901 | for event in events.iter_readable() { |
| 902 | match event.token() { |
| 903 | Token::Exit => { |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 904 | info!("vcpu requested shutdown"); |
| 905 | break 'poll; |
| 906 | } |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 907 | Token::Stdin => { |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 908 | let mut out = [0u8; 64]; |
| 909 | match stdin_lock.read_raw(&mut out[..]) { |
| 910 | Ok(0) => { |
| 911 | // Zero-length read indicates EOF. Remove from pollables. |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 912 | let _ = poll_ctx.delete(&stdin_handle); |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 913 | } |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 914 | Err(e) => { |
| 915 | warn!("error while reading stdin: {:?}", e); |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 916 | let _ = poll_ctx.delete(&stdin_handle); |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 917 | } |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 918 | Ok(count) => { |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 919 | linux |
| 920 | .stdio_serial |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 921 | .lock() |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 922 | .queue_input_bytes(&out[..count]) |
| 923 | .expect("failed to queue bytes into serial port"); |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 924 | } |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 925 | } |
| 926 | } |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 927 | Token::ChildSignal => { |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 928 | // Print all available siginfo structs, then exit the loop. |
David Tolnay | f503276 | 2018-12-03 10:46:45 -0800 | [diff] [blame] | 929 | while let Some(siginfo) = sigchld_fd.read().map_err(Error::SignalFd)? { |
| 930 | error!( |
| 931 | "child {} died: signo {}, status {}, code {}", |
| 932 | siginfo.ssi_pid, |
| 933 | siginfo.ssi_signo, |
| 934 | siginfo.ssi_status, |
| 935 | siginfo.ssi_code |
| 936 | ); |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 937 | } |
David Tolnay | f503276 | 2018-12-03 10:46:45 -0800 | [diff] [blame] | 938 | break 'poll; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 939 | } |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 940 | Token::CheckAvailableMemory => { |
| 941 | // Acknowledge the timer. |
| 942 | freemem_timer.wait().map_err(Error::TimerFd)?; |
| 943 | if current_balloon_memory == 0 { |
| 944 | // Nothing to see here. |
| 945 | if let Err(e) = freemem_timer.clear() { |
| 946 | warn!("unable to clear available memory check timer: {}", e); |
| 947 | } |
| 948 | continue; |
| 949 | } |
| 950 | |
| 951 | // Otherwise see if we can free up some memory. |
| 952 | let margin = file_to_u64(LOWMEM_MARGIN).map_err(Error::ReadLowmemMargin)?; |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 953 | let available = |
| 954 | file_to_u64(LOWMEM_AVAILABLE).map_err(Error::ReadLowmemAvailable)?; |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 955 | |
| 956 | // `available` and `margin` are specified in MB while `balloon_memory_increment` is in |
| 957 | // bytes. So to correctly compare them we need to turn the increment value into MB. |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 958 | if available >= margin + 2 * (balloon_memory_increment >> 20) { |
| 959 | current_balloon_memory = |
| 960 | if current_balloon_memory >= balloon_memory_increment { |
| 961 | current_balloon_memory - balloon_memory_increment |
| 962 | } else { |
| 963 | 0 |
| 964 | }; |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 965 | let mut buf = [0u8; mem::size_of::<u64>()]; |
| 966 | LittleEndian::write_u64(&mut buf, current_balloon_memory); |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 967 | if let Err(e) = balloon_host_socket.send(&buf) { |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 968 | warn!("failed to send memory value to balloon device: {}", e); |
| 969 | } |
| 970 | } |
| 971 | } |
| 972 | Token::LowMemory => { |
Dylan Reid | f11e6ed | 2018-07-31 10:24:06 -0700 | [diff] [blame] | 973 | if let Some(ref low_mem) = low_mem { |
| 974 | let old_balloon_memory = current_balloon_memory; |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 975 | current_balloon_memory = min( |
| 976 | current_balloon_memory + balloon_memory_increment, |
| 977 | max_balloon_memory, |
| 978 | ); |
Dylan Reid | f11e6ed | 2018-07-31 10:24:06 -0700 | [diff] [blame] | 979 | if current_balloon_memory != old_balloon_memory { |
| 980 | let mut buf = [0u8; mem::size_of::<u64>()]; |
| 981 | LittleEndian::write_u64(&mut buf, current_balloon_memory); |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 982 | if let Err(e) = balloon_host_socket.send(&buf) { |
Dylan Reid | f11e6ed | 2018-07-31 10:24:06 -0700 | [diff] [blame] | 983 | warn!("failed to send memory value to balloon device: {}", e); |
| 984 | } |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 985 | } |
Dylan Reid | f11e6ed | 2018-07-31 10:24:06 -0700 | [diff] [blame] | 986 | |
| 987 | // Stop polling the lowmem device until the timer fires. |
| 988 | poll_ctx.delete(low_mem).map_err(Error::PollContextDelete)?; |
| 989 | |
| 990 | // Add some jitter to the timer so that if there are multiple VMs running |
| 991 | // they don't all start ballooning at exactly the same time. |
| 992 | let lowmem_dur = |
| 993 | Duration::from_millis(1000 + lowmem_jitter_ms.ind_sample(&mut rng)); |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 994 | lowmem_timer |
| 995 | .reset(lowmem_dur, None) |
| 996 | .map_err(Error::ResetTimerFd)?; |
Dylan Reid | f11e6ed | 2018-07-31 10:24:06 -0700 | [diff] [blame] | 997 | |
| 998 | // Also start a timer to check when we can start giving memory back. Do the |
| 999 | // first check after a minute (with jitter) and subsequent checks after |
| 1000 | // every 30 seconds (with jitter). |
| 1001 | let freemem_dur = |
| 1002 | Duration::from_secs(60 + freemem_jitter_secs.ind_sample(&mut rng)); |
| 1003 | let freemem_int = |
| 1004 | Duration::from_secs(30 + interval_jitter_secs.ind_sample(&mut rng)); |
| 1005 | freemem_timer |
| 1006 | .reset(freemem_dur, Some(freemem_int)) |
| 1007 | .map_err(Error::ResetTimerFd)?; |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 1008 | } |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 1009 | } |
| 1010 | Token::LowmemTimer => { |
| 1011 | // Acknowledge the timer. |
| 1012 | lowmem_timer.wait().map_err(Error::TimerFd)?; |
| 1013 | |
Dylan Reid | f11e6ed | 2018-07-31 10:24:06 -0700 | [diff] [blame] | 1014 | if let Some(ref low_mem) = low_mem { |
| 1015 | // Start polling the lowmem device again. |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1016 | poll_ctx |
| 1017 | .add(low_mem, Token::LowMemory) |
| 1018 | .map_err(Error::PollContextAdd)?; |
Dylan Reid | f11e6ed | 2018-07-31 10:24:06 -0700 | [diff] [blame] | 1019 | } |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 1020 | } |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 1021 | Token::VmControl { index } => { |
Daniel Verkamp | 37c4a78 | 2019-01-04 10:44:17 -0800 | [diff] [blame] | 1022 | if let Some(socket) = control_sockets.get(index) { |
Jingkui Wang | e13b180 | 2018-10-03 13:04:47 -0700 | [diff] [blame] | 1023 | match socket.recv() { |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 1024 | Ok(request) => { |
| 1025 | let mut running = true; |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1026 | let response = request.execute( |
| 1027 | &mut linux.vm, |
| 1028 | &mut linux.resources, |
| 1029 | &mut running, |
| 1030 | &balloon_host_socket, |
| 1031 | ); |
Jingkui Wang | e13b180 | 2018-10-03 13:04:47 -0700 | [diff] [blame] | 1032 | if let Err(e) = socket.send(&response) { |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 1033 | error!("failed to send VmResponse: {:?}", e); |
| 1034 | } |
| 1035 | if !running { |
| 1036 | info!("control socket requested exit"); |
| 1037 | break 'poll; |
| 1038 | } |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1039 | } |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 1040 | Err(e) => error!("failed to recv VmRequest: {:?}", e), |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1041 | } |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1042 | } |
| 1043 | } |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 1044 | } |
| 1045 | } |
| 1046 | for event in events.iter_hungup() { |
| 1047 | // It's possible more data is readable and buffered while the socket is hungup, so |
| 1048 | // don't delete the socket from the poll context until we're sure all the data is |
| 1049 | // read. |
| 1050 | if !event.readable() { |
| 1051 | match event.token() { |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1052 | Token::Exit => {} |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 1053 | Token::Stdin => { |
| 1054 | let _ = poll_ctx.delete(&stdin_handle); |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1055 | } |
| 1056 | Token::ChildSignal => {} |
| 1057 | Token::CheckAvailableMemory => {} |
| 1058 | Token::LowMemory => {} |
| 1059 | Token::LowmemTimer => {} |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 1060 | Token::VmControl { index } => { |
Daniel Verkamp | 37c4a78 | 2019-01-04 10:44:17 -0800 | [diff] [blame] | 1061 | if let Some(socket) = control_sockets.get(index) { |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 1062 | let _ = poll_ctx.delete(socket.as_ref()); |
| 1063 | } |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1064 | } |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 1065 | } |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1066 | } |
| 1067 | } |
| 1068 | } |
| 1069 | |
| 1070 | // vcpu threads MUST see the kill signaled flag, otherwise they may |
| 1071 | // re-enter the VM. |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 1072 | kill_signaled.store(true, Ordering::SeqCst); |
| 1073 | for handle in vcpu_handles { |
Dmitry Torokhov | cd40533 | 2018-02-16 16:25:54 -0800 | [diff] [blame] | 1074 | match handle.kill(SIGRTMIN() + 0) { |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1075 | Ok(_) => { |
| 1076 | if let Err(e) = handle.join() { |
| 1077 | error!("failed to join vcpu thread: {:?}", e); |
| 1078 | } |
| 1079 | } |
| 1080 | Err(e) => error!("failed to kill vcpu thread: {:?}", e), |
| 1081 | } |
| 1082 | } |
| 1083 | |
| 1084 | stdin_lock |
| 1085 | .set_canon_mode() |
| 1086 | .expect("failed to restore canonical mode for terminal"); |
| 1087 | |
| 1088 | Ok(()) |
| 1089 | } |